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