GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/ac3enc.c Lines: 1009 1204 83.8 %
Date: 2021-04-20 04:37:23 Branches: 624 867 72.0 %

Line Branch Exec Source
1
/*
2
 * The simplest AC-3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard
4
 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5
 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6
 *
7
 * This file is part of FFmpeg.
8
 *
9
 * FFmpeg is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * FFmpeg is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with FFmpeg; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
 */
23
24
/**
25
 * @file
26
 * The simplest AC-3 encoder.
27
 */
28
29
#include <stdint.h>
30
31
#include "libavutil/attributes.h"
32
#include "libavutil/avassert.h"
33
#include "libavutil/avstring.h"
34
#include "libavutil/channel_layout.h"
35
#include "libavutil/crc.h"
36
#include "libavutil/internal.h"
37
#include "libavutil/mem_internal.h"
38
#include "libavutil/opt.h"
39
#include "libavutil/thread.h"
40
#include "avcodec.h"
41
#include "internal.h"
42
#include "me_cmp.h"
43
#include "put_bits.h"
44
#include "audiodsp.h"
45
#include "ac3dsp.h"
46
#include "ac3.h"
47
#include "fft.h"
48
#include "ac3enc.h"
49
#include "eac3enc.h"
50
51
typedef struct AC3Mant {
52
    int16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
53
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
54
} AC3Mant;
55
56
#define CMIXLEV_NUM_OPTIONS 3
57
static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
58
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
59
};
60
61
#define SURMIXLEV_NUM_OPTIONS 3
62
static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
63
    LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
64
};
65
66
#define EXTMIXLEV_NUM_OPTIONS 8
67
static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
68
    LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_1POINT5DB,
69
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
70
};
71
72
/* The first two options apply only to the AC-3 encoders;
73
 * the rest is also valid for EAC-3. When modifying it,
74
 * it might be necessary to adapt said offset in eac3enc.c. */
75
#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
76
#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
77
const AVOption ff_ac3_enc_options[] = {
78
/* AC-3 downmix levels */
79
{"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
80
{"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
81
/* audio production information */
82
{"mixing_level", "Mixing Level", OFFSET(mixing_level), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 111, AC3ENC_PARAM},
83
{"room_type", "Room Type", OFFSET(room_type), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_SMALL_ROOM, AC3ENC_PARAM, "room_type"},
84
    {"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
85
    {"large",        "Large Room",              0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_LARGE_ROOM    }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
86
    {"small",        "Small Room",              0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_SMALL_ROOM    }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
87
/* Metadata Options */
88
{"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, AC3ENC_PARAM},
89
{"copyright", "Copyright Bit", OFFSET(copyright), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 1, AC3ENC_PARAM},
90
{"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), AV_OPT_TYPE_INT, {.i64 = -31 }, -31, -1, AC3ENC_PARAM},
91
{"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_MODE_ON, AC3ENC_PARAM, "dsur_mode"},
92
    {"notindicated", "Not Indicated (default)",    0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
93
    {"on",           "Dolby Surround Encoded",     0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON       }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
94
    {"off",          "Not Dolby Surround Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF      }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
95
{"original", "Original Bit Stream", OFFSET(original), AV_OPT_TYPE_INT,   {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, 1, AC3ENC_PARAM},
96
/* extended bitstream information */
97
{"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_DOWNMIX_DPLII, AC3ENC_PARAM, "dmix_mode"},
98
    {"notindicated", "Not Indicated (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
99
    {"ltrt", "Lt/Rt Downmix Preferred",         0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_LTRT  }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
100
    {"loro", "Lo/Ro Downmix Preferred",         0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_LORO  }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
101
    {"dplii", "Dolby Pro Logic II Downmix Preferred", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DOWNMIX_DPLII }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
102
{"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
103
{"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
104
{"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
105
{"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), AV_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
106
{"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_DSUREX_DPLIIZ, AC3ENC_PARAM, "dsurex_mode"},
107
    {"notindicated", "Not Indicated (default)",       0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
108
    {"on",           "Dolby Surround EX Encoded",     0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON       }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
109
    {"off",          "Not Dolby Surround EX Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF      }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
110
    {"dpliiz",       "Dolby Pro Logic IIz-encoded",   0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_DSUREX_DPLIIZ }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
111
{"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_MODE_ON, AC3ENC_PARAM, "dheadphone_mode"},
112
    {"notindicated", "Not Indicated (default)",     0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_NOT_INDICATED }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
113
    {"on",           "Dolby Headphone Encoded",     0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_ON       }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
114
    {"off",          "Not Dolby Headphone Encoded", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_MODE_OFF      }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
115
{"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_NONE }, AC3ENC_OPT_NONE, AC3ENC_OPT_ADCONV_HDCD, AC3ENC_PARAM, "ad_conv_type"},
116
    {"standard", "Standard (default)", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_ADCONV_STANDARD }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
117
    {"hdcd",     "HDCD",               0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_ADCONV_HDCD     }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
118
/* Other Encoding Options */
119
{"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), AV_OPT_TYPE_BOOL, {.i64 = 1 }, 0, 1, AC3ENC_PARAM},
120
{"channel_coupling",   "Channel Coupling",   OFFSET(channel_coupling),   AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_AUTO }, AC3ENC_OPT_AUTO, AC3ENC_OPT_ON, AC3ENC_PARAM, "channel_coupling"},
121
    {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_AUTO }, INT_MIN, INT_MAX, AC3ENC_PARAM, "channel_coupling"},
122
{"cpl_start_band", "Coupling Start Band", OFFSET(cpl_start), AV_OPT_TYPE_INT, {.i64 = AC3ENC_OPT_AUTO }, AC3ENC_OPT_AUTO, 15, AC3ENC_PARAM, "cpl_start_band"},
123
    {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = AC3ENC_OPT_AUTO }, INT_MIN, INT_MAX, AC3ENC_PARAM, "cpl_start_band"},
124
{NULL}
125
};
126
127
const AVCodecDefault ff_ac3_enc_defaults[] = {
128
    { "b",  "0" },
129
    { NULL }
130
};
131
132
/**
133
 * LUT for number of exponent groups.
134
 * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
135
 */
136
static uint8_t exponent_group_tab[2][3][256];
137
138
139
/**
140
 * List of supported channel layouts.
141
 */
142
const uint64_t ff_ac3_channel_layouts[19] = {
143
     AV_CH_LAYOUT_MONO,
144
     AV_CH_LAYOUT_STEREO,
145
     AV_CH_LAYOUT_2_1,
146
     AV_CH_LAYOUT_SURROUND,
147
     AV_CH_LAYOUT_2_2,
148
     AV_CH_LAYOUT_QUAD,
149
     AV_CH_LAYOUT_4POINT0,
150
     AV_CH_LAYOUT_5POINT0,
151
     AV_CH_LAYOUT_5POINT0_BACK,
152
    (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
153
    (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
154
    (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
155
    (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
156
    (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
157
    (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
158
    (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
159
     AV_CH_LAYOUT_5POINT1,
160
     AV_CH_LAYOUT_5POINT1_BACK,
161
     0
162
};
163
164
/**
165
 * Table to remap channels from SMPTE order to AC-3 order.
166
 * [channel_mode][lfe][ch]
167
 */
168
static const uint8_t ac3_enc_channel_map[8][2][6] = {
169
    COMMON_CHANNEL_MAP
170
    { { 0, 1, 2, 3,    }, { 0, 1, 3, 4, 2,   } },
171
    { { 0, 2, 1, 3, 4, }, { 0, 2, 1, 4, 5, 3 } },
172
};
173
174
/**
175
 * LUT to select the bandwidth code based on the bit rate, sample rate, and
176
 * number of full-bandwidth channels.
177
 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
178
 */
179
static const uint8_t ac3_bandwidth_tab[5][3][19] = {
180
//      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
181
182
    { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
183
      {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
184
      {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
185
186
    { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
187
      {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
188
      {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
189
190
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
191
      {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
192
      {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
193
194
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
195
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
196
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
197
198
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
199
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
200
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
201
};
202
203
204
/**
205
 * LUT to select the coupling start band based on the bit rate, sample rate, and
206
 * number of full-bandwidth channels. -1 = coupling off
207
 * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
208
 *
209
 * TODO: more testing for optimal parameters.
210
 *       multi-channel tests at 44.1kHz and 32kHz.
211
 */
212
static const int8_t ac3_coupling_start_tab[6][3][19] = {
213
//      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
214
215
    // 2/0
216
    { {  0,  0,  0,  0,  0,  0,  0,  1,  1,  7,  8, 11, 12, -1, -1, -1, -1, -1, -1 },
217
      {  0,  0,  0,  0,  0,  0,  1,  3,  5,  7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
218
      {  0,  0,  0,  0,  1,  2,  2,  9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
219
220
    // 3/0
221
    { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
222
      {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
223
      { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
224
225
    // 2/1 - untested
226
    { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
227
      {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
228
      { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
229
230
    // 3/1
231
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
232
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
233
      { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
234
235
    // 2/2 - untested
236
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
237
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
238
      { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
239
240
    // 3/2
241
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
242
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
243
      { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
244
};
245
246
247
/**
248
 * Adjust the frame size to make the average bit rate match the target bit rate.
249
 * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
250
 *
251
 * @param s  AC-3 encoder private context
252
 */
253
925
void ff_ac3_adjust_frame_size(AC3EncodeContext *s)
254
{
255

953
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
256
28
        s->bits_written    -= s->bit_rate;
257
28
        s->samples_written -= s->sample_rate;
258
    }
259
1850
    s->frame_size = s->frame_size_min +
260
925
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
261
925
    s->bits_written    += s->frame_size * 8;
262
925
    s->samples_written += AC3_BLOCK_SIZE * s->num_blocks;
263
925
}
264
265
266
/**
267
 * Set the initial coupling strategy parameters prior to coupling analysis.
268
 *
269
 * @param s  AC-3 encoder private context
270
 */
271
925
void ff_ac3_compute_coupling_strategy(AC3EncodeContext *s)
272
{
273
    int blk, ch;
274
    int got_cpl_snr;
275
    int num_cpl_blocks;
276
277
    /* set coupling use flags for each block/channel */
278
    /* TODO: turn coupling on/off and adjust start band based on bit usage */
279
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
280
5550
        AC3Block *block = &s->blocks[blk];
281
15414
        for (ch = 1; ch <= s->fbw_channels; ch++)
282
9864
            block->channel_in_cpl[ch] = s->cpl_on;
283
    }
284
285
    /* enable coupling for each block if at least 2 channels have coupling
286
       enabled for that block */
287
925
    got_cpl_snr = 0;
288
925
    num_cpl_blocks = 0;
289
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
290
5550
        AC3Block *block = &s->blocks[blk];
291
5550
        block->num_cpl_channels = 0;
292
15414
        for (ch = 1; ch <= s->fbw_channels; ch++)
293
9864
            block->num_cpl_channels += block->channel_in_cpl[ch];
294
5550
        block->cpl_in_use = block->num_cpl_channels > 1;
295
5550
        num_cpl_blocks += block->cpl_in_use;
296
5550
        if (!block->cpl_in_use) {
297
1236
            block->num_cpl_channels = 0;
298
2472
            for (ch = 1; ch <= s->fbw_channels; ch++)
299
1236
                block->channel_in_cpl[ch] = 0;
300
        }
301
302
5550
        block->new_cpl_strategy = !blk;
303
5550
        if (blk) {
304
12845
            for (ch = 1; ch <= s->fbw_channels; ch++) {
305
8220
                if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
306
                    block->new_cpl_strategy = 1;
307
                    break;
308
                }
309
            }
310
        }
311
5550
        block->new_cpl_leak = block->new_cpl_strategy;
312
313

5550
        if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
314
925
            block->new_snr_offsets = 1;
315
925
            if (block->cpl_in_use)
316
719
                got_cpl_snr = 1;
317
        } else {
318
4625
            block->new_snr_offsets = 0;
319
        }
320
    }
321
925
    if (!num_cpl_blocks)
322
206
        s->cpl_on = 0;
323
324
    /* set bandwidth for each channel */
325
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
326
5550
        AC3Block *block = &s->blocks[blk];
327
15414
        for (ch = 1; ch <= s->fbw_channels; ch++) {
328
9864
            if (block->channel_in_cpl[ch])
329
8628
                block->end_freq[ch] = s->start_freq[CPL_CH];
330
            else
331
1236
                block->end_freq[ch] = s->bandwidth_code * 3 + 73;
332
        }
333
    }
334
925
}
335
336
337
/**
338
 * Apply stereo rematrixing to coefficients based on rematrixing flags.
339
 *
340
 * @param s  AC-3 encoder private context
341
 */
342
925
static void ac3_apply_rematrixing(AC3EncodeContext *s)
343
{
344
    int nb_coefs;
345
    int blk, bnd, i;
346
    int start, end;
347
925
    uint8_t *flags = NULL;
348
349
925
    if (!s->rematrixing_enabled)
350
206
        return;
351
352
5033
    for (blk = 0; blk < s->num_blocks; blk++) {
353
4314
        AC3Block *block = &s->blocks[blk];
354
4314
        if (block->new_rematrixing_strategy)
355
2197
            flags = block->rematrixing_flags;
356
4314
        nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
357
21570
        for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
358
17256
            if (flags[bnd]) {
359
9547
                start = ff_ac3_rematrix_band_tab[bnd];
360
9547
                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
361
225283
                for (i = start; i < end; i++) {
362
215736
                    int32_t lt = block->fixed_coef[1][i];
363
215736
                    int32_t rt = block->fixed_coef[2][i];
364
215736
                    block->fixed_coef[1][i] = (lt + rt) >> 1;
365
215736
                    block->fixed_coef[2][i] = (lt - rt) >> 1;
366
                }
367
            }
368
        }
369
    }
370
}
371
372
373
/*
374
 * Initialize exponent tables.
375
 */
376
6
static av_cold void exponent_init(void)
377
{
378
    int expstr, i, grpsize;
379
380
24
    for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
381
18
        grpsize = 3 << expstr;
382
4410
        for (i = 12; i < 256; i++) {
383
4392
            exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
384
4392
            exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
385
        }
386
    }
387
    /* LFE */
388
6
    exponent_group_tab[0][0][7] = 2;
389
6
}
390
391
392
/*
393
 * Extract exponents from the MDCT coefficients.
394
 */
395
925
static void extract_exponents(AC3EncodeContext *s)
396
{
397
925
    int ch        = !s->cpl_on;
398
925
    int chan_size = AC3_MAX_COEFS * s->num_blocks * (s->channels - ch + 1);
399
925
    AC3Block *block = &s->blocks[0];
400
401
925
    s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
402
925
}
403
404
405
/**
406
 * Exponent Difference Threshold.
407
 * New exponents are sent if their SAD exceed this number.
408
 */
409
#define EXP_DIFF_THRESHOLD 500
410
411
/**
412
 * Table used to select exponent strategy based on exponent reuse block interval.
413
 */
414
static const uint8_t exp_strategy_reuse_tab[4][6] = {
415
    { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
416
    { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
417
    { EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
418
    { EXP_D45, EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15 }
419
};
420
421
/*
422
 * Calculate exponent strategies for all channels.
423
 * Array arrangement is reversed to simplify the per-channel calculation.
424
 */
425
925
static void compute_exp_strategy(AC3EncodeContext *s)
426
{
427
    int ch, blk, blk1;
428
429
3288
    for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
430
2363
        uint8_t *exp_strategy = s->exp_strategy[ch];
431
2363
        uint8_t *exp          = s->blocks[0].exp[ch];
432
        int exp_diff;
433
434
        /* estimate if the exponent variation & decide if they should be
435
           reused in the next frame */
436
2363
        exp_strategy[0] = EXP_NEW;
437
2363
        exp += AC3_MAX_COEFS;
438
14178
        for (blk = 1; blk < s->num_blocks; blk++, exp += AC3_MAX_COEFS) {
439
11815
            if (ch == CPL_CH) {
440
3595
                if (!s->blocks[blk-1].cpl_in_use) {
441
                    exp_strategy[blk] = EXP_NEW;
442
                    continue;
443
3595
                } else if (!s->blocks[blk].cpl_in_use) {
444
                    exp_strategy[blk] = EXP_REUSE;
445
                    continue;
446
                }
447
8220
            } else if (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
448
                exp_strategy[blk] = EXP_NEW;
449
                continue;
450
            }
451
11815
            exp_diff = s->mecc.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
452
11815
            exp_strategy[blk] = EXP_REUSE;
453

11815
            if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
454
685
                exp_strategy[blk] = EXP_NEW;
455

11130
            else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
456
106
                exp_strategy[blk] = EXP_NEW;
457
        }
458
459
        /* now select the encoding strategy type : if exponents are often
460
           recoded, we use a coarse encoding */
461
2363
        blk = 0;
462
5517
        while (blk < s->num_blocks) {
463
3154
            blk1 = blk + 1;
464

14178
            while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE)
465
11024
                blk1++;
466
3154
            exp_strategy[blk] = exp_strategy_reuse_tab[s->num_blks_code][blk1-blk-1];
467
3154
            blk = blk1;
468
        }
469
    }
470
925
    if (s->lfe_on) {
471
        ch = s->lfe_channel;
472
        s->exp_strategy[ch][0] = EXP_D15;
473
        for (blk = 1; blk < s->num_blocks; blk++)
474
            s->exp_strategy[ch][blk] = EXP_REUSE;
475
    }
476
477
    /* for E-AC-3, determine frame exponent strategy */
478
925
    if (CONFIG_EAC3_ENCODER && s->eac3)
479
273
        ff_eac3_get_frame_exp_strategy(s);
480
925
}
481
482
483
/**
484
 * Update the exponents so that they are the ones the decoder will decode.
485
 *
486
 * @param[in,out] exp   array of exponents for 1 block in 1 channel
487
 * @param nb_exps       number of exponents in active bandwidth
488
 * @param exp_strategy  exponent strategy for the block
489
 * @param cpl           indicates if the block is in the coupling channel
490
 */
491
3154
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
492
                                    int cpl)
493
{
494
    int nb_groups, i, k;
495
496
3154
    nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
497
498
    /* for each group, compute the minimum exponent */
499
3154
    switch(exp_strategy) {
500
459
    case EXP_D25:
501
15705
        for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
502
15246
            uint8_t exp_min = exp[k];
503
15246
            if (exp[k+1] < exp_min)
504
4828
                exp_min = exp[k+1];
505
15246
            exp[i-cpl] = exp_min;
506
15246
            k += 2;
507
        }
508
459
        break;
509
532
    case EXP_D45:
510
9448
        for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
511
8916
            uint8_t exp_min = exp[k];
512
8916
            if (exp[k+1] < exp_min)
513
3435
                exp_min = exp[k+1];
514
8916
            if (exp[k+2] < exp_min)
515
1848
                exp_min = exp[k+2];
516
8916
            if (exp[k+3] < exp_min)
517
1149
                exp_min = exp[k+3];
518
8916
            exp[i-cpl] = exp_min;
519
8916
            k += 4;
520
        }
521
532
        break;
522
    }
523
524
    /* constraint for DC exponent */
525

3154
    if (!cpl && exp[0] > 15)
526
427
        exp[0] = 15;
527
528
    /* decrease the delta between each groups to within 2 so that they can be
529
       differentially encoded */
530
241768
    for (i = 1; i <= nb_groups; i++)
531
238614
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
532
3154
    i--;
533
241768
    while (--i >= 0)
534
238614
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
535
536
3154
    if (cpl)
537
1404
        exp[-1] = exp[0] & ~1;
538
539
    /* now we have the exponent values the decoder will see */
540
3154
    switch (exp_strategy) {
541
459
    case EXP_D25:
542
15705
        for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
543
15246
            uint8_t exp1 = exp[i-cpl];
544
15246
            exp[k--] = exp1;
545
15246
            exp[k--] = exp1;
546
        }
547
459
        break;
548
532
    case EXP_D45:
549
9448
        for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
550
8916
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
551
8916
            k -= 4;
552
        }
553
532
        break;
554
    }
555
3154
}
556
557
558
/*
559
 * Encode exponents from original extracted form to what the decoder will see.
560
 * This copies and groups exponents based on exponent strategy and reduces
561
 * deltas between adjacent exponent groups so that they can be differentially
562
 * encoded.
563
 */
564
925
static void encode_exponents(AC3EncodeContext *s)
565
{
566
    int blk, blk1, ch, cpl;
567
    uint8_t *exp, *exp_strategy;
568
    int nb_coefs, num_reuse_blocks;
569
570
3288
    for (ch = !s->cpl_on; ch <= s->channels; ch++) {
571
2363
        exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
572
2363
        exp_strategy = s->exp_strategy[ch];
573
574
2363
        cpl = (ch == CPL_CH);
575
2363
        blk = 0;
576
5517
        while (blk < s->num_blocks) {
577
3154
            AC3Block *block = &s->blocks[blk];
578

3154
            if (cpl && !block->cpl_in_use) {
579
                exp += AC3_MAX_COEFS;
580
                blk++;
581
                continue;
582
            }
583
3154
            nb_coefs = block->end_freq[ch] - s->start_freq[ch];
584
3154
            blk1 = blk + 1;
585
586
            /* count the number of EXP_REUSE blocks after the current block
587
               and set exponent reference block numbers */
588
3154
            s->exp_ref_block[ch][blk] = blk;
589

14178
            while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE) {
590
11024
                s->exp_ref_block[ch][blk1] = blk;
591
11024
                blk1++;
592
            }
593
3154
            num_reuse_blocks = blk1 - blk - 1;
594
595
            /* for the EXP_REUSE case we select the min of the exponents */
596
3154
            s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
597
                                       AC3_MAX_COEFS);
598
599
3154
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
600
601
3154
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
602
3154
            blk = blk1;
603
        }
604
    }
605
606
    /* reference block numbers have been changed, so reset ref_bap_set */
607
925
    s->ref_bap_set = 0;
608
925
}
609
610
611
/*
612
 * Count exponent bits based on bandwidth, coupling, and exponent strategies.
613
 */
614
925
static int count_exponent_bits(AC3EncodeContext *s)
615
{
616
    int blk, ch;
617
    int nb_groups, bit_count;
618
619
925
    bit_count = 0;
620
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
621
5550
        AC3Block *block = &s->blocks[blk];
622
19728
        for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
623
14178
            int exp_strategy = s->exp_strategy[ch][blk];
624
14178
            int cpl          = (ch == CPL_CH);
625
14178
            int nb_coefs     = block->end_freq[ch] - s->start_freq[ch];
626
627
14178
            if (exp_strategy == EXP_REUSE)
628
11024
                continue;
629
630
3154
            nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_coefs];
631
3154
            bit_count += 4 + (nb_groups * 7);
632
        }
633
    }
634
635
925
    return bit_count;
636
}
637
638
639
/**
640
 * Group exponents.
641
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
642
 * varies depending on exponent strategy and bandwidth.
643
 *
644
 * @param s  AC-3 encoder private context
645
 */
646
925
static void ac3_group_exponents(AC3EncodeContext *s)
647
{
648
    int blk, ch, i, cpl;
649
    int group_size, nb_groups;
650
    uint8_t *p;
651
    int delta0, delta1, delta2;
652
    int exp0, exp1;
653
654
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
655
5550
        AC3Block *block = &s->blocks[blk];
656
19728
        for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
657
14178
            int exp_strategy = s->exp_strategy[ch][blk];
658
14178
            if (exp_strategy == EXP_REUSE)
659
11024
                continue;
660
3154
            cpl = (ch == CPL_CH);
661
3154
            group_size = exp_strategy + (exp_strategy == EXP_D45);
662
3154
            nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
663
3154
            p = block->exp[ch] + s->start_freq[ch] - cpl;
664
665
            /* DC exponent */
666
3154
            exp1 = *p++;
667
3154
            block->grouped_exp[ch][0] = exp1;
668
669
            /* remaining exponents are delta encoded */
670
82692
            for (i = 1; i <= nb_groups; i++) {
671
                /* merge three delta in one code */
672
79538
                exp0   = exp1;
673
79538
                exp1   = p[0];
674
79538
                p     += group_size;
675
79538
                delta0 = exp1 - exp0 + 2;
676
                av_assert2(delta0 >= 0 && delta0 <= 4);
677
678
79538
                exp0   = exp1;
679
79538
                exp1   = p[0];
680
79538
                p     += group_size;
681
79538
                delta1 = exp1 - exp0 + 2;
682
                av_assert2(delta1 >= 0 && delta1 <= 4);
683
684
79538
                exp0   = exp1;
685
79538
                exp1   = p[0];
686
79538
                p     += group_size;
687
79538
                delta2 = exp1 - exp0 + 2;
688
                av_assert2(delta2 >= 0 && delta2 <= 4);
689
690
79538
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
691
            }
692
        }
693
    }
694
925
}
695
696
697
/**
698
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
699
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
700
 * and encode final exponents.
701
 *
702
 * @param s  AC-3 encoder private context
703
 */
704
925
static void ac3_process_exponents(AC3EncodeContext *s)
705
{
706
925
    extract_exponents(s);
707
708
925
    compute_exp_strategy(s);
709
710
925
    encode_exponents(s);
711
712
925
    emms_c();
713
925
}
714
715
716
/*
717
 * Count frame bits that are based solely on fixed parameters.
718
 * This only has to be run once when the encoder is initialized.
719
 */
720
6
static void count_frame_bits_fixed(AC3EncodeContext *s)
721
{
722
    static const uint8_t frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
723
    int blk;
724
    int frame_bits;
725
726
    /* assumptions:
727
     *   no dynamic range codes
728
     *   bit allocation parameters do not change between blocks
729
     *   no delta bit allocation
730
     *   no skipped data
731
     *   no auxiliary data
732
     *   no E-AC-3 metadata
733
     */
734
735
    /* header */
736
6
    frame_bits = 16; /* sync info */
737
6
    if (s->eac3) {
738
        /* bitstream info header */
739
1
        frame_bits += 35;
740
1
        frame_bits += 1 + 1;
741
1
        if (s->num_blocks != 0x6)
742
            frame_bits++;
743
1
        frame_bits++;
744
        /* audio frame header */
745
1
        if (s->num_blocks == 6)
746
1
            frame_bits += 2;
747
1
        frame_bits += 10;
748
        /* exponent strategy */
749
1
        if (s->use_frame_exp_strategy)
750
            frame_bits += 5 * s->fbw_channels;
751
        else
752
1
            frame_bits += s->num_blocks * 2 * s->fbw_channels;
753
1
        if (s->lfe_on)
754
            frame_bits += s->num_blocks;
755
        /* converter exponent strategy */
756
1
        if (s->num_blks_code != 0x3)
757
            frame_bits++;
758
        else
759
1
            frame_bits += s->fbw_channels * 5;
760
        /* snr offsets */
761
1
        frame_bits += 10;
762
        /* block start info */
763
1
        if (s->num_blocks != 1)
764
1
            frame_bits++;
765
    } else {
766
5
        frame_bits += 49;
767
5
        frame_bits += frame_bits_inc[s->channel_mode];
768
    }
769
770
    /* audio blocks */
771
42
    for (blk = 0; blk < s->num_blocks; blk++) {
772
36
        if (!s->eac3) {
773
            /* block switch flags */
774
30
            frame_bits += s->fbw_channels;
775
776
            /* dither flags */
777
30
            frame_bits += s->fbw_channels;
778
        }
779
780
        /* dynamic range */
781
36
        frame_bits++;
782
783
        /* spectral extension */
784
36
        if (s->eac3)
785
6
            frame_bits++;
786
787
        /* coupling strategy exists: cplstre */
788
36
        if (!s->eac3)
789
30
            frame_bits++;
790
791
36
        if (!s->eac3) {
792
            /* exponent strategy */
793
30
            frame_bits += 2 * s->fbw_channels;
794
30
            if (s->lfe_on)
795
                frame_bits++;
796
797
            /* bit allocation params */
798
30
            frame_bits++;
799
30
            if (!blk)
800
5
                frame_bits += 2 + 2 + 2 + 2 + 3;
801
        }
802
803
        /* snroffste for AC-3, convsnroffste for E-AC-3 */
804
36
        frame_bits++;
805
806
36
        if (!s->eac3) {
807
            /* delta bit allocation */
808
30
            frame_bits++;
809
810
            /* skipped data */
811
30
            frame_bits++;
812
        }
813
    }
814
815
    /* auxiliary data */
816
6
    frame_bits++;
817
818
    /* CRC */
819
6
    frame_bits += 1 + 16;
820
821
6
    s->frame_bits_fixed = frame_bits;
822
6
}
823
824
825
/*
826
 * Initialize bit allocation.
827
 * Set default parameter codes and calculate parameter values.
828
 */
829
6
static av_cold void bit_alloc_init(AC3EncodeContext *s)
830
{
831
    int ch;
832
833
    /* init default parameters */
834
6
    s->slow_decay_code = 2;
835
6
    s->fast_decay_code = 1;
836
6
    s->slow_gain_code  = 1;
837
6
    s->db_per_bit_code = s->eac3 ? 2 : 3;
838
6
    s->floor_code      = 7;
839
21
    for (ch = 0; ch <= s->channels; ch++)
840
15
        s->fast_gain_code[ch] = 4;
841
842
    /* initial snr offset */
843
6
    s->coarse_snr_offset = 40;
844
845
    /* compute real values */
846
    /* currently none of these values change during encoding, so we can just
847
       set them once at initialization */
848
6
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
849
6
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
850
6
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
851
6
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
852
6
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
853
6
    s->bit_alloc.cpl_fast_leak = 0;
854
6
    s->bit_alloc.cpl_slow_leak = 0;
855
856
6
    count_frame_bits_fixed(s);
857
6
}
858
859
860
/*
861
 * Count the bits used to encode the frame, minus exponents and mantissas.
862
 * Bits based on fixed parameters have already been counted, so now we just
863
 * have to add the bits based on parameters that change during encoding.
864
 */
865
925
static void count_frame_bits(AC3EncodeContext *s)
866
{
867
925
    AC3EncOptions *opt = &s->options;
868
    int blk, ch;
869
925
    int frame_bits = 0;
870
871
    /* header */
872
925
    if (s->eac3) {
873
273
        if (opt->eac3_mixing_metadata) {
874
            if (s->channel_mode > AC3_CHMODE_STEREO)
875
                frame_bits += 2;
876
            if (s->has_center)
877
                frame_bits += 6;
878
            if (s->has_surround)
879
                frame_bits += 6;
880
            frame_bits += s->lfe_on;
881
            frame_bits += 1 + 1 + 2;
882
            if (s->channel_mode < AC3_CHMODE_STEREO)
883
                frame_bits++;
884
            frame_bits++;
885
        }
886
273
        if (opt->eac3_info_metadata) {
887
            frame_bits += 3 + 1 + 1;
888
            if (s->channel_mode == AC3_CHMODE_STEREO)
889
                frame_bits += 2 + 2;
890
            if (s->channel_mode >= AC3_CHMODE_2F2R)
891
                frame_bits += 2;
892
            frame_bits++;
893
            if (opt->audio_production_info)
894
                frame_bits += 5 + 2 + 1;
895
            frame_bits++;
896
        }
897
        /* coupling */
898
273
        if (s->channel_mode > AC3_CHMODE_MONO) {
899
273
            frame_bits++;
900
1638
            for (blk = 1; blk < s->num_blocks; blk++) {
901
1365
                AC3Block *block = &s->blocks[blk];
902
1365
                frame_bits++;
903
1365
                if (block->new_cpl_strategy)
904
                    frame_bits++;
905
            }
906
        }
907
        /* coupling exponent strategy */
908
273
        if (s->cpl_on) {
909
273
            if (s->use_frame_exp_strategy) {
910
273
                frame_bits += 5;
911
            } else {
912
                for (blk = 0; blk < s->num_blocks; blk++)
913
                    frame_bits += 2 * s->blocks[blk].cpl_in_use;
914
            }
915
        }
916
    } else {
917
652
        if (opt->audio_production_info)
918
            frame_bits += 7;
919
652
        if (s->bitstream_id == 6) {
920
            if (opt->extended_bsi_1)
921
                frame_bits += 14;
922
            if (opt->extended_bsi_2)
923
                frame_bits += 14;
924
        }
925
    }
926
927
    /* audio blocks */
928
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
929
5550
        AC3Block *block = &s->blocks[blk];
930
931
        /* coupling strategy */
932
5550
        if (block->new_cpl_strategy) {
933
925
            if (!s->eac3)
934
652
                frame_bits++;
935
925
            if (block->cpl_in_use) {
936
719
                if (s->eac3)
937
273
                    frame_bits++;
938

719
                if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
939
446
                    frame_bits += s->fbw_channels;
940
719
                if (s->channel_mode == AC3_CHMODE_STEREO)
941
719
                    frame_bits++;
942
719
                frame_bits += 4 + 4;
943
719
                if (s->eac3)
944
273
                    frame_bits++;
945
                else
946
446
                    frame_bits += s->num_cpl_subbands - 1;
947
            }
948
        }
949
950
        /* coupling coordinates */
951
5550
        if (block->cpl_in_use) {
952
12942
            for (ch = 1; ch <= s->fbw_channels; ch++) {
953
8628
                if (block->channel_in_cpl[ch]) {
954

8628
                    if (!s->eac3 || block->new_cpl_coords[ch] != 2)
955
8082
                        frame_bits++;
956
8628
                    if (block->new_cpl_coords[ch]) {
957
1470
                        frame_bits += 2;
958
1470
                        frame_bits += (4 + 4) * s->num_cpl_bands;
959
                    }
960
                }
961
            }
962
        }
963
964
        /* stereo rematrixing */
965
5550
        if (s->channel_mode == AC3_CHMODE_STEREO) {
966

4314
            if (!s->eac3 || blk > 0)
967
4041
                frame_bits++;
968
4314
            if (s->blocks[blk].new_rematrixing_strategy)
969
2197
                frame_bits += block->num_rematrixing_bands;
970
        }
971
972
        /* bandwidth codes & gain range */
973
15414
        for (ch = 1; ch <= s->fbw_channels; ch++) {
974
9864
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
975
1750
                if (!block->channel_in_cpl[ch])
976
221
                    frame_bits += 6;
977
1750
                frame_bits += 2;
978
            }
979
        }
980
981
        /* coupling exponent strategy */
982

5550
        if (!s->eac3 && block->cpl_in_use)
983
2676
            frame_bits += 2;
984
985
        /* snr offsets and fast gain codes */
986
5550
        if (!s->eac3) {
987
3912
            if (block->new_snr_offsets)
988
652
                frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
989
        }
990
991
        /* coupling leak info */
992
5550
        if (block->cpl_in_use) {
993

4314
            if (!s->eac3 || block->new_cpl_leak != 2)
994
4041
                frame_bits++;
995
4314
            if (block->new_cpl_leak)
996
719
                frame_bits += 3 + 3;
997
        }
998
    }
999
1000
925
    s->frame_bits = s->frame_bits_fixed + frame_bits;
1001
925
}
1002
1003
1004
/*
1005
 * Calculate masking curve based on the final exponents.
1006
 * Also calculate the power spectral densities to use in future calculations.
1007
 */
1008
925
static void bit_alloc_masking(AC3EncodeContext *s)
1009
{
1010
    int blk, ch;
1011
1012
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
1013
5550
        AC3Block *block = &s->blocks[blk];
1014
19728
        for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1015
            /* We only need psd and mask for calculating bap.
1016
               Since we currently do not calculate bap when exponent
1017
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
1018
14178
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1019
3154
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1020
3154
                                          block->end_freq[ch], block->psd[ch],
1021
3154
                                          block->band_psd[ch]);
1022
3154
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1023
                                           s->start_freq[ch], block->end_freq[ch],
1024
3154
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1025
3154
                                           ch == s->lfe_channel,
1026
                                           DBA_NONE, 0, NULL, NULL, NULL,
1027
3154
                                           block->mask[ch]);
1028
            }
1029
        }
1030
    }
1031
925
}
1032
1033
1034
/*
1035
 * Ensure that bap for each block and channel point to the current bap_buffer.
1036
 * They may have been switched during the bit allocation search.
1037
 */
1038
8802
static void reset_block_bap(AC3EncodeContext *s)
1039
{
1040
    int blk, ch;
1041
    uint8_t *ref_bap;
1042
1043

8802
    if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
1044
2967
        return;
1045
1046
5835
    ref_bap = s->bap_buffer;
1047
21996
    for (ch = 0; ch <= s->channels; ch++) {
1048
113127
        for (blk = 0; blk < s->num_blocks; blk++)
1049
96966
            s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
1050
16161
        ref_bap += AC3_MAX_COEFS * s->num_blocks;
1051
    }
1052
5835
    s->ref_bap_set = 1;
1053
}
1054
1055
1056
/**
1057
 * Initialize mantissa counts.
1058
 * These are set so that they are padded to the next whole group size when bits
1059
 * are counted in compute_mantissa_size.
1060
 *
1061
 * @param[in,out] mant_cnt  running counts for each bap value for each block
1062
 */
1063
7877
static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
1064
{
1065
    int blk;
1066
1067
55139
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1068
47262
        memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
1069
47262
        mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
1070
47262
        mant_cnt[blk][4] = 1;
1071
    }
1072
7877
}
1073
1074
1075
/**
1076
 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
1077
 * range.
1078
 *
1079
 * @param s                 AC-3 encoder private context
1080
 * @param ch                channel index
1081
 * @param[in,out] mant_cnt  running counts for each bap value for each block
1082
 * @param start             starting coefficient bin
1083
 * @param end               ending coefficient bin
1084
 */
1085
20001
static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
1086
                                          uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
1087
                                          int start, int end)
1088
{
1089
    int blk;
1090
1091
140007
    for (blk = 0; blk < s->num_blocks; blk++) {
1092
120006
        AC3Block *block = &s->blocks[blk];
1093

120006
        if (ch == CPL_CH && !block->cpl_in_use)
1094
            continue;
1095
120006
        s->ac3dsp.update_bap_counts(mant_cnt[blk],
1096
120006
                                    s->ref_bap[ch][blk] + start,
1097
120006
                                    FFMIN(end, block->end_freq[ch]) - start);
1098
    }
1099
20001
}
1100
1101
1102
/*
1103
 * Count the number of mantissa bits in the frame based on the bap values.
1104
 */
1105
7877
static int count_mantissa_bits(AC3EncodeContext *s)
1106
{
1107
    int ch, max_end_freq;
1108
7877
    LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
1109
1110
7877
    count_mantissa_bits_init(mant_cnt);
1111
1112
7877
    max_end_freq = s->bandwidth_code * 3 + 73;
1113
27878
    for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
1114
20001
        count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1115
                                      max_end_freq);
1116
1117
7877
    return s->ac3dsp.compute_mantissa_size(mant_cnt);
1118
}
1119
1120
1121
/**
1122
 * Run the bit allocation with a given SNR offset.
1123
 * This calculates the bit allocation pointers that will be used to determine
1124
 * the quantization of each mantissa.
1125
 *
1126
 * @param s           AC-3 encoder private context
1127
 * @param snr_offset  SNR offset, 0 to 1023
1128
 * @return the number of bits needed for mantissas if the given SNR offset is
1129
 *         is used.
1130
 */
1131
7877
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1132
{
1133
    int blk, ch;
1134
1135
7877
    snr_offset = (snr_offset - 240) * 4;
1136
1137
7877
    reset_block_bap(s);
1138
55139
    for (blk = 0; blk < s->num_blocks; blk++) {
1139
47262
        AC3Block *block = &s->blocks[blk];
1140
1141
167268
        for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1142
            /* Currently the only bit allocation parameters which vary across
1143
               blocks within a frame are the exponent values.  We can take
1144
               advantage of that by reusing the bit allocation pointers
1145
               whenever we reuse exponents. */
1146
120006
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1147
26777
                s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1148
                                             s->start_freq[ch], block->end_freq[ch],
1149
                                             snr_offset, s->bit_alloc.floor,
1150
                                             ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1151
            }
1152
        }
1153
    }
1154
7877
    return count_mantissa_bits(s);
1155
}
1156
1157
1158
/*
1159
 * Constant bitrate bit allocation search.
1160
 * Find the largest SNR offset that will allow data to fit in the frame.
1161
 */
1162
925
static int cbr_bit_allocation(AC3EncodeContext *s)
1163
{
1164
    int ch;
1165
    int bits_left;
1166
    int snr_offset, snr_incr;
1167
1168
925
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1169
925
    if (bits_left < 0)
1170
        return AVERROR(EINVAL);
1171
1172
925
    snr_offset = s->coarse_snr_offset << 4;
1173
1174
    /* if previous frame SNR offset was 1023, check if current frame can also
1175
       use SNR offset of 1023. if so, skip the search. */
1176
925
    if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1177
        if (bit_alloc(s, 1023) <= bits_left)
1178
            return 0;
1179
    }
1180
1181

2234
    while (snr_offset >= 0 &&
1182
1117
           bit_alloc(s, snr_offset) > bits_left) {
1183
192
        snr_offset -= 64;
1184
    }
1185
925
    if (snr_offset < 0)
1186
        return AVERROR(EINVAL);
1187
1188
925
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1189
4625
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1190

13520
        while (snr_offset + snr_incr <= 1023 &&
1191
6760
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1192
3060
            snr_offset += snr_incr;
1193
3060
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1194
        }
1195
    }
1196
925
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1197
925
    reset_block_bap(s);
1198
1199
925
    s->coarse_snr_offset = snr_offset >> 4;
1200
3288
    for (ch = !s->cpl_on; ch <= s->channels; ch++)
1201
2363
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1202
1203
925
    return 0;
1204
}
1205
1206
1207
/*
1208
 * Perform bit allocation search.
1209
 * Finds the SNR offset value that maximizes quality and fits in the specified
1210
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1211
 * used to quantize the mantissas.
1212
 */
1213
925
static int ac3_compute_bit_allocation(AC3EncodeContext *s)
1214
{
1215
925
    count_frame_bits(s);
1216
1217
925
    s->exponent_bits = count_exponent_bits(s);
1218
1219
925
    bit_alloc_masking(s);
1220
1221
925
    return cbr_bit_allocation(s);
1222
}
1223
1224
1225
/**
1226
 * Symmetric quantization on 'levels' levels.
1227
 *
1228
 * @param c       unquantized coefficient
1229
 * @param e       exponent
1230
 * @param levels  number of quantization levels
1231
 * @return        quantized coefficient
1232
 */
1233
931204
static inline int sym_quant(int c, int e, int levels)
1234
{
1235
931204
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1236
    av_assert2(v >= 0 && v < levels);
1237
931204
    return v;
1238
}
1239
1240
1241
/**
1242
 * Asymmetric quantization on 2^qbits levels.
1243
 *
1244
 * @param c      unquantized coefficient
1245
 * @param e      exponent
1246
 * @param qbits  number of quantization bits
1247
 * @return       quantized coefficient
1248
 */
1249
101024
static inline int asym_quant(int c, int e, int qbits)
1250
{
1251
    int m;
1252
1253
101024
    c = (((c * (1<<e)) >> (24 - qbits)) + 1) >> 1;
1254
101024
    m = (1 << (qbits-1));
1255
101024
    if (c >= m)
1256
149
        c = m - 1;
1257
    av_assert2(c >= -m);
1258
101024
    return c;
1259
}
1260
1261
1262
/**
1263
 * Quantize a set of mantissas for a single channel in a single block.
1264
 *
1265
 * @param s           Mantissa count context
1266
 * @param fixed_coef  unquantized fixed-point coefficients
1267
 * @param exp         exponents
1268
 * @param bap         bit allocation pointer indices
1269
 * @param[out] qmant  quantized coefficients
1270
 * @param start_freq  starting coefficient bin
1271
 * @param end_freq    ending coefficient bin
1272
 */
1273
14178
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1274
                                      uint8_t *exp, uint8_t *bap,
1275
                                      int16_t *qmant, int start_freq,
1276
                                      int end_freq)
1277
{
1278
    int i;
1279
1280
1389018
    for (i = start_freq; i < end_freq; i++) {
1281
1374840
        int c = fixed_coef[i];
1282
1374840
        int e = exp[i];
1283
1374840
        int v = bap[i];
1284


1374840
        switch (v) {
1285
342612
        case 0:
1286
342612
            break;
1287
437576
        case 1:
1288
437576
            v = sym_quant(c, e, 3);
1289
437576
            switch (s->mant1_cnt) {
1290
147558
            case 0:
1291
147558
                s->qmant1_ptr = &qmant[i];
1292
147558
                v = 9 * v;
1293
147558
                s->mant1_cnt = 1;
1294
147558
                break;
1295
145931
            case 1:
1296
145931
                *s->qmant1_ptr += 3 * v;
1297
145931
                s->mant1_cnt = 2;
1298
145931
                v = 128;
1299
145931
                break;
1300
144087
            default:
1301
144087
                *s->qmant1_ptr += v;
1302
144087
                s->mant1_cnt = 0;
1303
144087
                v = 128;
1304
144087
                break;
1305
            }
1306
437576
            break;
1307
177528
        case 2:
1308
177528
            v = sym_quant(c, e, 5);
1309
177528
            switch (s->mant2_cnt) {
1310
60838
            case 0:
1311
60838
                s->qmant2_ptr = &qmant[i];
1312
60838
                v = 25 * v;
1313
60838
                s->mant2_cnt = 1;
1314
60838
                break;
1315
59235
            case 1:
1316
59235
                *s->qmant2_ptr += 5 * v;
1317
59235
                s->mant2_cnt = 2;
1318
59235
                v = 128;
1319
59235
                break;
1320
57455
            default:
1321
57455
                *s->qmant2_ptr += v;
1322
57455
                s->mant2_cnt = 0;
1323
57455
                v = 128;
1324
57455
                break;
1325
            }
1326
177528
            break;
1327
181669
        case 3:
1328
181669
            v = sym_quant(c, e, 7);
1329
181669
            break;
1330
79589
        case 4:
1331
79589
            v = sym_quant(c, e, 11);
1332
79589
            switch (s->mant4_cnt) {
1333
40925
            case 0:
1334
40925
                s->qmant4_ptr = &qmant[i];
1335
40925
                v = 11 * v;
1336
40925
                s->mant4_cnt = 1;
1337
40925
                break;
1338
38664
            default:
1339
38664
                *s->qmant4_ptr += v;
1340
38664
                s->mant4_cnt = 0;
1341
38664
                v = 128;
1342
38664
                break;
1343
            }
1344
79589
            break;
1345
54842
        case 5:
1346
54842
            v = sym_quant(c, e, 15);
1347
54842
            break;
1348
9065
        case 14:
1349
9065
            v = asym_quant(c, e, 14);
1350
9065
            break;
1351
4398
        case 15:
1352
4398
            v = asym_quant(c, e, 16);
1353
4398
            break;
1354
87561
        default:
1355
87561
            v = asym_quant(c, e, v - 1);
1356
87561
            break;
1357
        }
1358
1374840
        qmant[i] = v;
1359
    }
1360
14178
}
1361
1362
1363
/**
1364
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1365
 *
1366
 * @param s  AC-3 encoder private context
1367
 */
1368
925
static void ac3_quantize_mantissas(AC3EncodeContext *s)
1369
{
1370
925
    int blk, ch, ch0=0, got_cpl;
1371
1372
6475
    for (blk = 0; blk < s->num_blocks; blk++) {
1373
5550
        AC3Block *block = &s->blocks[blk];
1374
5550
        AC3Mant m = { 0 };
1375
1376
5550
        got_cpl = !block->cpl_in_use;
1377
19728
        for (ch = 1; ch <= s->channels; ch++) {
1378

14178
            if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1379
4314
                ch0     = ch - 1;
1380
4314
                ch      = CPL_CH;
1381
4314
                got_cpl = 1;
1382
            }
1383
14178
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1384
14178
                                      s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1385
14178
                                      s->ref_bap[ch][blk], block->qmant[ch],
1386
                                      s->start_freq[ch], block->end_freq[ch]);
1387
14178
            if (ch == CPL_CH)
1388
4314
                ch = ch0;
1389
        }
1390
    }
1391
925
}
1392
1393
1394
/*
1395
 * Write the AC-3 frame header to the output bitstream.
1396
 */
1397
652
static void ac3_output_frame_header(AC3EncodeContext *s)
1398
{
1399
652
    AC3EncOptions *opt = &s->options;
1400
1401
652
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1402
652
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1403
652
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1404
652
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1405
652
    put_bits(&s->pb, 5,  s->bitstream_id);
1406
652
    put_bits(&s->pb, 3,  s->bitstream_mode);
1407
652
    put_bits(&s->pb, 3,  s->channel_mode);
1408

652
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1409
        put_bits(&s->pb, 2, s->center_mix_level);
1410
652
    if (s->channel_mode & 0x04)
1411
        put_bits(&s->pb, 2, s->surround_mix_level);
1412
652
    if (s->channel_mode == AC3_CHMODE_STEREO)
1413
446
        put_bits(&s->pb, 2, opt->dolby_surround_mode);
1414
652
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1415
652
    put_bits(&s->pb, 5, -opt->dialogue_level);
1416
652
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1417
652
    put_bits(&s->pb, 1, 0);         /* no lang code */
1418
652
    put_bits(&s->pb, 1, opt->audio_production_info);
1419
652
    if (opt->audio_production_info) {
1420
        put_bits(&s->pb, 5, opt->mixing_level - 80);
1421
        put_bits(&s->pb, 2, opt->room_type);
1422
    }
1423
652
    put_bits(&s->pb, 1, opt->copyright);
1424
652
    put_bits(&s->pb, 1, opt->original);
1425
652
    if (s->bitstream_id == 6) {
1426
        /* alternate bit stream syntax */
1427
        put_bits(&s->pb, 1, opt->extended_bsi_1);
1428
        if (opt->extended_bsi_1) {
1429
            put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1430
            put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1431
            put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1432
            put_bits(&s->pb, 3, s->loro_center_mix_level);
1433
            put_bits(&s->pb, 3, s->loro_surround_mix_level);
1434
        }
1435
        put_bits(&s->pb, 1, opt->extended_bsi_2);
1436
        if (opt->extended_bsi_2) {
1437
            put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1438
            put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1439
            put_bits(&s->pb, 1, opt->ad_converter_type);
1440
            put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1441
        }
1442
    } else {
1443
652
        put_bits(&s->pb, 1, 0);     /* no time code 1 */
1444
652
        put_bits(&s->pb, 1, 0);     /* no time code 2 */
1445
    }
1446
652
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1447
652
}
1448
1449
1450
/*
1451
 * Write one audio block to the output bitstream.
1452
 */
1453
5550
static void output_audio_block(AC3EncodeContext *s, int blk)
1454
{
1455
5550
    int ch, i, baie, bnd, got_cpl, av_uninit(ch0);
1456
5550
    AC3Block *block = &s->blocks[blk];
1457
1458
    /* block switching */
1459
5550
    if (!s->eac3) {
1460
10500
        for (ch = 0; ch < s->fbw_channels; ch++)
1461
6588
            put_bits(&s->pb, 1, 0);
1462
    }
1463
1464
    /* dither flags */
1465
5550
    if (!s->eac3) {
1466
10500
        for (ch = 0; ch < s->fbw_channels; ch++)
1467
6588
            put_bits(&s->pb, 1, 1);
1468
    }
1469
1470
    /* dynamic range codes */
1471
5550
    put_bits(&s->pb, 1, 0);
1472
1473
    /* spectral extension */
1474
5550
    if (s->eac3)
1475
1638
        put_bits(&s->pb, 1, 0);
1476
1477
    /* channel coupling */
1478
5550
    if (!s->eac3)
1479
3912
        put_bits(&s->pb, 1, block->new_cpl_strategy);
1480
5550
    if (block->new_cpl_strategy) {
1481
925
        if (!s->eac3)
1482
652
            put_bits(&s->pb, 1, block->cpl_in_use);
1483
925
        if (block->cpl_in_use) {
1484
            int start_sub, end_sub;
1485
719
            if (s->eac3)
1486
273
                put_bits(&s->pb, 1, 0); /* enhanced coupling */
1487

719
            if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1488
1338
                for (ch = 1; ch <= s->fbw_channels; ch++)
1489
892
                    put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1490
            }
1491
719
            if (s->channel_mode == AC3_CHMODE_STEREO)
1492
719
                put_bits(&s->pb, 1, 0); /* phase flags in use */
1493
719
            start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1494
719
            end_sub   = (s->cpl_end_freq       - 37) / 12;
1495
719
            put_bits(&s->pb, 4, start_sub);
1496
719
            put_bits(&s->pb, 4, end_sub - 3);
1497
            /* coupling band structure */
1498
719
            if (s->eac3) {
1499
273
                put_bits(&s->pb, 1, 0); /* use default */
1500
            } else {
1501
2230
                for (bnd = start_sub+1; bnd < end_sub; bnd++)
1502
1784
                    put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1503
            }
1504
        }
1505
    }
1506
1507
    /* coupling coordinates */
1508
5550
    if (block->cpl_in_use) {
1509
12942
        for (ch = 1; ch <= s->fbw_channels; ch++) {
1510
8628
            if (block->channel_in_cpl[ch]) {
1511

8628
                if (!s->eac3 || block->new_cpl_coords[ch] != 2)
1512
8082
                    put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
1513
8628
                if (block->new_cpl_coords[ch]) {
1514
1470
                    put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1515
7350
                    for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1516
5880
                        put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1517
5880
                        put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1518
                    }
1519
                }
1520
            }
1521
        }
1522
    }
1523
1524
    /* stereo rematrixing */
1525
5550
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1526

4314
        if (!s->eac3 || blk > 0)
1527
4041
            put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1528
4314
        if (block->new_rematrixing_strategy) {
1529
            /* rematrixing flags */
1530
10985
            for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1531
8788
                put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1532
        }
1533
    }
1534
1535
    /* exponent strategy */
1536
5550
    if (!s->eac3) {
1537
13176
        for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1538
9264
            put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1539
3912
        if (s->lfe_on)
1540
            put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1541
    }
1542
1543
    /* bandwidth */
1544
15414
    for (ch = 1; ch <= s->fbw_channels; ch++) {
1545

9864
        if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1546
221
            put_bits(&s->pb, 6, s->bandwidth_code);
1547
    }
1548
1549
    /* exponents */
1550
19728
    for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1551
        int nb_groups;
1552
14178
        int cpl = (ch == CPL_CH);
1553
1554
14178
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1555
11024
            continue;
1556
1557
        /* DC exponent */
1558
3154
        put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1559
1560
        /* exponent groups */
1561
3154
        nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1562
82692
        for (i = 1; i <= nb_groups; i++)
1563
79538
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1564
1565
        /* gain range info */
1566

3154
        if (ch != s->lfe_channel && !cpl)
1567
1750
            put_bits(&s->pb, 2, 0);
1568
    }
1569
1570
    /* bit allocation info */
1571
5550
    if (!s->eac3) {
1572
3912
        baie = (blk == 0);
1573
3912
        put_bits(&s->pb, 1, baie);
1574
3912
        if (baie) {
1575
652
            put_bits(&s->pb, 2, s->slow_decay_code);
1576
652
            put_bits(&s->pb, 2, s->fast_decay_code);
1577
652
            put_bits(&s->pb, 2, s->slow_gain_code);
1578
652
            put_bits(&s->pb, 2, s->db_per_bit_code);
1579
652
            put_bits(&s->pb, 3, s->floor_code);
1580
        }
1581
    }
1582
1583
    /* snr offset */
1584
5550
    if (!s->eac3) {
1585
3912
        put_bits(&s->pb, 1, block->new_snr_offsets);
1586
3912
        if (block->new_snr_offsets) {
1587
652
            put_bits(&s->pb, 6, s->coarse_snr_offset);
1588
2196
            for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1589
1544
                put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1590
1544
                put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1591
            }
1592
        }
1593
    } else {
1594
1638
        put_bits(&s->pb, 1, 0); /* no converter snr offset */
1595
    }
1596
1597
    /* coupling leak */
1598
5550
    if (block->cpl_in_use) {
1599

4314
        if (!s->eac3 || block->new_cpl_leak != 2)
1600
4041
            put_bits(&s->pb, 1, block->new_cpl_leak);
1601
4314
        if (block->new_cpl_leak) {
1602
719
            put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1603
719
            put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1604
        }
1605
    }
1606
1607
5550
    if (!s->eac3) {
1608
3912
        put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1609
3912
        put_bits(&s->pb, 1, 0); /* no data to skip */
1610
    }
1611
1612
    /* mantissas */
1613
5550
    got_cpl = !block->cpl_in_use;
1614
19728
    for (ch = 1; ch <= s->channels; ch++) {
1615
        int b, q;
1616
1617

14178
        if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1618
4314
            ch0     = ch - 1;
1619
4314
            ch      = CPL_CH;
1620
4314
            got_cpl = 1;
1621
        }
1622
1389018
        for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1623
1374840
            q = block->qmant[ch][i];
1624
1374840
            b = s->ref_bap[ch][blk][i];
1625


1374840
            switch (b) {
1626
342612
            case 0:                                          break;
1627
437576
            case 1: if (q != 128) put_bits (&s->pb,   5, q); break;
1628
177528
            case 2: if (q != 128) put_bits (&s->pb,   7, q); break;
1629
181669
            case 3:               put_sbits(&s->pb,   3, q); break;
1630
79589
            case 4: if (q != 128) put_bits (&s->pb,   7, q); break;
1631
9065
            case 14:              put_sbits(&s->pb,  14, q); break;
1632
4398
            case 15:              put_sbits(&s->pb,  16, q); break;
1633
142403
            default:              put_sbits(&s->pb, b-1, q); break;
1634
            }
1635
        }
1636
14178
        if (ch == CPL_CH)
1637
4314
            ch = ch0;
1638
    }
1639
5550
}
1640
1641
1642
/** CRC-16 Polynomial */
1643
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1644
1645
1646
834
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1647
{
1648
    unsigned int c;
1649
1650
834
    c = 0;
1651
13544
    while (a) {
1652
12710
        if (a & 1)
1653
6338
            c ^= b;
1654
12710
        a = a >> 1;
1655
12710
        b = b << 1;
1656
12710
        if (b & (1 << 16))
1657
6131
            b ^= poly;
1658
    }
1659
834
    return c;
1660
}
1661
1662
1663
12
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1664
{
1665
    unsigned int r;
1666
12
    r = 1;
1667
154
    while (n) {
1668
142
        if (n & 1)
1669
40
            r = mul_poly(r, a, poly);
1670
142
        a = mul_poly(a, a, poly);
1671
142
        n >>= 1;
1672
    }
1673
12
    return r;
1674
}
1675
1676
1677
/*
1678
 * Fill the end of the frame with 0's and compute the two CRCs.
1679
 */
1680
925
static void output_frame_end(AC3EncodeContext *s)
1681
{
1682
925
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1683
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1684
    uint8_t *frame;
1685
1686
925
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1687
1688
    /* pad the remainder of the frame with zeros */
1689
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1690
925
    flush_put_bits(&s->pb);
1691
925
    frame = s->pb.buf;
1692
925
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1693
    av_assert2(pad_bytes >= 0);
1694
925
    if (pad_bytes > 0)
1695
845
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1696
1697
925
    if (s->eac3) {
1698
        /* compute crc2 */
1699
273
        crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1700
    } else {
1701
        /* compute crc1 */
1702
        /* this is not so easy because it is at the beginning of the data... */
1703
652
        crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1704
652
        crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1705
652
        crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1706
652
        AV_WB16(frame + 2, crc1);
1707
1708
        /* compute crc2 */
1709
652
        crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1710
652
                              s->frame_size - frame_size_58 - 3);
1711
    }
1712
925
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1713
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1714
925
    if (crc2 == 0x770B) {
1715
        frame[s->frame_size - 3] ^= 0x1;
1716
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1717
    }
1718
925
    crc2 = av_bswap16(crc2);
1719
925
    AV_WB16(frame + s->frame_size - 2, crc2);
1720
925
}
1721
1722
1723
/**
1724
 * Write the frame to the output bitstream.
1725
 *
1726
 * @param s      AC-3 encoder private context
1727
 * @param frame  output data buffer
1728
 */
1729
925
static void ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1730
{
1731
    int blk;
1732
1733
925
    init_put_bits(&s->pb, frame, s->frame_size);
1734
1735
925
    s->output_frame_header(s);
1736
1737
6475
    for (blk = 0; blk < s->num_blocks; blk++)
1738
5550
        output_audio_block(s, blk);
1739
1740
925
    output_frame_end(s);
1741
925
}
1742
1743
925
int ff_ac3_encode_frame_common_end(AVCodecContext *avctx, AVPacket *avpkt,
1744
                                   const AVFrame *frame, int *got_packet_ptr)
1745
{
1746
925
    AC3EncodeContext *const s = avctx->priv_data;
1747
    int ret;
1748
1749
925
    ac3_apply_rematrixing(s);
1750
1751
925
    ac3_process_exponents(s);
1752
1753
925
    ret = ac3_compute_bit_allocation(s);
1754
925
    if (ret) {
1755
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1756
        return ret;
1757
    }
1758
1759
925
    ac3_group_exponents(s);
1760
1761
925
    ac3_quantize_mantissas(s);
1762
1763
925
    ret = ff_alloc_packet2(avctx, avpkt, s->frame_size, s->frame_size);
1764
925
    if (ret < 0)
1765
        return ret;
1766
925
    ac3_output_frame(s, avpkt->data);
1767
1768
925
    if (frame->pts != AV_NOPTS_VALUE)
1769
925
        avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding);
1770
1771
925
    *got_packet_ptr = 1;
1772
925
    return 0;
1773
}
1774
1775
6
static void dprint_options(AC3EncodeContext *s)
1776
{
1777
#ifdef DEBUG
1778
    AVCodecContext *avctx = s->avctx;
1779
    AC3EncOptions *opt = &s->options;
1780
    char strbuf[32];
1781
1782
    switch (s->bitstream_id) {
1783
    case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
1784
    case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
1785
    case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
1786
    case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1787
    case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
1788
    default: snprintf(strbuf, 32, "ERROR");
1789
    }
1790
    ff_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1791
    ff_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1792
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1793
    ff_dlog(avctx, "channel_layout: %s\n", strbuf);
1794
    ff_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1795
    ff_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1796
    ff_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1797
    if (s->cutoff)
1798
        ff_dlog(avctx, "cutoff: %d\n", s->cutoff);
1799
1800
    ff_dlog(avctx, "per_frame_metadata: %s\n",
1801
            opt->allow_per_frame_metadata?"on":"off");
1802
    if (s->has_center)
1803
        ff_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1804
                s->center_mix_level);
1805
    else
1806
        ff_dlog(avctx, "center_mixlev: {not written}\n");
1807
    if (s->has_surround)
1808
        ff_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1809
                s->surround_mix_level);
1810
    else
1811
        ff_dlog(avctx, "surround_mixlev: {not written}\n");
1812
    if (opt->audio_production_info) {
1813
        ff_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1814
        switch (opt->room_type) {
1815
        case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1816
        case AC3ENC_OPT_LARGE_ROOM:    av_strlcpy(strbuf, "large", 32);        break;
1817
        case AC3ENC_OPT_SMALL_ROOM:    av_strlcpy(strbuf, "small", 32);        break;
1818
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1819
        }
1820
        ff_dlog(avctx, "room_type: %s\n", strbuf);
1821
    } else {
1822
        ff_dlog(avctx, "mixing_level: {not written}\n");
1823
        ff_dlog(avctx, "room_type: {not written}\n");
1824
    }
1825
    ff_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1826
    ff_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1827
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1828
        switch (opt->dolby_surround_mode) {
1829
        case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1830
        case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1831
        case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1832
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1833
        }
1834
        ff_dlog(avctx, "dsur_mode: %s\n", strbuf);
1835
    } else {
1836
        ff_dlog(avctx, "dsur_mode: {not written}\n");
1837
    }
1838
    ff_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1839
1840
    if (s->bitstream_id == 6) {
1841
        if (opt->extended_bsi_1) {
1842
            switch (opt->preferred_stereo_downmix) {
1843
            case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1844
            case AC3ENC_OPT_DOWNMIX_LTRT:  av_strlcpy(strbuf, "ltrt", 32);         break;
1845
            case AC3ENC_OPT_DOWNMIX_LORO:  av_strlcpy(strbuf, "loro", 32);         break;
1846
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1847
            }
1848
            ff_dlog(avctx, "dmix_mode: %s\n", strbuf);
1849
            ff_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1850
                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1851
            ff_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1852
                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1853
            ff_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1854
                    opt->loro_center_mix_level, s->loro_center_mix_level);
1855
            ff_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1856
                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
1857
        } else {
1858
            ff_dlog(avctx, "extended bitstream info 1: {not written}\n");
1859
        }
1860
        if (opt->extended_bsi_2) {
1861
            switch (opt->dolby_surround_ex_mode) {
1862
            case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1863
            case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1864
            case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1865
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1866
            }
1867
            ff_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1868
            switch (opt->dolby_headphone_mode) {
1869
            case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1870
            case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
1871
            case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
1872
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1873
            }
1874
            ff_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1875
1876
            switch (opt->ad_converter_type) {
1877
            case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
1878
            case AC3ENC_OPT_ADCONV_HDCD:     av_strlcpy(strbuf, "hdcd", 32);     break;
1879
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1880
            }
1881
            ff_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1882
        } else {
1883
            ff_dlog(avctx, "extended bitstream info 2: {not written}\n");
1884
        }
1885
    }
1886
#endif
1887
6
}
1888
1889
1890
#define FLT_OPTION_THRESHOLD 0.01
1891
1892
static int validate_float_option(float v, const float *v_list, int v_list_size)
1893
{
1894
    int i;
1895
1896
    for (i = 0; i < v_list_size; i++) {
1897
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1898
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1899
            break;
1900
    }
1901
    if (i == v_list_size)
1902
        return AVERROR(EINVAL);
1903
1904
    return i;
1905
}
1906
1907
1908
static void validate_mix_level(void *log_ctx, const char *opt_name,
1909
                               float *opt_param, const float *list,
1910
                               int list_size, int default_value, int min_value,
1911
                               int *ctx_param)
1912
{
1913
    int mixlev = validate_float_option(*opt_param, list, list_size);
1914
    if (mixlev < min_value) {
1915
        mixlev = default_value;
1916
        if (*opt_param >= 0.0) {
1917
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1918
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1919
        }
1920
    }
1921
    *opt_param = list[mixlev];
1922
    *ctx_param = mixlev;
1923
}
1924
1925
1926
/**
1927
 * Validate metadata options as set by AVOption system.
1928
 * These values can optionally be changed per-frame.
1929
 *
1930
 * @param s  AC-3 encoder private context
1931
 */
1932
6
int ff_ac3_validate_metadata(AC3EncodeContext *s)
1933
{
1934
6
    AVCodecContext *avctx = s->avctx;
1935
6
    AC3EncOptions *opt = &s->options;
1936
1937
6
    opt->audio_production_info = 0;
1938
6
    opt->extended_bsi_1        = 0;
1939
6
    opt->extended_bsi_2        = 0;
1940
6
    opt->eac3_mixing_metadata  = 0;
1941
6
    opt->eac3_info_metadata    = 0;
1942
1943
    /* determine mixing metadata / xbsi1 use */
1944

6
    if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
1945
        opt->extended_bsi_1       = 1;
1946
        opt->eac3_mixing_metadata = 1;
1947
    }
1948
6
    if (s->has_center &&
1949
        (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1950
        opt->extended_bsi_1       = 1;
1951
        opt->eac3_mixing_metadata = 1;
1952
    }
1953
6
    if (s->has_surround &&
1954
        (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1955
        opt->extended_bsi_1       = 1;
1956
        opt->eac3_mixing_metadata = 1;
1957
    }
1958
1959
6
    if (s->eac3) {
1960
        /* determine info metadata use */
1961
1
        if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1962
            opt->eac3_info_metadata = 1;
1963

1
        if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
1964
            opt->eac3_info_metadata = 1;
1965
1
        if (s->channel_mode == AC3_CHMODE_STEREO &&
1966

1
            (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
1967
            opt->eac3_info_metadata = 1;
1968

1
        if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1969
            opt->eac3_info_metadata = 1;
1970

1
        if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
1971
1
            opt->ad_converter_type != AC3ENC_OPT_NONE) {
1972
            opt->audio_production_info = 1;
1973
            opt->eac3_info_metadata    = 1;
1974
        }
1975
    } else {
1976
        /* determine audio production info use */
1977

5
        if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
1978
            opt->audio_production_info = 1;
1979
1980
        /* determine xbsi2 use */
1981

5
        if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1982
            opt->extended_bsi_2 = 1;
1983

5
        if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
1984
            opt->extended_bsi_2 = 1;
1985
5
        if (opt->ad_converter_type != AC3ENC_OPT_NONE)
1986
            opt->extended_bsi_2 = 1;
1987
    }
1988
1989
    /* validate AC-3 mixing levels */
1990
6
    if (!s->eac3) {
1991
5
        if (s->has_center) {
1992
            validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1993
                               cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1994
                               &s->center_mix_level);
1995
        }
1996
5
        if (s->has_surround) {
1997
            validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1998
                               surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1999
                               &s->surround_mix_level);
2000
        }
2001
    }
2002
2003
    /* validate extended bsi 1 / mixing metadata */
2004

6
    if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
2005
        /* default preferred stereo downmix */
2006
        if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
2007
            opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
2008
        if (!s->eac3 || s->has_center) {
2009
            /* validate Lt/Rt center mix level */
2010
            validate_mix_level(avctx, "ltrt_center_mix_level",
2011
                               &opt->ltrt_center_mix_level, extmixlev_options,
2012
                               EXTMIXLEV_NUM_OPTIONS, 5, 0,
2013
                               &s->ltrt_center_mix_level);
2014
            /* validate Lo/Ro center mix level */
2015
            validate_mix_level(avctx, "loro_center_mix_level",
2016
                               &opt->loro_center_mix_level, extmixlev_options,
2017
                               EXTMIXLEV_NUM_OPTIONS, 5, 0,
2018
                               &s->loro_center_mix_level);
2019
        }
2020
        if (!s->eac3 || s->has_surround) {
2021
            /* validate Lt/Rt surround mix level */
2022
            validate_mix_level(avctx, "ltrt_surround_mix_level",
2023
                               &opt->ltrt_surround_mix_level, extmixlev_options,
2024
                               EXTMIXLEV_NUM_OPTIONS, 6, 3,
2025
                               &s->ltrt_surround_mix_level);
2026
            /* validate Lo/Ro surround mix level */
2027
            validate_mix_level(avctx, "loro_surround_mix_level",
2028
                               &opt->loro_surround_mix_level, extmixlev_options,
2029
                               EXTMIXLEV_NUM_OPTIONS, 6, 3,
2030
                               &s->loro_surround_mix_level);
2031
        }
2032
    }
2033
2034
    /* validate audio service type / channels combination */
2035
6
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2036
         avctx->channels == 1) ||
2037
6
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2038
6
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2039
6
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2040
         && avctx->channels > 1)) {
2041
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2042
                                    "specified number of channels\n");
2043
        return AVERROR(EINVAL);
2044
    }
2045
2046
    /* validate extended bsi 2 / info metadata */
2047

6
    if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
2048
        /* default dolby headphone mode */
2049
        if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
2050
            opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
2051
        /* default dolby surround ex mode */
2052
        if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
2053
            opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
2054
        /* default A/D converter type */
2055
        if (opt->ad_converter_type == AC3ENC_OPT_NONE)
2056
            opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
2057
    }
2058
2059
    /* copyright & original defaults */
2060

6
    if (!s->eac3 || opt->eac3_info_metadata) {
2061
        /* default copyright */
2062
5
        if (opt->copyright == AC3ENC_OPT_NONE)
2063
5
            opt->copyright = AC3ENC_OPT_OFF;
2064
        /* default original */
2065
5
        if (opt->original == AC3ENC_OPT_NONE)
2066
5
            opt->original = AC3ENC_OPT_ON;
2067
    }
2068
2069
    /* dolby surround mode default */
2070

6
    if (!s->eac3 || opt->eac3_info_metadata) {
2071
5
        if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
2072
5
            opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
2073
    }
2074
2075
    /* validate audio production info */
2076
6
    if (opt->audio_production_info) {
2077
        if (opt->mixing_level == AC3ENC_OPT_NONE) {
2078
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2079
                   "room_type is set\n");
2080
            return AVERROR(EINVAL);
2081
        }
2082
        if (opt->mixing_level < 80) {
2083
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2084
                   "80dB and 111dB\n");
2085
            return AVERROR(EINVAL);
2086
        }
2087
        /* default room type */
2088
        if (opt->room_type == AC3ENC_OPT_NONE)
2089
            opt->room_type = AC3ENC_OPT_NOT_INDICATED;
2090
    }
2091
2092
    /* set bitstream id for alternate bitstream syntax */
2093

6
    if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
2094
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2095
            if (!s->warned_alternate_bitstream) {
2096
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2097
                       "not compatible with reduced samplerates. writing of "
2098
                       "extended bitstream information will be disabled.\n");
2099
                s->warned_alternate_bitstream = 1;
2100
            }
2101
        } else {
2102
            s->bitstream_id = 6;
2103
        }
2104
    }
2105
2106
6
    return 0;
2107
}
2108
2109
2110
/**
2111
 * Finalize encoding and free any memory allocated by the encoder.
2112
 *
2113
 * @param avctx  Codec context
2114
 */
2115
6
av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
2116
{
2117
    int blk, ch;
2118
6
    AC3EncodeContext *s = avctx->priv_data;
2119
2120
6
    av_freep(&s->mdct_window);
2121
6
    av_freep(&s->windowed_samples);
2122
6
    if (s->planar_samples)
2123
15
        for (ch = 0; ch < s->channels; ch++)
2124
9
            av_freep(&s->planar_samples[ch]);
2125
6
    av_freep(&s->planar_samples);
2126
6
    av_freep(&s->bap_buffer);
2127
6
    av_freep(&s->bap1_buffer);
2128
6
    av_freep(&s->mdct_coef_buffer);
2129
6
    av_freep(&s->fixed_coef_buffer);
2130
6
    av_freep(&s->exp_buffer);
2131
6
    av_freep(&s->grouped_exp_buffer);
2132
6
    av_freep(&s->psd_buffer);
2133
6
    av_freep(&s->band_psd_buffer);
2134
6
    av_freep(&s->mask_buffer);
2135
6
    av_freep(&s->qmant_buffer);
2136
6
    av_freep(&s->cpl_coord_exp_buffer);
2137
6
    av_freep(&s->cpl_coord_mant_buffer);
2138
6
    av_freep(&s->fdsp);
2139
42
    for (blk = 0; blk < s->num_blocks; blk++) {
2140
36
        AC3Block *block = &s->blocks[blk];
2141
36
        av_freep(&block->mdct_coef);
2142
36
        av_freep(&block->fixed_coef);
2143
36
        av_freep(&block->exp);
2144
36
        av_freep(&block->grouped_exp);
2145
36
        av_freep(&block->psd);
2146
36
        av_freep(&block->band_psd);
2147
36
        av_freep(&block->mask);
2148
36
        av_freep(&block->qmant);
2149
36
        av_freep(&block->cpl_coord_exp);
2150
36
        av_freep(&block->cpl_coord_mant);
2151
    }
2152
2153
6
    s->mdct_end(s);
2154
2155
6
    return 0;
2156
}
2157
2158
2159
/*
2160
 * Set channel information during initialization.
2161
 */
2162
6
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2163
                                    uint64_t *channel_layout)
2164
{
2165
    int ch_layout;
2166
2167

6
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
2168
        return AVERROR(EINVAL);
2169
6
    if (*channel_layout > 0x7FF)
2170
        return AVERROR(EINVAL);
2171
6
    ch_layout = *channel_layout;
2172
6
    if (!ch_layout)
2173
        ch_layout = av_get_default_channel_layout(channels);
2174
2175
6
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2176
6
    s->channels     = channels;
2177
6
    s->fbw_channels = channels - s->lfe_on;
2178
6
    s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
2179
6
    if (s->lfe_on)
2180
        ch_layout -= AV_CH_LOW_FREQUENCY;
2181
2182


6
    switch (ch_layout) {
2183
3
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2184
3
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2185
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2186
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2187
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2188
    case AV_CH_LAYOUT_QUAD:
2189
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2190
    case AV_CH_LAYOUT_5POINT0:
2191
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2192
    default:
2193
        return AVERROR(EINVAL);
2194
    }
2195

6
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2196
6
    s->has_surround =  s->channel_mode & 0x04;
2197
2198
6
    s->channel_map  = ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2199
6
    *channel_layout = ch_layout;
2200
6
    if (s->lfe_on)
2201
        *channel_layout |= AV_CH_LOW_FREQUENCY;
2202
2203
6
    return 0;
2204
}
2205
2206
2207
6
static av_cold int validate_options(AC3EncodeContext *s)
2208
{
2209
6
    AVCodecContext *avctx = s->avctx;
2210
    int i, ret, max_sr;
2211
2212
    /* validate channel layout */
2213
6
    if (!avctx->channel_layout) {
2214
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2215
                                      "encoder will guess the layout, but it "
2216
                                      "might be incorrect.\n");
2217
    }
2218
6
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2219
6
    if (ret) {
2220
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2221
        return ret;
2222
    }
2223
2224
    /* validate sample rate */
2225
    /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2226
             decoder that supports half sample rate so we can validate that
2227
             the generated files are correct. */
2228
6
    max_sr = s->eac3 ? 2 : 8;
2229
12
    for (i = 0; i <= max_sr; i++) {
2230
12
        if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2231
6
            break;
2232
    }
2233
6
    if (i > max_sr) {
2234
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2235
        return AVERROR(EINVAL);
2236
    }
2237
6
    s->sample_rate        = avctx->sample_rate;
2238
6
    s->bit_alloc.sr_shift = i / 3;
2239
6
    s->bit_alloc.sr_code  = i % 3;
2240
6
    s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2241
2242
    /* select a default bit rate if not set by the user */
2243
6
    if (!avctx->bit_rate) {
2244

2
        switch (s->fbw_channels) {
2245
2
        case 1: avctx->bit_rate =  96000; break;
2246
        case 2: avctx->bit_rate = 192000; break;
2247
        case 3: avctx->bit_rate = 320000; break;
2248
        case 4: avctx->bit_rate = 384000; break;
2249
        case 5: avctx->bit_rate = 448000; break;
2250
        }
2251
4
    }
2252
2253
    /* validate bit rate */
2254
6
    if (s->eac3) {
2255
        int max_br, min_br, wpf, min_br_code;
2256
        int num_blks_code, num_blocks, frame_samples;
2257
        long long min_br_dist;
2258
2259
        /* calculate min/max bitrate */
2260
        /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2261
                 found use either 6 blocks or 1 block, even though 2 or 3 blocks
2262
                 would work as far as the bit rate is concerned. */
2263
1
        for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2264
1
            num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2265
1
            frame_samples  = AC3_BLOCK_SIZE * num_blocks;
2266
1
            max_br = 2048 * s->sample_rate / frame_samples * 16;
2267
1
            min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2268
1
            if (avctx->bit_rate <= max_br)
2269
1
                break;
2270
        }
2271

1
        if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2272
            av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2273
                   "for this sample rate\n", min_br, max_br);
2274
            return AVERROR(EINVAL);
2275
        }
2276
1
        s->num_blks_code = num_blks_code;
2277
1
        s->num_blocks    = num_blocks;
2278
2279
        /* calculate words-per-frame for the selected bitrate */
2280
1
        wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2281
        av_assert1(wpf > 0 && wpf <= 2048);
2282
2283
        /* find the closest AC-3 bitrate code to the selected bitrate.
2284
           this is needed for lookup tables for bandwidth and coupling
2285
           parameter selection */
2286
1
        min_br_code = -1;
2287
1
        min_br_dist = INT64_MAX;
2288
20
        for (i = 0; i < 19; i++) {
2289
19
            long long br_dist = llabs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2290
19
            if (br_dist < min_br_dist) {
2291
9
                min_br_dist = br_dist;
2292
9
                min_br_code = i;
2293
            }
2294
        }
2295
2296
        /* make sure the minimum frame size is below the average frame size */
2297
1
        s->frame_size_code = min_br_code << 1;
2298

1
        while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2299
            wpf--;
2300
1
        s->frame_size_min = 2 * wpf;
2301
    } else {
2302
5
        int best_br = 0, best_code = 0;
2303
5
        long long best_diff = INT64_MAX;
2304
37
        for (i = 0; i < 19; i++) {
2305
37
            int br   = (ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift) * 1000;
2306
37
            long long diff = llabs(br - avctx->bit_rate);
2307
37
            if (diff < best_diff) {
2308
37
                best_br   = br;
2309
37
                best_code = i;
2310
37
                best_diff = diff;
2311
            }
2312
37
            if (!best_diff)
2313
5
                break;
2314
        }
2315
5
        avctx->bit_rate    = best_br;
2316
5
        s->frame_size_code = best_code << 1;
2317
5
        s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2318
5
        s->num_blks_code   = 0x3;
2319
5
        s->num_blocks      = 6;
2320
    }
2321
6
    s->bit_rate   = avctx->bit_rate;
2322
6
    s->frame_size = s->frame_size_min;
2323
2324
    /* validate cutoff */
2325
6
    if (avctx->cutoff < 0) {
2326
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2327
        return AVERROR(EINVAL);
2328
    }
2329
6
    s->cutoff = avctx->cutoff;
2330
6
    if (s->cutoff > (s->sample_rate >> 1))
2331
        s->cutoff = s->sample_rate >> 1;
2332
2333
6
    ret = ff_ac3_validate_metadata(s);
2334
6
    if (ret)
2335
        return ret;
2336
2337
12
    s->rematrixing_enabled = s->options.stereo_rematrixing &&
2338
6
                             (s->channel_mode == AC3_CHMODE_STEREO);
2339
2340
12
    s->cpl_enabled = s->options.channel_coupling &&
2341
6
                     s->channel_mode >= AC3_CHMODE_STEREO;
2342
2343
6
    return 0;
2344
}
2345
2346
2347
/*
2348
 * Set bandwidth for all channels.
2349
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2350
 * default value will be used.
2351
 */
2352
6
static av_cold void set_bandwidth(AC3EncodeContext *s)
2353
{
2354
6
    int blk, ch, av_uninit(cpl_start);
2355
2356
6
    if (s->cutoff) {
2357
        /* calculate bandwidth based on user-specified cutoff frequency */
2358
        int fbw_coeffs;
2359
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2360
        s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2361
    } else {
2362
        /* use default bandwidth setting */
2363
6
        s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2364
    }
2365
2366
    /* set number of coefficients for each channel */
2367
15
    for (ch = 1; ch <= s->fbw_channels; ch++) {
2368
9
        s->start_freq[ch] = 0;
2369
63
        for (blk = 0; blk < s->num_blocks; blk++)
2370
54
            s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2371
    }
2372
    /* LFE channel always has 7 coefs */
2373
6
    if (s->lfe_on) {
2374
        s->start_freq[s->lfe_channel] = 0;
2375
        for (blk = 0; blk < s->num_blocks; blk++)
2376
            s->blocks[blk].end_freq[ch] = 7;
2377
    }
2378
2379
    /* initialize coupling strategy */
2380
6
    if (s->cpl_enabled) {
2381
3
        if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
2382
            cpl_start = s->options.cpl_start;
2383
        } else {
2384
3
            cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2385
3
            if (cpl_start < 0) {
2386
                if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
2387
                    s->cpl_enabled = 0;
2388
                else
2389
                    cpl_start = 15;
2390
            }
2391
        }
2392
    }
2393
6
    if (s->cpl_enabled) {
2394
        int i, cpl_start_band, cpl_end_band;
2395
3
        uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2396
2397
3
        cpl_end_band   = s->bandwidth_code / 4 + 3;
2398
3
        cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2399
2400
3
        s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2401
2402
3
        s->num_cpl_bands = 1;
2403
3
        *cpl_band_sizes  = 12;
2404
15
        for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2405
12
            if (ff_eac3_default_cpl_band_struct[i]) {
2406
3
                *cpl_band_sizes += 12;
2407
            } else {
2408
9
                s->num_cpl_bands++;
2409
9
                cpl_band_sizes++;
2410
9
                *cpl_band_sizes = 12;
2411
            }
2412
        }
2413
2414
3
        s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2415
3
        s->cpl_end_freq       = cpl_end_band   * 12 + 37;
2416
21
        for (blk = 0; blk < s->num_blocks; blk++)
2417
18
            s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2418
    }
2419
6
}
2420
2421
2422
6
static av_cold int allocate_buffers(AC3EncodeContext *s)
2423
{
2424
    int blk, ch;
2425
6
    int channels = s->channels + 1; /* includes coupling channel */
2426
6
    int channel_blocks = channels * s->num_blocks;
2427
6
    int total_coefs    = AC3_MAX_COEFS * channel_blocks;
2428
2429
6
    if (s->allocate_sample_buffers(s))
2430
        return AVERROR(ENOMEM);
2431
2432
6
    if (!FF_ALLOC_TYPED_ARRAY(s->bap_buffer,         total_coefs)          ||
2433
6
        !FF_ALLOC_TYPED_ARRAY(s->bap1_buffer,        total_coefs)          ||
2434
6
        !FF_ALLOCZ_TYPED_ARRAY(s->mdct_coef_buffer,  total_coefs)          ||
2435
6
        !FF_ALLOC_TYPED_ARRAY(s->exp_buffer,         total_coefs)          ||
2436
6
        !FF_ALLOC_TYPED_ARRAY(s->grouped_exp_buffer, channel_blocks * 128) ||
2437
6
        !FF_ALLOC_TYPED_ARRAY(s->psd_buffer,         total_coefs)          ||
2438
6
        !FF_ALLOC_TYPED_ARRAY(s->band_psd_buffer,    channel_blocks * 64)  ||
2439
6
        !FF_ALLOC_TYPED_ARRAY(s->mask_buffer,        channel_blocks * 64)  ||
2440
6
        !FF_ALLOC_TYPED_ARRAY(s->qmant_buffer,       total_coefs))
2441
        return AVERROR(ENOMEM);
2442
2443
6
    if (s->cpl_enabled) {
2444
3
        if (!FF_ALLOC_TYPED_ARRAY(s->cpl_coord_exp_buffer,  channel_blocks * 16) ||
2445
3
            !FF_ALLOC_TYPED_ARRAY(s->cpl_coord_mant_buffer, channel_blocks * 16))
2446
            return AVERROR(ENOMEM);
2447
    }
2448
42
    for (blk = 0; blk < s->num_blocks; blk++) {
2449
36
        AC3Block *block = &s->blocks[blk];
2450
2451
36
        if (!FF_ALLOCZ_TYPED_ARRAY(block->mdct_coef,   channels) ||
2452
36
            !FF_ALLOCZ_TYPED_ARRAY(block->exp,         channels) ||
2453
36
            !FF_ALLOCZ_TYPED_ARRAY(block->grouped_exp, channels) ||
2454
36
            !FF_ALLOCZ_TYPED_ARRAY(block->psd,         channels) ||
2455
36
            !FF_ALLOCZ_TYPED_ARRAY(block->band_psd,    channels) ||
2456
36
            !FF_ALLOCZ_TYPED_ARRAY(block->mask,        channels) ||
2457
36
            !FF_ALLOCZ_TYPED_ARRAY(block->qmant,       channels))
2458
            return AVERROR(ENOMEM);
2459
2460
36
        if (s->cpl_enabled) {
2461
18
            if (!FF_ALLOCZ_TYPED_ARRAY(block->cpl_coord_exp,  channels) ||
2462
18
                !FF_ALLOCZ_TYPED_ARRAY(block->cpl_coord_mant, channels))
2463
                return AVERROR(ENOMEM);
2464
        }
2465
2466
126
        for (ch = 0; ch < channels; ch++) {
2467
            /* arrangement: block, channel, coeff */
2468
90
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
2469
90
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2470
90
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
2471
90
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
2472
90
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
2473
90
            if (s->cpl_enabled) {
2474
54
                block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
2475
54
                block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
2476
            }
2477
2478
            /* arrangement: channel, block, coeff */
2479
90
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2480
90
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2481
        }
2482
    }
2483
2484
6
    if (!s->fixed_point) {
2485
2
        if (!FF_ALLOCZ_TYPED_ARRAY(s->fixed_coef_buffer, total_coefs))
2486
            return AVERROR(ENOMEM);
2487
14
        for (blk = 0; blk < s->num_blocks; blk++) {
2488
12
            AC3Block *block = &s->blocks[blk];
2489
12
            if (!FF_ALLOCZ_TYPED_ARRAY(block->fixed_coef, channels))
2490
                return AVERROR(ENOMEM);
2491
48
            for (ch = 0; ch < channels; ch++)
2492
36
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2493
        }
2494
    } else {
2495
28
        for (blk = 0; blk < s->num_blocks; blk++) {
2496
24
            AC3Block *block = &s->blocks[blk];
2497
24
            if (!FF_ALLOCZ_TYPED_ARRAY(block->fixed_coef, channels))
2498
                return AVERROR(ENOMEM);
2499
78
            for (ch = 0; ch < channels; ch++)
2500
54
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2501
        }
2502
    }
2503
2504
6
    return 0;
2505
}
2506
2507
2508
6
av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2509
{
2510
    static AVOnce init_static_once = AV_ONCE_INIT;
2511
6
    AC3EncodeContext *s = avctx->priv_data;
2512
    int ret, frame_size_58;
2513
2514
6
    s->avctx = avctx;
2515
2516
6
    s->eac3 = avctx->codec_id == AV_CODEC_ID_EAC3;
2517
2518
6
    ret = validate_options(s);
2519
6
    if (ret)
2520
        return ret;
2521
2522
6
    avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2523
6
    avctx->initial_padding = AC3_BLOCK_SIZE;
2524
2525
6
    s->bitstream_mode = avctx->audio_service_type;
2526
6
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2527
        s->bitstream_mode = 0x7;
2528
2529
6
    s->bits_written    = 0;
2530
6
    s->samples_written = 0;
2531
2532
    /* calculate crc_inv for both possible frame sizes */
2533
6
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2534
6
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2535
6
    if (s->bit_alloc.sr_code == 1) {
2536
6
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2537
6
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2538
    }
2539
2540
6
    if (CONFIG_EAC3_ENCODER && s->eac3) {
2541
        static AVOnce init_static_once_eac3 = AV_ONCE_INIT;
2542
1
        ff_thread_once(&init_static_once_eac3, ff_eac3_exponent_init);
2543
1
        s->output_frame_header = ff_eac3_output_frame_header;
2544
    } else
2545
5
        s->output_frame_header = ac3_output_frame_header;
2546
2547
6
    set_bandwidth(s);
2548
2549
6
    bit_alloc_init(s);
2550
2551
6
    ret = s->mdct_init(s);
2552
6
    if (ret)
2553
        return ret;
2554
2555
6
    ret = allocate_buffers(s);
2556
6
    if (ret)
2557
        return ret;
2558
2559
6
    ff_audiodsp_init(&s->adsp);
2560
6
    ff_me_cmp_init(&s->mecc, avctx);
2561
6
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
2562
2563
6
    dprint_options(s);
2564
2565
6
    ff_thread_once(&init_static_once, exponent_init);
2566
2567
6
    return 0;
2568
}