]> 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 c = fixed_coef[i];
1167         int e = exp[i];
1168         int v = bap[i];
1169         if (v)
1170         switch (v) {
1171         case 1:
1172             v = sym_quant(c, e, 3);
1173             switch (s->mant1_cnt) {
1174             case 0:
1175                 s->qmant1_ptr = &qmant[i];
1176                 v = 9 * v;
1177                 s->mant1_cnt = 1;
1178                 break;
1179             case 1:
1180                 *s->qmant1_ptr += 3 * v;
1181                 s->mant1_cnt = 2;
1182                 v = 128;
1183                 break;
1184             default:
1185                 *s->qmant1_ptr += v;
1186                 s->mant1_cnt = 0;
1187                 v = 128;
1188                 break;
1189             }
1190             break;
1191         case 2:
1192             v = sym_quant(c, e, 5);
1193             switch (s->mant2_cnt) {
1194             case 0:
1195                 s->qmant2_ptr = &qmant[i];
1196                 v = 25 * v;
1197                 s->mant2_cnt = 1;
1198                 break;
1199             case 1:
1200                 *s->qmant2_ptr += 5 * v;
1201                 s->mant2_cnt = 2;
1202                 v = 128;
1203                 break;
1204             default:
1205                 *s->qmant2_ptr += v;
1206                 s->mant2_cnt = 0;
1207                 v = 128;
1208                 break;
1209             }
1210             break;
1211         case 3:
1212             v = sym_quant(c, e, 7);
1213             break;
1214         case 4:
1215             v = sym_quant(c, e, 11);
1216             switch (s->mant4_cnt) {
1217             case 0:
1218                 s->qmant4_ptr = &qmant[i];
1219                 v = 11 * v;
1220                 s->mant4_cnt = 1;
1221                 break;
1222             default:
1223                 *s->qmant4_ptr += v;
1224                 s->mant4_cnt = 0;
1225                 v = 128;
1226                 break;
1227             }
1228             break;
1229         case 5:
1230             v = sym_quant(c, e, 15);
1231             break;
1232         case 14:
1233             v = asym_quant(c, e, 14);
1234             break;
1235         case 15:
1236             v = asym_quant(c, e, 16);
1237             break;
1238         default:
1239             v = asym_quant(c, e, v - 1);
1240             break;
1241         }
1242         qmant[i] = v;
1243     }
1244 }
1245
1246
1247 /**
1248  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1249  */
1250 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1251 {
1252     int blk, ch, ch0=0, got_cpl;
1253
1254     for (blk = 0; blk < s->num_blocks; blk++) {
1255         AC3Block *block = &s->blocks[blk];
1256         AC3Mant m = { 0 };
1257
1258         got_cpl = !block->cpl_in_use;
1259         for (ch = 1; ch <= s->channels; ch++) {
1260             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1261                 ch0     = ch - 1;
1262                 ch      = CPL_CH;
1263                 got_cpl = 1;
1264             }
1265             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1266                                       s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1267                                       s->ref_bap[ch][blk], block->qmant[ch],
1268                                       s->start_freq[ch], block->end_freq[ch]);
1269             if (ch == CPL_CH)
1270                 ch = ch0;
1271         }
1272     }
1273 }
1274
1275
1276 /**
1277  * Write the AC-3 frame header to the output bitstream.
1278  */
1279 static void ac3_output_frame_header(AC3EncodeContext *s)
1280 {
1281     AC3EncOptions *opt = &s->options;
1282
1283     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1284     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1285     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1286     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1287     put_bits(&s->pb, 5,  s->bitstream_id);
1288     put_bits(&s->pb, 3,  s->bitstream_mode);
1289     put_bits(&s->pb, 3,  s->channel_mode);
1290     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1291         put_bits(&s->pb, 2, s->center_mix_level);
1292     if (s->channel_mode & 0x04)
1293         put_bits(&s->pb, 2, s->surround_mix_level);
1294     if (s->channel_mode == AC3_CHMODE_STEREO)
1295         put_bits(&s->pb, 2, opt->dolby_surround_mode);
1296     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1297     put_bits(&s->pb, 5, -opt->dialogue_level);
1298     put_bits(&s->pb, 1, 0);         /* no compression control word */
1299     put_bits(&s->pb, 1, 0);         /* no lang code */
1300     put_bits(&s->pb, 1, opt->audio_production_info);
1301     if (opt->audio_production_info) {
1302         put_bits(&s->pb, 5, opt->mixing_level - 80);
1303         put_bits(&s->pb, 2, opt->room_type);
1304     }
1305     put_bits(&s->pb, 1, opt->copyright);
1306     put_bits(&s->pb, 1, opt->original);
1307     if (s->bitstream_id == 6) {
1308         /* alternate bit stream syntax */
1309         put_bits(&s->pb, 1, opt->extended_bsi_1);
1310         if (opt->extended_bsi_1) {
1311             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1312             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1313             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1314             put_bits(&s->pb, 3, s->loro_center_mix_level);
1315             put_bits(&s->pb, 3, s->loro_surround_mix_level);
1316         }
1317         put_bits(&s->pb, 1, opt->extended_bsi_2);
1318         if (opt->extended_bsi_2) {
1319             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1320             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1321             put_bits(&s->pb, 1, opt->ad_converter_type);
1322             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1323         }
1324     } else {
1325     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1326     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1327     }
1328     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1329 }
1330
1331
1332 /**
1333  * Write one audio block to the output bitstream.
1334  */
1335 static void output_audio_block(AC3EncodeContext *s, int blk)
1336 {
1337     int ch, i, baie, bnd, got_cpl;
1338     int av_uninit(ch0);
1339     AC3Block *block = &s->blocks[blk];
1340
1341     /* block switching */
1342     if (!s->eac3) {
1343         for (ch = 0; ch < s->fbw_channels; ch++)
1344             put_bits(&s->pb, 1, 0);
1345     }
1346
1347     /* dither flags */
1348     if (!s->eac3) {
1349         for (ch = 0; ch < s->fbw_channels; ch++)
1350             put_bits(&s->pb, 1, 1);
1351     }
1352
1353     /* dynamic range codes */
1354     put_bits(&s->pb, 1, 0);
1355
1356     /* spectral extension */
1357     if (s->eac3)
1358         put_bits(&s->pb, 1, 0);
1359
1360     /* channel coupling */
1361     if (!s->eac3)
1362         put_bits(&s->pb, 1, block->new_cpl_strategy);
1363     if (block->new_cpl_strategy) {
1364         if (!s->eac3)
1365             put_bits(&s->pb, 1, block->cpl_in_use);
1366         if (block->cpl_in_use) {
1367             int start_sub, end_sub;
1368             if (s->eac3)
1369                 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1370             if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1371                 for (ch = 1; ch <= s->fbw_channels; ch++)
1372                     put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1373             }
1374             if (s->channel_mode == AC3_CHMODE_STEREO)
1375                 put_bits(&s->pb, 1, 0); /* phase flags in use */
1376             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1377             end_sub   = (s->cpl_end_freq       - 37) / 12;
1378             put_bits(&s->pb, 4, start_sub);
1379             put_bits(&s->pb, 4, end_sub - 3);
1380             /* coupling band structure */
1381             if (s->eac3) {
1382                 put_bits(&s->pb, 1, 0); /* use default */
1383             } else {
1384                 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1385                     put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1386             }
1387         }
1388     }
1389
1390     /* coupling coordinates */
1391     if (block->cpl_in_use) {
1392         for (ch = 1; ch <= s->fbw_channels; ch++) {
1393             if (block->channel_in_cpl[ch]) {
1394                 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
1395                     put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
1396                 if (block->new_cpl_coords[ch]) {
1397                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1398                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1399                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1400                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1401                     }
1402                 }
1403             }
1404         }
1405     }
1406
1407     /* stereo rematrixing */
1408     if (s->channel_mode == AC3_CHMODE_STEREO) {
1409         if (!s->eac3 || blk > 0)
1410             put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1411         if (block->new_rematrixing_strategy) {
1412             /* rematrixing flags */
1413             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1414                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1415         }
1416     }
1417
1418     /* exponent strategy */
1419     if (!s->eac3) {
1420         for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1421             put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1422         if (s->lfe_on)
1423             put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1424     }
1425
1426     /* bandwidth */
1427     for (ch = 1; ch <= s->fbw_channels; ch++) {
1428         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1429             put_bits(&s->pb, 6, s->bandwidth_code);
1430     }
1431
1432     /* exponents */
1433     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1434         int nb_groups;
1435         int cpl = (ch == CPL_CH);
1436
1437         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1438             continue;
1439
1440         /* DC exponent */
1441         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1442
1443         /* exponent groups */
1444         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1445         for (i = 1; i <= nb_groups; i++)
1446             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1447
1448         /* gain range info */
1449         if (ch != s->lfe_channel && !cpl)
1450             put_bits(&s->pb, 2, 0);
1451     }
1452
1453     /* bit allocation info */
1454     if (!s->eac3) {
1455         baie = (blk == 0);
1456         put_bits(&s->pb, 1, baie);
1457         if (baie) {
1458             put_bits(&s->pb, 2, s->slow_decay_code);
1459             put_bits(&s->pb, 2, s->fast_decay_code);
1460             put_bits(&s->pb, 2, s->slow_gain_code);
1461             put_bits(&s->pb, 2, s->db_per_bit_code);
1462             put_bits(&s->pb, 3, s->floor_code);
1463         }
1464     }
1465
1466     /* snr offset */
1467     if (!s->eac3) {
1468         put_bits(&s->pb, 1, block->new_snr_offsets);
1469         if (block->new_snr_offsets) {
1470             put_bits(&s->pb, 6, s->coarse_snr_offset);
1471             for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1472                 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1473                 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1474             }
1475         }
1476     } else {
1477         put_bits(&s->pb, 1, 0); /* no converter snr offset */
1478     }
1479
1480     /* coupling leak */
1481     if (block->cpl_in_use) {
1482         if (!s->eac3 || block->new_cpl_leak != 2)
1483             put_bits(&s->pb, 1, block->new_cpl_leak);
1484         if (block->new_cpl_leak) {
1485             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1486             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1487         }
1488     }
1489
1490     if (!s->eac3) {
1491         put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1492         put_bits(&s->pb, 1, 0); /* no data to skip */
1493     }
1494
1495     /* mantissas */
1496     got_cpl = !block->cpl_in_use;
1497     for (ch = 1; ch <= s->channels; ch++) {
1498         int b, q;
1499
1500         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1501             ch0     = ch - 1;
1502             ch      = CPL_CH;
1503             got_cpl = 1;
1504         }
1505         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1506             q = block->qmant[ch][i];
1507             b = s->ref_bap[ch][blk][i];
1508             switch (b) {
1509             case 0:                                          break;
1510             case 1: if (q != 128) put_bits (&s->pb,   5, q); break;
1511             case 2: if (q != 128) put_bits (&s->pb,   7, q); break;
1512             case 3:               put_sbits(&s->pb,   3, q); break;
1513             case 4: if (q != 128) put_bits (&s->pb,   7, q); break;
1514             case 14:              put_sbits(&s->pb,  14, q); break;
1515             case 15:              put_sbits(&s->pb,  16, q); break;
1516             default:              put_sbits(&s->pb, b-1, q); break;
1517             }
1518         }
1519         if (ch == CPL_CH)
1520             ch = ch0;
1521     }
1522 }
1523
1524
1525 /** CRC-16 Polynomial */
1526 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1527
1528
1529 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1530 {
1531     unsigned int c;
1532
1533     c = 0;
1534     while (a) {
1535         if (a & 1)
1536             c ^= b;
1537         a = a >> 1;
1538         b = b << 1;
1539         if (b & (1 << 16))
1540             b ^= poly;
1541     }
1542     return c;
1543 }
1544
1545
1546 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1547 {
1548     unsigned int r;
1549     r = 1;
1550     while (n) {
1551         if (n & 1)
1552             r = mul_poly(r, a, poly);
1553         a = mul_poly(a, a, poly);
1554         n >>= 1;
1555     }
1556     return r;
1557 }
1558
1559
1560 /**
1561  * Fill the end of the frame with 0's and compute the two CRCs.
1562  */
1563 static void output_frame_end(AC3EncodeContext *s)
1564 {
1565     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1566     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1567     uint8_t *frame;
1568
1569     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1570
1571     /* pad the remainder of the frame with zeros */
1572     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1573     flush_put_bits(&s->pb);
1574     frame = s->pb.buf;
1575     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1576     av_assert2(pad_bytes >= 0);
1577     if (pad_bytes > 0)
1578         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1579
1580     if (s->eac3) {
1581         /* compute crc2 */
1582         crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1583     } else {
1584     /* compute crc1 */
1585     /* this is not so easy because it is at the beginning of the data... */
1586     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1587     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1588     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1589     AV_WB16(frame + 2, crc1);
1590
1591     /* compute crc2 */
1592     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1593                           s->frame_size - frame_size_58 - 3);
1594     }
1595     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1596     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1597     if (crc2 == 0x770B) {
1598         frame[s->frame_size - 3] ^= 0x1;
1599         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1600     }
1601     crc2 = av_bswap16(crc2);
1602     AV_WB16(frame + s->frame_size - 2, crc2);
1603 }
1604
1605
1606 /**
1607  * Write the frame to the output bitstream.
1608  */
1609 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1610 {
1611     int blk;
1612
1613     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1614
1615     s->output_frame_header(s);
1616
1617     for (blk = 0; blk < s->num_blocks; blk++)
1618         output_audio_block(s, blk);
1619
1620     output_frame_end(s);
1621 }
1622
1623
1624 static void dprint_options(AC3EncodeContext *s)
1625 {
1626 #ifdef DEBUG
1627     AVCodecContext *avctx = s->avctx;
1628     AC3EncOptions *opt = &s->options;
1629     char strbuf[32];
1630
1631     switch (s->bitstream_id) {
1632     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
1633     case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
1634     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
1635     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1636     case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
1637     default: snprintf(strbuf, 32, "ERROR");
1638     }
1639     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1640     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1641     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1642     av_dlog(avctx, "channel_layout: %s\n", strbuf);
1643     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1644     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1645     av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1646     if (s->cutoff)
1647         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1648
1649     av_dlog(avctx, "per_frame_metadata: %s\n",
1650             opt->allow_per_frame_metadata?"on":"off");
1651     if (s->has_center)
1652         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1653                 s->center_mix_level);
1654     else
1655         av_dlog(avctx, "center_mixlev: {not written}\n");
1656     if (s->has_surround)
1657         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1658                 s->surround_mix_level);
1659     else
1660         av_dlog(avctx, "surround_mixlev: {not written}\n");
1661     if (opt->audio_production_info) {
1662         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1663         switch (opt->room_type) {
1664         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1665         case AC3ENC_OPT_LARGE_ROOM:    av_strlcpy(strbuf, "large", 32);        break;
1666         case AC3ENC_OPT_SMALL_ROOM:    av_strlcpy(strbuf, "small", 32);        break;
1667         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1668         }
1669         av_dlog(avctx, "room_type: %s\n", strbuf);
1670     } else {
1671         av_dlog(avctx, "mixing_level: {not written}\n");
1672         av_dlog(avctx, "room_type: {not written}\n");
1673     }
1674     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1675     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1676     if (s->channel_mode == AC3_CHMODE_STEREO) {
1677         switch (opt->dolby_surround_mode) {
1678         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1679         case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1680         case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1681         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1682         }
1683         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1684     } else {
1685         av_dlog(avctx, "dsur_mode: {not written}\n");
1686     }
1687     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1688
1689     if (s->bitstream_id == 6) {
1690         if (opt->extended_bsi_1) {
1691             switch (opt->preferred_stereo_downmix) {
1692             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1693             case AC3ENC_OPT_DOWNMIX_LTRT:  av_strlcpy(strbuf, "ltrt", 32);         break;
1694             case AC3ENC_OPT_DOWNMIX_LORO:  av_strlcpy(strbuf, "loro", 32);         break;
1695             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1696             }
1697             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1698             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1699                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1700             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1701                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1702             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1703                     opt->loro_center_mix_level, s->loro_center_mix_level);
1704             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1705                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
1706         } else {
1707             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1708         }
1709         if (opt->extended_bsi_2) {
1710             switch (opt->dolby_surround_ex_mode) {
1711             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1712             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1713             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1714             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1715             }
1716             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1717             switch (opt->dolby_headphone_mode) {
1718             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1719             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1720             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1721             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1722             }
1723             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1724
1725             switch (opt->ad_converter_type) {
1726             case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
1727             case AC3ENC_OPT_ADCONV_HDCD:     av_strlcpy(strbuf, "hdcd", 32);     break;
1728             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1729             }
1730             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1731         } else {
1732             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1733         }
1734     }
1735 #endif
1736 }
1737
1738
1739 #define FLT_OPTION_THRESHOLD 0.01
1740
1741 static int validate_float_option(float v, const float *v_list, int v_list_size)
1742 {
1743     int i;
1744
1745     for (i = 0; i < v_list_size; i++) {
1746         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1747             v > (v_list[i] - FLT_OPTION_THRESHOLD))
1748             break;
1749     }
1750     if (i == v_list_size)
1751         return -1;
1752
1753     return i;
1754 }
1755
1756
1757 static void validate_mix_level(void *log_ctx, const char *opt_name,
1758                                float *opt_param, const float *list,
1759                                int list_size, int default_value, int min_value,
1760                                int *ctx_param)
1761 {
1762     int mixlev = validate_float_option(*opt_param, list, list_size);
1763     if (mixlev < min_value) {
1764         mixlev = default_value;
1765         if (*opt_param >= 0.0) {
1766             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1767                    "default value: %0.3f\n", opt_name, list[mixlev]);
1768         }
1769     }
1770     *opt_param = list[mixlev];
1771     *ctx_param = mixlev;
1772 }
1773
1774
1775 /**
1776  * Validate metadata options as set by AVOption system.
1777  * These values can optionally be changed per-frame.
1778  */
1779 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1780 {
1781     AVCodecContext *avctx = s->avctx;
1782     AC3EncOptions *opt = &s->options;
1783
1784     opt->audio_production_info = 0;
1785     opt->extended_bsi_1        = 0;
1786     opt->extended_bsi_2        = 0;
1787     opt->eac3_mixing_metadata  = 0;
1788     opt->eac3_info_metadata    = 0;
1789
1790     /* determine mixing metadata / xbsi1 use */
1791     if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
1792         opt->extended_bsi_1       = 1;
1793         opt->eac3_mixing_metadata = 1;
1794     }
1795     if (s->has_center &&
1796         (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1797         opt->extended_bsi_1       = 1;
1798         opt->eac3_mixing_metadata = 1;
1799     }
1800     if (s->has_surround &&
1801         (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1802         opt->extended_bsi_1       = 1;
1803         opt->eac3_mixing_metadata = 1;
1804     }
1805
1806     if (s->eac3) {
1807         /* determine info metadata use */
1808         if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1809             opt->eac3_info_metadata = 1;
1810         if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
1811             opt->eac3_info_metadata = 1;
1812         if (s->channel_mode == AC3_CHMODE_STEREO &&
1813             (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
1814             opt->eac3_info_metadata = 1;
1815         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1816             opt->eac3_info_metadata = 1;
1817         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
1818             opt->ad_converter_type != AC3ENC_OPT_NONE) {
1819             opt->audio_production_info = 1;
1820             opt->eac3_info_metadata    = 1;
1821         }
1822     } else {
1823         /* determine audio production info use */
1824         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
1825             opt->audio_production_info = 1;
1826
1827         /* determine xbsi2 use */
1828         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1829             opt->extended_bsi_2 = 1;
1830         if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
1831             opt->extended_bsi_2 = 1;
1832         if (opt->ad_converter_type != AC3ENC_OPT_NONE)
1833             opt->extended_bsi_2 = 1;
1834     }
1835
1836     /* validate AC-3 mixing levels */
1837     if (!s->eac3) {
1838         if (s->has_center) {
1839             validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1840                             cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1841                             &s->center_mix_level);
1842         }
1843         if (s->has_surround) {
1844             validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1845                             surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1846                             &s->surround_mix_level);
1847         }
1848     }
1849
1850     /* validate extended bsi 1 / mixing metadata */
1851     if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
1852         /* default preferred stereo downmix */
1853         if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
1854             opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
1855         if (!s->eac3 || s->has_center) {
1856             /* validate Lt/Rt center mix level */
1857             validate_mix_level(avctx, "ltrt_center_mix_level",
1858                                &opt->ltrt_center_mix_level, extmixlev_options,
1859                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
1860                                &s->ltrt_center_mix_level);
1861             /* validate Lo/Ro center mix level */
1862             validate_mix_level(avctx, "loro_center_mix_level",
1863                                &opt->loro_center_mix_level, extmixlev_options,
1864                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
1865                                &s->loro_center_mix_level);
1866         }
1867         if (!s->eac3 || s->has_surround) {
1868             /* validate Lt/Rt surround mix level */
1869             validate_mix_level(avctx, "ltrt_surround_mix_level",
1870                                &opt->ltrt_surround_mix_level, extmixlev_options,
1871                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
1872                                &s->ltrt_surround_mix_level);
1873             /* validate Lo/Ro surround mix level */
1874             validate_mix_level(avctx, "loro_surround_mix_level",
1875                                &opt->loro_surround_mix_level, extmixlev_options,
1876                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
1877                                &s->loro_surround_mix_level);
1878         }
1879     }
1880
1881     /* validate audio service type / channels combination */
1882     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1883          avctx->channels == 1) ||
1884         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1885           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
1886           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1887          && avctx->channels > 1)) {
1888         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1889                                     "specified number of channels\n");
1890         return AVERROR(EINVAL);
1891     }
1892
1893     /* validate extended bsi 2 / info metadata */
1894     if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
1895         /* default dolby headphone mode */
1896         if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
1897             opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
1898         /* default dolby surround ex mode */
1899         if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
1900             opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
1901         /* default A/D converter type */
1902         if (opt->ad_converter_type == AC3ENC_OPT_NONE)
1903             opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
1904     }
1905
1906     /* copyright & original defaults */
1907     if (!s->eac3 || opt->eac3_info_metadata) {
1908         /* default copyright */
1909         if (opt->copyright == AC3ENC_OPT_NONE)
1910             opt->copyright = AC3ENC_OPT_OFF;
1911         /* default original */
1912         if (opt->original == AC3ENC_OPT_NONE)
1913             opt->original = AC3ENC_OPT_ON;
1914     }
1915
1916     /* dolby surround mode default */
1917     if (!s->eac3 || opt->eac3_info_metadata) {
1918         if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
1919             opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
1920     }
1921
1922     /* validate audio production info */
1923     if (opt->audio_production_info) {
1924         if (opt->mixing_level == AC3ENC_OPT_NONE) {
1925             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1926                    "room_type is set\n");
1927             return AVERROR(EINVAL);
1928         }
1929         if (opt->mixing_level < 80) {
1930             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1931                    "80dB and 111dB\n");
1932             return AVERROR(EINVAL);
1933         }
1934         /* default room type */
1935         if (opt->room_type == AC3ENC_OPT_NONE)
1936             opt->room_type = AC3ENC_OPT_NOT_INDICATED;
1937     }
1938
1939     /* set bitstream id for alternate bitstream syntax */
1940     if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
1941         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1942             static int warn_once = 1;
1943             if (warn_once) {
1944                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1945                        "not compatible with reduced samplerates. writing of "
1946                        "extended bitstream information will be disabled.\n");
1947                 warn_once = 0;
1948             }
1949         } else {
1950             s->bitstream_id = 6;
1951         }
1952     }
1953
1954     return 0;
1955 }
1956
1957
1958 /**
1959  * Finalize encoding and free any memory allocated by the encoder.
1960  */
1961 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1962 {
1963     int blk, ch;
1964     AC3EncodeContext *s = avctx->priv_data;
1965
1966     av_freep(&s->windowed_samples);
1967     for (ch = 0; ch < s->channels; ch++)
1968         av_freep(&s->planar_samples[ch]);
1969     av_freep(&s->planar_samples);
1970     av_freep(&s->bap_buffer);
1971     av_freep(&s->bap1_buffer);
1972     av_freep(&s->mdct_coef_buffer);
1973     av_freep(&s->fixed_coef_buffer);
1974     av_freep(&s->exp_buffer);
1975     av_freep(&s->grouped_exp_buffer);
1976     av_freep(&s->psd_buffer);
1977     av_freep(&s->band_psd_buffer);
1978     av_freep(&s->mask_buffer);
1979     av_freep(&s->qmant_buffer);
1980     av_freep(&s->cpl_coord_exp_buffer);
1981     av_freep(&s->cpl_coord_mant_buffer);
1982     for (blk = 0; blk < s->num_blocks; blk++) {
1983         AC3Block *block = &s->blocks[blk];
1984         av_freep(&block->mdct_coef);
1985         av_freep(&block->fixed_coef);
1986         av_freep(&block->exp);
1987         av_freep(&block->grouped_exp);
1988         av_freep(&block->psd);
1989         av_freep(&block->band_psd);
1990         av_freep(&block->mask);
1991         av_freep(&block->qmant);
1992         av_freep(&block->cpl_coord_exp);
1993         av_freep(&block->cpl_coord_mant);
1994     }
1995
1996     s->mdct_end(s);
1997
1998     av_freep(&avctx->coded_frame);
1999     return 0;
2000 }
2001
2002
2003 /**
2004  * Set channel information during initialization.
2005  */
2006 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2007                                     int64_t *channel_layout)
2008 {
2009     int ch_layout;
2010
2011     if (channels < 1 || channels > AC3_MAX_CHANNELS)
2012         return AVERROR(EINVAL);
2013     if ((uint64_t)*channel_layout > 0x7FF)
2014         return AVERROR(EINVAL);
2015     ch_layout = *channel_layout;
2016     if (!ch_layout)
2017         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2018
2019     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2020     s->channels     = channels;
2021     s->fbw_channels = channels - s->lfe_on;
2022     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
2023     if (s->lfe_on)
2024         ch_layout -= AV_CH_LOW_FREQUENCY;
2025
2026     switch (ch_layout) {
2027     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2028     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2029     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2030     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2031     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2032     case AV_CH_LAYOUT_QUAD:
2033     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2034     case AV_CH_LAYOUT_5POINT0:
2035     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2036     default:
2037         return AVERROR(EINVAL);
2038     }
2039     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2040     s->has_surround =  s->channel_mode & 0x04;
2041
2042     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2043     *channel_layout = ch_layout;
2044     if (s->lfe_on)
2045         *channel_layout |= AV_CH_LOW_FREQUENCY;
2046
2047     return 0;
2048 }
2049
2050
2051 static av_cold int validate_options(AC3EncodeContext *s)
2052 {
2053     AVCodecContext *avctx = s->avctx;
2054     int i, ret, max_sr;
2055
2056     /* validate channel layout */
2057     if (!avctx->channel_layout) {
2058         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2059                                       "encoder will guess the layout, but it "
2060                                       "might be incorrect.\n");
2061     }
2062     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2063     if (ret) {
2064         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2065         return ret;
2066     }
2067
2068     /* validate sample rate */
2069     /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2070              decoder that supports half sample rate so we can validate that
2071              the generated files are correct. */
2072     max_sr = s->eac3 ? 2 : 8;
2073     for (i = 0; i <= max_sr; i++) {
2074         if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2075             break;
2076     }
2077     if (i > max_sr) {
2078         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2079         return AVERROR(EINVAL);
2080     }
2081     s->sample_rate        = avctx->sample_rate;
2082     s->bit_alloc.sr_shift = i / 3;
2083     s->bit_alloc.sr_code  = i % 3;
2084     s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2085
2086     /* validate bit rate */
2087     if (s->eac3) {
2088         int max_br, min_br, wpf, min_br_dist, min_br_code;
2089         int num_blks_code, num_blocks, frame_samples;
2090
2091         /* calculate min/max bitrate */
2092         /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2093                  found use either 6 blocks or 1 block, even though 2 or 3 blocks
2094                  would work as far as the bit rate is concerned. */
2095         for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2096             num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2097             frame_samples  = AC3_BLOCK_SIZE * num_blocks;
2098             max_br = 2048 * s->sample_rate / frame_samples * 16;
2099             min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2100             if (avctx->bit_rate <= max_br)
2101                 break;
2102         }
2103         if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2104             av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2105                    "for this sample rate\n", min_br, max_br);
2106             return AVERROR(EINVAL);
2107         }
2108         s->num_blks_code = num_blks_code;
2109         s->num_blocks    = num_blocks;
2110
2111         /* calculate words-per-frame for the selected bitrate */
2112         wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2113         av_assert1(wpf > 0 && wpf <= 2048);
2114
2115         /* find the closest AC-3 bitrate code to the selected bitrate.
2116            this is needed for lookup tables for bandwidth and coupling
2117            parameter selection */
2118         min_br_code = -1;
2119         min_br_dist = INT_MAX;
2120         for (i = 0; i < 19; i++) {
2121             int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2122             if (br_dist < min_br_dist) {
2123                 min_br_dist = br_dist;
2124                 min_br_code = i;
2125             }
2126         }
2127
2128         /* make sure the minimum frame size is below the average frame size */
2129         s->frame_size_code = min_br_code << 1;
2130         while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2131             wpf--;
2132         s->frame_size_min = 2 * wpf;
2133     } else {
2134         for (i = 0; i < 19; i++) {
2135             if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2136                 break;
2137         }
2138         if (i == 19) {
2139             av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2140             return AVERROR(EINVAL);
2141         }
2142         s->frame_size_code = i << 1;
2143         s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2144         s->num_blks_code   = 0x3;
2145         s->num_blocks      = 6;
2146     }
2147     s->bit_rate   = avctx->bit_rate;
2148     s->frame_size = s->frame_size_min;
2149
2150     /* validate cutoff */
2151     if (avctx->cutoff < 0) {
2152         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2153         return AVERROR(EINVAL);
2154     }
2155     s->cutoff = avctx->cutoff;
2156     if (s->cutoff > (s->sample_rate >> 1))
2157         s->cutoff = s->sample_rate >> 1;
2158
2159     ret = ff_ac3_validate_metadata(s);
2160     if (ret)
2161         return ret;
2162
2163     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2164                              (s->channel_mode == AC3_CHMODE_STEREO);
2165
2166     s->cpl_enabled = s->options.channel_coupling &&
2167                      s->channel_mode >= AC3_CHMODE_STEREO;
2168
2169     return 0;
2170 }
2171
2172
2173 /**
2174  * Set bandwidth for all channels.
2175  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2176  * default value will be used.
2177  */
2178 static av_cold void set_bandwidth(AC3EncodeContext *s)
2179 {
2180     int blk, ch;
2181     int av_uninit(cpl_start);
2182
2183     if (s->cutoff) {
2184         /* calculate bandwidth based on user-specified cutoff frequency */
2185         int fbw_coeffs;
2186         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2187         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2188     } else {
2189         /* use default bandwidth setting */
2190         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2191     }
2192
2193     /* set number of coefficients for each channel */
2194     for (ch = 1; ch <= s->fbw_channels; ch++) {
2195         s->start_freq[ch] = 0;
2196         for (blk = 0; blk < s->num_blocks; blk++)
2197             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2198     }
2199     /* LFE channel always has 7 coefs */
2200     if (s->lfe_on) {
2201         s->start_freq[s->lfe_channel] = 0;
2202         for (blk = 0; blk < s->num_blocks; blk++)
2203             s->blocks[blk].end_freq[ch] = 7;
2204     }
2205
2206     /* initialize coupling strategy */
2207     if (s->cpl_enabled) {
2208         if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
2209             cpl_start = s->options.cpl_start;
2210         } else {
2211             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2212             if (cpl_start < 0) {
2213                 if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
2214                     s->cpl_enabled = 0;
2215                 else
2216                     cpl_start = 15;
2217             }
2218         }
2219     }
2220     if (s->cpl_enabled) {
2221         int i, cpl_start_band, cpl_end_band;
2222         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2223
2224         cpl_end_band   = s->bandwidth_code / 4 + 3;
2225         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2226
2227         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2228
2229         s->num_cpl_bands = 1;
2230         *cpl_band_sizes  = 12;
2231         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2232             if (ff_eac3_default_cpl_band_struct[i]) {
2233                 *cpl_band_sizes += 12;
2234             } else {
2235                 s->num_cpl_bands++;
2236                 cpl_band_sizes++;
2237                 *cpl_band_sizes = 12;
2238             }
2239         }
2240
2241         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2242         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
2243         for (blk = 0; blk < s->num_blocks; blk++)
2244             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2245     }
2246 }
2247
2248
2249 static av_cold int allocate_buffers(AC3EncodeContext *s)
2250 {
2251     AVCodecContext *avctx = s->avctx;
2252     int blk, ch;
2253     int channels = s->channels + 1; /* includes coupling channel */
2254     int channel_blocks = channels * s->num_blocks;
2255     int total_coefs    = AC3_MAX_COEFS * channel_blocks;
2256
2257     if (s->allocate_sample_buffers(s))
2258         goto alloc_fail;
2259
2260     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2261                      sizeof(*s->bap_buffer), alloc_fail);
2262     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2263                      sizeof(*s->bap1_buffer), alloc_fail);
2264     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2265                       sizeof(*s->mdct_coef_buffer), alloc_fail);
2266     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2267                      sizeof(*s->exp_buffer), alloc_fail);
2268     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2269                      sizeof(*s->grouped_exp_buffer), alloc_fail);
2270     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2271                      sizeof(*s->psd_buffer), alloc_fail);
2272     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2273                      sizeof(*s->band_psd_buffer), alloc_fail);
2274     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2275                      sizeof(*s->mask_buffer), alloc_fail);
2276     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2277                      sizeof(*s->qmant_buffer), alloc_fail);
2278     if (s->cpl_enabled) {
2279         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2280                          sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2281         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2282                          sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2283     }
2284     for (blk = 0; blk < s->num_blocks; blk++) {
2285         AC3Block *block = &s->blocks[blk];
2286         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2287                           alloc_fail);
2288         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2289                           alloc_fail);
2290         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2291                           alloc_fail);
2292         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2293                           alloc_fail);
2294         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2295                           alloc_fail);
2296         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2297                           alloc_fail);
2298         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2299                           alloc_fail);
2300         if (s->cpl_enabled) {
2301             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2302                               alloc_fail);
2303             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2304                               alloc_fail);
2305         }
2306
2307         for (ch = 0; ch < channels; ch++) {
2308             /* arrangement: block, channel, coeff */
2309             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
2310             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2311             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
2312             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
2313             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
2314             if (s->cpl_enabled) {
2315                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
2316                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
2317             }
2318
2319             /* arrangement: channel, block, coeff */
2320             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2321             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2322         }
2323     }
2324
2325     if (!s->fixed_point) {
2326         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2327                           sizeof(*s->fixed_coef_buffer), alloc_fail);
2328         for (blk = 0; blk < s->num_blocks; blk++) {
2329             AC3Block *block = &s->blocks[blk];
2330             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2331                               sizeof(*block->fixed_coef), alloc_fail);
2332             for (ch = 0; ch < channels; ch++)
2333                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2334         }
2335     } else {
2336         for (blk = 0; blk < s->num_blocks; blk++) {
2337             AC3Block *block = &s->blocks[blk];
2338             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2339                               sizeof(*block->fixed_coef), alloc_fail);
2340             for (ch = 0; ch < channels; ch++)
2341                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2342         }
2343     }
2344
2345     return 0;
2346 alloc_fail:
2347     return AVERROR(ENOMEM);
2348 }
2349
2350
2351 /**
2352  * Initialize the encoder.
2353  */
2354 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2355 {
2356     AC3EncodeContext *s = avctx->priv_data;
2357     int ret, frame_size_58;
2358
2359     s->avctx = avctx;
2360
2361     s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2362
2363     ff_ac3_common_init();
2364
2365     ret = validate_options(s);
2366     if (ret)
2367         return ret;
2368
2369     avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2370
2371     s->bitstream_mode = avctx->audio_service_type;
2372     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2373         s->bitstream_mode = 0x7;
2374
2375     s->bits_written    = 0;
2376     s->samples_written = 0;
2377
2378     /* calculate crc_inv for both possible frame sizes */
2379     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2380     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2381     if (s->bit_alloc.sr_code == 1) {
2382         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2383         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2384     }
2385
2386     /* set function pointers */
2387     if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2388         s->mdct_end                     = ff_ac3_fixed_mdct_end;
2389         s->mdct_init                    = ff_ac3_fixed_mdct_init;
2390         s->allocate_sample_buffers      = ff_ac3_fixed_allocate_sample_buffers;
2391     } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2392         s->mdct_end                     = ff_ac3_float_mdct_end;
2393         s->mdct_init                    = ff_ac3_float_mdct_init;
2394         s->allocate_sample_buffers      = ff_ac3_float_allocate_sample_buffers;
2395     }
2396     if (CONFIG_EAC3_ENCODER && s->eac3)
2397         s->output_frame_header = ff_eac3_output_frame_header;
2398     else
2399         s->output_frame_header = ac3_output_frame_header;
2400
2401     set_bandwidth(s);
2402
2403     exponent_init(s);
2404
2405     bit_alloc_init(s);
2406
2407     ret = s->mdct_init(s);
2408     if (ret)
2409         goto init_fail;
2410
2411     ret = allocate_buffers(s);
2412     if (ret)
2413         goto init_fail;
2414
2415     avctx->coded_frame= avcodec_alloc_frame();
2416
2417     dsputil_init(&s->dsp, avctx);
2418     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2419
2420     dprint_options(s);
2421
2422     return 0;
2423 init_fail:
2424     ff_ac3_encode_close(avctx);
2425     return ret;
2426 }