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