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