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