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