OSDN Git Service

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