You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2282 lines
77KB

  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 Libav.
  8. *
  9. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * The simplest AC-3 encoder.
  26. */
  27. //#define DEBUG
  28. //#define ASSERT_LEVEL 2
  29. #include "libavutil/audioconvert.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/crc.h"
  32. #include "libavutil/opt.h"
  33. #include "avcodec.h"
  34. #include "put_bits.h"
  35. #include "dsputil.h"
  36. #include "ac3dsp.h"
  37. #include "ac3.h"
  38. #include "audioconvert.h"
  39. #ifndef CONFIG_AC3ENC_FLOAT
  40. #define CONFIG_AC3ENC_FLOAT 0
  41. #endif
  42. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  43. #define AC3_MAX_EXP_GROUPS 85
  44. /* stereo rematrixing algorithms */
  45. #define AC3_REMATRIXING_IS_STATIC 0x1
  46. #define AC3_REMATRIXING_SUMS 0
  47. #define AC3_REMATRIXING_NONE 1
  48. #define AC3_REMATRIXING_ALWAYS 3
  49. /** Scale a float value by 2^bits and convert to an integer. */
  50. #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
  51. #if CONFIG_AC3ENC_FLOAT
  52. #include "ac3enc_float.h"
  53. #else
  54. #include "ac3enc_fixed.h"
  55. #endif
  56. /**
  57. * Encoding Options used by AVOption.
  58. */
  59. typedef struct AC3EncOptions {
  60. /* AC-3 metadata options*/
  61. int dialogue_level;
  62. int bitstream_mode;
  63. float center_mix_level;
  64. float surround_mix_level;
  65. int dolby_surround_mode;
  66. int audio_production_info;
  67. int mixing_level;
  68. int room_type;
  69. int copyright;
  70. int original;
  71. int extended_bsi_1;
  72. int preferred_stereo_downmix;
  73. float ltrt_center_mix_level;
  74. float ltrt_surround_mix_level;
  75. float loro_center_mix_level;
  76. float loro_surround_mix_level;
  77. int extended_bsi_2;
  78. int dolby_surround_ex_mode;
  79. int dolby_headphone_mode;
  80. int ad_converter_type;
  81. /* other encoding options */
  82. int allow_per_frame_metadata;
  83. } AC3EncOptions;
  84. /**
  85. * Data for a single audio block.
  86. */
  87. typedef struct AC3Block {
  88. uint8_t **bap; ///< bit allocation pointers (bap)
  89. CoefType **mdct_coef; ///< MDCT coefficients
  90. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  91. uint8_t **exp; ///< original exponents
  92. uint8_t **grouped_exp; ///< grouped exponents
  93. int16_t **psd; ///< psd per frequency bin
  94. int16_t **band_psd; ///< psd per critical band
  95. int16_t **mask; ///< masking curve
  96. uint16_t **qmant; ///< quantized mantissas
  97. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  98. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  99. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  100. } AC3Block;
  101. /**
  102. * AC-3 encoder private context.
  103. */
  104. typedef struct AC3EncodeContext {
  105. AVClass *av_class; ///< AVClass used for AVOption
  106. AC3EncOptions options; ///< encoding options
  107. PutBitContext pb; ///< bitstream writer context
  108. DSPContext dsp;
  109. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  110. AC3MDCTContext mdct; ///< MDCT context
  111. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  112. int bitstream_id; ///< bitstream id (bsid)
  113. int bitstream_mode; ///< bitstream mode (bsmod)
  114. int bit_rate; ///< target bit rate, in bits-per-second
  115. int sample_rate; ///< sampling frequency, in Hz
  116. int frame_size_min; ///< minimum frame size in case rounding is necessary
  117. int frame_size; ///< current frame size in bytes
  118. int frame_size_code; ///< frame size code (frmsizecod)
  119. uint16_t crc_inv[2];
  120. int bits_written; ///< bit count (used to avg. bitrate)
  121. int samples_written; ///< sample count (used to avg. bitrate)
  122. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  123. int channels; ///< total number of channels (nchans)
  124. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  125. int lfe_channel; ///< channel index of the LFE channel
  126. int has_center; ///< indicates if there is a center channel
  127. int has_surround; ///< indicates if there are one or more surround channels
  128. int channel_mode; ///< channel mode (acmod)
  129. const uint8_t *channel_map; ///< channel map used to reorder channels
  130. int center_mix_level; ///< center mix level code
  131. int surround_mix_level; ///< surround mix level code
  132. int ltrt_center_mix_level; ///< Lt/Rt center mix level code
  133. int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
  134. int loro_center_mix_level; ///< Lo/Ro center mix level code
  135. int loro_surround_mix_level; ///< Lo/Ro surround mix level code
  136. int cutoff; ///< user-specified cutoff frequency, in Hz
  137. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  138. int nb_coefs[AC3_MAX_CHANNELS];
  139. int rematrixing; ///< determines how rematrixing strategy is calculated
  140. int num_rematrixing_bands; ///< number of rematrixing bands
  141. /* bitrate allocation control */
  142. int slow_gain_code; ///< slow gain code (sgaincod)
  143. int slow_decay_code; ///< slow decay code (sdcycod)
  144. int fast_decay_code; ///< fast decay code (fdcycod)
  145. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  146. int floor_code; ///< floor code (floorcod)
  147. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  148. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  149. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  150. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  151. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  152. int frame_bits; ///< all frame bits except exponents and mantissas
  153. int exponent_bits; ///< number of bits used for exponents
  154. /* mantissa encoding */
  155. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  156. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  157. SampleType **planar_samples;
  158. uint8_t *bap_buffer;
  159. uint8_t *bap1_buffer;
  160. CoefType *mdct_coef_buffer;
  161. int32_t *fixed_coef_buffer;
  162. uint8_t *exp_buffer;
  163. uint8_t *grouped_exp_buffer;
  164. int16_t *psd_buffer;
  165. int16_t *band_psd_buffer;
  166. int16_t *mask_buffer;
  167. uint16_t *qmant_buffer;
  168. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  169. DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  170. } AC3EncodeContext;
  171. #define CMIXLEV_NUM_OPTIONS 3
  172. static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
  173. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
  174. };
  175. #define SURMIXLEV_NUM_OPTIONS 3
  176. static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
  177. LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  178. };
  179. #define EXTMIXLEV_NUM_OPTIONS 8
  180. static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
  181. LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
  182. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  183. };
  184. #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
  185. #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  186. static const AVOption options[] = {
  187. /* Metadata Options */
  188. {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  189. /* downmix levels */
  190. {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
  191. {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
  192. /* audio production information */
  193. {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
  194. {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
  195. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  196. {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  197. {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  198. /* other metadata options */
  199. {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  200. {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
  201. {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
  202. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  203. {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  204. {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  205. {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
  206. /* extended bitstream information */
  207. {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
  208. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  209. {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  210. {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  211. {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  212. {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  213. {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  214. {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  215. {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
  216. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  217. {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  218. {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  219. {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
  220. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  221. {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  222. {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  223. {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
  224. {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  225. {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  226. {NULL}
  227. };
  228. #if CONFIG_AC3ENC_FLOAT
  229. static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
  230. options, LIBAVUTIL_VERSION_INT };
  231. #else
  232. static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
  233. options, LIBAVUTIL_VERSION_INT };
  234. #endif
  235. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  236. static av_cold void mdct_end(AC3MDCTContext *mdct);
  237. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  238. int nbits);
  239. static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);
  240. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  241. const SampleType *window, unsigned int len);
  242. static int normalize_samples(AC3EncodeContext *s);
  243. static void scale_coefficients(AC3EncodeContext *s);
  244. /**
  245. * LUT for number of exponent groups.
  246. * exponent_group_tab[exponent strategy-1][number of coefficients]
  247. */
  248. static uint8_t exponent_group_tab[3][256];
  249. /**
  250. * List of supported channel layouts.
  251. */
  252. static const int64_t ac3_channel_layouts[] = {
  253. AV_CH_LAYOUT_MONO,
  254. AV_CH_LAYOUT_STEREO,
  255. AV_CH_LAYOUT_2_1,
  256. AV_CH_LAYOUT_SURROUND,
  257. AV_CH_LAYOUT_2_2,
  258. AV_CH_LAYOUT_QUAD,
  259. AV_CH_LAYOUT_4POINT0,
  260. AV_CH_LAYOUT_5POINT0,
  261. AV_CH_LAYOUT_5POINT0_BACK,
  262. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  263. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  264. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  265. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  266. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  267. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  268. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  269. AV_CH_LAYOUT_5POINT1,
  270. AV_CH_LAYOUT_5POINT1_BACK,
  271. 0
  272. };
  273. /**
  274. * Adjust the frame size to make the average bit rate match the target bit rate.
  275. * This is only needed for 11025, 22050, and 44100 sample rates.
  276. */
  277. static void adjust_frame_size(AC3EncodeContext *s)
  278. {
  279. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  280. s->bits_written -= s->bit_rate;
  281. s->samples_written -= s->sample_rate;
  282. }
  283. s->frame_size = s->frame_size_min +
  284. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  285. s->bits_written += s->frame_size * 8;
  286. s->samples_written += AC3_FRAME_SIZE;
  287. }
  288. /**
  289. * Deinterleave input samples.
  290. * Channels are reordered from Libav's default order to AC-3 order.
  291. */
  292. static void deinterleave_input_samples(AC3EncodeContext *s,
  293. const SampleType *samples)
  294. {
  295. int ch, i;
  296. /* deinterleave and remap input samples */
  297. for (ch = 0; ch < s->channels; ch++) {
  298. const SampleType *sptr;
  299. int sinc;
  300. /* copy last 256 samples of previous frame to the start of the current frame */
  301. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  302. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  303. /* deinterleave */
  304. sinc = s->channels;
  305. sptr = samples + s->channel_map[ch];
  306. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  307. s->planar_samples[ch][i] = *sptr;
  308. sptr += sinc;
  309. }
  310. }
  311. }
  312. /**
  313. * Apply the MDCT to input samples to generate frequency coefficients.
  314. * This applies the KBD window and normalizes the input to reduce precision
  315. * loss due to fixed-point calculations.
  316. */
  317. static void apply_mdct(AC3EncodeContext *s)
  318. {
  319. int blk, ch;
  320. for (ch = 0; ch < s->channels; ch++) {
  321. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  322. AC3Block *block = &s->blocks[blk];
  323. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  324. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  325. block->coeff_shift[ch] = normalize_samples(s);
  326. mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
  327. }
  328. }
  329. }
  330. /**
  331. * Initialize stereo rematrixing.
  332. * If the strategy does not change for each frame, set the rematrixing flags.
  333. */
  334. static void rematrixing_init(AC3EncodeContext *s)
  335. {
  336. if (s->channel_mode == AC3_CHMODE_STEREO)
  337. s->rematrixing = AC3_REMATRIXING_SUMS;
  338. else
  339. s->rematrixing = AC3_REMATRIXING_NONE;
  340. /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
  341. the future in conjunction with channel coupling. */
  342. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
  343. int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
  344. s->blocks[0].new_rematrixing_strategy = 1;
  345. memset(s->blocks[0].rematrixing_flags, flag,
  346. sizeof(s->blocks[0].rematrixing_flags));
  347. }
  348. }
  349. /**
  350. * Determine rematrixing flags for each block and band.
  351. */
  352. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  353. {
  354. int nb_coefs;
  355. int blk, bnd, i;
  356. AC3Block *block, *block0;
  357. s->num_rematrixing_bands = 4;
  358. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
  359. return;
  360. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  361. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  362. block = &s->blocks[blk];
  363. block->new_rematrixing_strategy = !blk;
  364. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  365. /* calculate calculate sum of squared coeffs for one band in one block */
  366. int start = ff_ac3_rematrix_band_tab[bnd];
  367. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  368. CoefSumType sum[4] = {0,};
  369. for (i = start; i < end; i++) {
  370. CoefType lt = block->mdct_coef[0][i];
  371. CoefType rt = block->mdct_coef[1][i];
  372. CoefType md = lt + rt;
  373. CoefType sd = lt - rt;
  374. MAC_COEF(sum[0], lt, lt);
  375. MAC_COEF(sum[1], rt, rt);
  376. MAC_COEF(sum[2], md, md);
  377. MAC_COEF(sum[3], sd, sd);
  378. }
  379. /* compare sums to determine if rematrixing will be used for this band */
  380. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  381. block->rematrixing_flags[bnd] = 1;
  382. else
  383. block->rematrixing_flags[bnd] = 0;
  384. /* determine if new rematrixing flags will be sent */
  385. if (blk &&
  386. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  387. block->new_rematrixing_strategy = 1;
  388. }
  389. }
  390. block0 = block;
  391. }
  392. }
  393. /**
  394. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  395. */
  396. static void apply_rematrixing(AC3EncodeContext *s)
  397. {
  398. int nb_coefs;
  399. int blk, bnd, i;
  400. int start, end;
  401. uint8_t *flags;
  402. if (s->rematrixing == AC3_REMATRIXING_NONE)
  403. return;
  404. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  405. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  406. AC3Block *block = &s->blocks[blk];
  407. if (block->new_rematrixing_strategy)
  408. flags = block->rematrixing_flags;
  409. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  410. if (flags[bnd]) {
  411. start = ff_ac3_rematrix_band_tab[bnd];
  412. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  413. for (i = start; i < end; i++) {
  414. int32_t lt = block->fixed_coef[0][i];
  415. int32_t rt = block->fixed_coef[1][i];
  416. block->fixed_coef[0][i] = (lt + rt) >> 1;
  417. block->fixed_coef[1][i] = (lt - rt) >> 1;
  418. }
  419. }
  420. }
  421. }
  422. }
  423. /**
  424. * Initialize exponent tables.
  425. */
  426. static av_cold void exponent_init(AC3EncodeContext *s)
  427. {
  428. int i;
  429. for (i = 73; i < 256; i++) {
  430. exponent_group_tab[0][i] = (i - 1) / 3;
  431. exponent_group_tab[1][i] = (i + 2) / 6;
  432. exponent_group_tab[2][i] = (i + 8) / 12;
  433. }
  434. /* LFE */
  435. exponent_group_tab[0][7] = 2;
  436. }
  437. /**
  438. * Extract exponents from the MDCT coefficients.
  439. * This takes into account the normalization that was done to the input samples
  440. * by adjusting the exponents by the exponent shift values.
  441. */
  442. static void extract_exponents(AC3EncodeContext *s)
  443. {
  444. int blk, ch, i;
  445. for (ch = 0; ch < s->channels; ch++) {
  446. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  447. AC3Block *block = &s->blocks[blk];
  448. uint8_t *exp = block->exp[ch];
  449. int32_t *coef = block->fixed_coef[ch];
  450. for (i = 0; i < AC3_MAX_COEFS; i++) {
  451. int e;
  452. int v = abs(coef[i]);
  453. if (v == 0)
  454. e = 24;
  455. else {
  456. e = 23 - av_log2(v);
  457. if (e >= 24) {
  458. e = 24;
  459. coef[i] = 0;
  460. }
  461. av_assert2(e >= 0);
  462. }
  463. exp[i] = e;
  464. }
  465. }
  466. }
  467. }
  468. /**
  469. * Exponent Difference Threshold.
  470. * New exponents are sent if their SAD exceed this number.
  471. */
  472. #define EXP_DIFF_THRESHOLD 500
  473. /**
  474. * Calculate exponent strategies for all blocks in a single channel.
  475. */
  476. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  477. uint8_t *exp)
  478. {
  479. int blk, blk1;
  480. int exp_diff;
  481. /* estimate if the exponent variation & decide if they should be
  482. reused in the next frame */
  483. exp_strategy[0] = EXP_NEW;
  484. exp += AC3_MAX_COEFS;
  485. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  486. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  487. if (exp_diff > EXP_DIFF_THRESHOLD)
  488. exp_strategy[blk] = EXP_NEW;
  489. else
  490. exp_strategy[blk] = EXP_REUSE;
  491. exp += AC3_MAX_COEFS;
  492. }
  493. /* now select the encoding strategy type : if exponents are often
  494. recoded, we use a coarse encoding */
  495. blk = 0;
  496. while (blk < AC3_MAX_BLOCKS) {
  497. blk1 = blk + 1;
  498. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  499. blk1++;
  500. switch (blk1 - blk) {
  501. case 1: exp_strategy[blk] = EXP_D45; break;
  502. case 2:
  503. case 3: exp_strategy[blk] = EXP_D25; break;
  504. default: exp_strategy[blk] = EXP_D15; break;
  505. }
  506. blk = blk1;
  507. }
  508. }
  509. /**
  510. * Calculate exponent strategies for all channels.
  511. * Array arrangement is reversed to simplify the per-channel calculation.
  512. */
  513. static void compute_exp_strategy(AC3EncodeContext *s)
  514. {
  515. int ch, blk;
  516. for (ch = 0; ch < s->fbw_channels; ch++) {
  517. compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
  518. }
  519. if (s->lfe_on) {
  520. ch = s->lfe_channel;
  521. s->exp_strategy[ch][0] = EXP_D15;
  522. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  523. s->exp_strategy[ch][blk] = EXP_REUSE;
  524. }
  525. }
  526. /**
  527. * Update the exponents so that they are the ones the decoder will decode.
  528. */
  529. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  530. {
  531. int nb_groups, i, k;
  532. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  533. /* for each group, compute the minimum exponent */
  534. switch(exp_strategy) {
  535. case EXP_D25:
  536. for (i = 1, k = 1; i <= nb_groups; i++) {
  537. uint8_t exp_min = exp[k];
  538. if (exp[k+1] < exp_min)
  539. exp_min = exp[k+1];
  540. exp[i] = exp_min;
  541. k += 2;
  542. }
  543. break;
  544. case EXP_D45:
  545. for (i = 1, k = 1; i <= nb_groups; i++) {
  546. uint8_t exp_min = exp[k];
  547. if (exp[k+1] < exp_min)
  548. exp_min = exp[k+1];
  549. if (exp[k+2] < exp_min)
  550. exp_min = exp[k+2];
  551. if (exp[k+3] < exp_min)
  552. exp_min = exp[k+3];
  553. exp[i] = exp_min;
  554. k += 4;
  555. }
  556. break;
  557. }
  558. /* constraint for DC exponent */
  559. if (exp[0] > 15)
  560. exp[0] = 15;
  561. /* decrease the delta between each groups to within 2 so that they can be
  562. differentially encoded */
  563. for (i = 1; i <= nb_groups; i++)
  564. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  565. i--;
  566. while (--i >= 0)
  567. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  568. /* now we have the exponent values the decoder will see */
  569. switch (exp_strategy) {
  570. case EXP_D25:
  571. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  572. uint8_t exp1 = exp[i];
  573. exp[k--] = exp1;
  574. exp[k--] = exp1;
  575. }
  576. break;
  577. case EXP_D45:
  578. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  579. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  580. k -= 4;
  581. }
  582. break;
  583. }
  584. }
  585. /**
  586. * Encode exponents from original extracted form to what the decoder will see.
  587. * This copies and groups exponents based on exponent strategy and reduces
  588. * deltas between adjacent exponent groups so that they can be differentially
  589. * encoded.
  590. */
  591. static void encode_exponents(AC3EncodeContext *s)
  592. {
  593. int blk, blk1, ch;
  594. uint8_t *exp, *exp1, *exp_strategy;
  595. int nb_coefs, num_reuse_blocks;
  596. for (ch = 0; ch < s->channels; ch++) {
  597. exp = s->blocks[0].exp[ch];
  598. exp_strategy = s->exp_strategy[ch];
  599. nb_coefs = s->nb_coefs[ch];
  600. blk = 0;
  601. while (blk < AC3_MAX_BLOCKS) {
  602. blk1 = blk + 1;
  603. /* count the number of EXP_REUSE blocks after the current block */
  604. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  605. blk1++;
  606. num_reuse_blocks = blk1 - blk - 1;
  607. /* for the EXP_REUSE case we select the min of the exponents */
  608. s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
  609. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
  610. /* copy encoded exponents for reuse case */
  611. exp1 = exp + AC3_MAX_COEFS;
  612. while (blk < blk1-1) {
  613. memcpy(exp1, exp, nb_coefs * sizeof(*exp));
  614. exp1 += AC3_MAX_COEFS;
  615. blk++;
  616. }
  617. blk = blk1;
  618. exp = exp1;
  619. }
  620. }
  621. }
  622. /**
  623. * Group exponents.
  624. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  625. * varies depending on exponent strategy and bandwidth.
  626. */
  627. static void group_exponents(AC3EncodeContext *s)
  628. {
  629. int blk, ch, i;
  630. int group_size, nb_groups, bit_count;
  631. uint8_t *p;
  632. int delta0, delta1, delta2;
  633. int exp0, exp1;
  634. bit_count = 0;
  635. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  636. AC3Block *block = &s->blocks[blk];
  637. for (ch = 0; ch < s->channels; ch++) {
  638. int exp_strategy = s->exp_strategy[ch][blk];
  639. if (exp_strategy == EXP_REUSE)
  640. continue;
  641. group_size = exp_strategy + (exp_strategy == EXP_D45);
  642. nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
  643. bit_count += 4 + (nb_groups * 7);
  644. p = block->exp[ch];
  645. /* DC exponent */
  646. exp1 = *p++;
  647. block->grouped_exp[ch][0] = exp1;
  648. /* remaining exponents are delta encoded */
  649. for (i = 1; i <= nb_groups; i++) {
  650. /* merge three delta in one code */
  651. exp0 = exp1;
  652. exp1 = p[0];
  653. p += group_size;
  654. delta0 = exp1 - exp0 + 2;
  655. av_assert2(delta0 >= 0 && delta0 <= 4);
  656. exp0 = exp1;
  657. exp1 = p[0];
  658. p += group_size;
  659. delta1 = exp1 - exp0 + 2;
  660. av_assert2(delta1 >= 0 && delta1 <= 4);
  661. exp0 = exp1;
  662. exp1 = p[0];
  663. p += group_size;
  664. delta2 = exp1 - exp0 + 2;
  665. av_assert2(delta2 >= 0 && delta2 <= 4);
  666. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  667. }
  668. }
  669. }
  670. s->exponent_bits = bit_count;
  671. }
  672. /**
  673. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  674. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  675. * and encode final exponents.
  676. */
  677. static void process_exponents(AC3EncodeContext *s)
  678. {
  679. extract_exponents(s);
  680. compute_exp_strategy(s);
  681. encode_exponents(s);
  682. group_exponents(s);
  683. emms_c();
  684. }
  685. /**
  686. * Count frame bits that are based solely on fixed parameters.
  687. * This only has to be run once when the encoder is initialized.
  688. */
  689. static void count_frame_bits_fixed(AC3EncodeContext *s)
  690. {
  691. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  692. int blk;
  693. int frame_bits;
  694. /* assumptions:
  695. * no dynamic range codes
  696. * no channel coupling
  697. * bit allocation parameters do not change between blocks
  698. * SNR offsets do not change between blocks
  699. * no delta bit allocation
  700. * no skipped data
  701. * no auxilliary data
  702. */
  703. /* header size */
  704. frame_bits = 65;
  705. frame_bits += frame_bits_inc[s->channel_mode];
  706. /* audio blocks */
  707. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  708. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  709. if (s->channel_mode == AC3_CHMODE_STEREO) {
  710. frame_bits++; /* rematstr */
  711. }
  712. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  713. if (s->lfe_on)
  714. frame_bits++; /* lfeexpstr */
  715. frame_bits++; /* baie */
  716. frame_bits++; /* snr */
  717. frame_bits += 2; /* delta / skip */
  718. }
  719. frame_bits++; /* cplinu for block 0 */
  720. /* bit alloc info */
  721. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  722. /* csnroffset[6] */
  723. /* (fsnoffset[4] + fgaincod[4]) * c */
  724. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  725. /* auxdatae, crcrsv */
  726. frame_bits += 2;
  727. /* CRC */
  728. frame_bits += 16;
  729. s->frame_bits_fixed = frame_bits;
  730. }
  731. /**
  732. * Initialize bit allocation.
  733. * Set default parameter codes and calculate parameter values.
  734. */
  735. static void bit_alloc_init(AC3EncodeContext *s)
  736. {
  737. int ch;
  738. /* init default parameters */
  739. s->slow_decay_code = 2;
  740. s->fast_decay_code = 1;
  741. s->slow_gain_code = 1;
  742. s->db_per_bit_code = 3;
  743. s->floor_code = 7;
  744. for (ch = 0; ch < s->channels; ch++)
  745. s->fast_gain_code[ch] = 4;
  746. /* initial snr offset */
  747. s->coarse_snr_offset = 40;
  748. /* compute real values */
  749. /* currently none of these values change during encoding, so we can just
  750. set them once at initialization */
  751. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  752. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  753. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  754. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  755. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  756. count_frame_bits_fixed(s);
  757. }
  758. /**
  759. * Count the bits used to encode the frame, minus exponents and mantissas.
  760. * Bits based on fixed parameters have already been counted, so now we just
  761. * have to add the bits based on parameters that change during encoding.
  762. */
  763. static void count_frame_bits(AC3EncodeContext *s)
  764. {
  765. AC3EncOptions *opt = &s->options;
  766. int blk, ch;
  767. int frame_bits = 0;
  768. if (opt->audio_production_info)
  769. frame_bits += 7;
  770. if (s->bitstream_id == 6) {
  771. if (opt->extended_bsi_1)
  772. frame_bits += 14;
  773. if (opt->extended_bsi_2)
  774. frame_bits += 14;
  775. }
  776. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  777. /* stereo rematrixing */
  778. if (s->channel_mode == AC3_CHMODE_STEREO &&
  779. s->blocks[blk].new_rematrixing_strategy) {
  780. frame_bits += s->num_rematrixing_bands;
  781. }
  782. for (ch = 0; ch < s->fbw_channels; ch++) {
  783. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  784. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  785. }
  786. }
  787. s->frame_bits = s->frame_bits_fixed + frame_bits;
  788. }
  789. /**
  790. * Calculate the number of bits needed to encode a set of mantissas.
  791. */
  792. static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
  793. {
  794. int bits, b, i;
  795. bits = 0;
  796. for (i = 0; i < nb_coefs; i++) {
  797. b = bap[i];
  798. if (b <= 4) {
  799. // bap=1 to bap=4 will be counted in compute_mantissa_size_final
  800. mant_cnt[b]++;
  801. } else if (b <= 13) {
  802. // bap=5 to bap=13 use (bap-1) bits
  803. bits += b - 1;
  804. } else {
  805. // bap=14 uses 14 bits and bap=15 uses 16 bits
  806. bits += (b == 14) ? 14 : 16;
  807. }
  808. }
  809. return bits;
  810. }
  811. /**
  812. * Finalize the mantissa bit count by adding in the grouped mantissas.
  813. */
  814. static int compute_mantissa_size_final(int mant_cnt[5])
  815. {
  816. // bap=1 : 3 mantissas in 5 bits
  817. int bits = (mant_cnt[1] / 3) * 5;
  818. // bap=2 : 3 mantissas in 7 bits
  819. // bap=4 : 2 mantissas in 7 bits
  820. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  821. // bap=3 : each mantissa is 3 bits
  822. bits += mant_cnt[3] * 3;
  823. return bits;
  824. }
  825. /**
  826. * Calculate masking curve based on the final exponents.
  827. * Also calculate the power spectral densities to use in future calculations.
  828. */
  829. static void bit_alloc_masking(AC3EncodeContext *s)
  830. {
  831. int blk, ch;
  832. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  833. AC3Block *block = &s->blocks[blk];
  834. for (ch = 0; ch < s->channels; ch++) {
  835. /* We only need psd and mask for calculating bap.
  836. Since we currently do not calculate bap when exponent
  837. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  838. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  839. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  840. s->nb_coefs[ch],
  841. block->psd[ch], block->band_psd[ch]);
  842. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  843. 0, s->nb_coefs[ch],
  844. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  845. ch == s->lfe_channel,
  846. DBA_NONE, 0, NULL, NULL, NULL,
  847. block->mask[ch]);
  848. }
  849. }
  850. }
  851. }
  852. /**
  853. * Ensure that bap for each block and channel point to the current bap_buffer.
  854. * They may have been switched during the bit allocation search.
  855. */
  856. static void reset_block_bap(AC3EncodeContext *s)
  857. {
  858. int blk, ch;
  859. if (s->blocks[0].bap[0] == s->bap_buffer)
  860. return;
  861. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  862. for (ch = 0; ch < s->channels; ch++) {
  863. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  864. }
  865. }
  866. }
  867. /**
  868. * Run the bit allocation with a given SNR offset.
  869. * This calculates the bit allocation pointers that will be used to determine
  870. * the quantization of each mantissa.
  871. * @return the number of bits needed for mantissas if the given SNR offset is
  872. * is used.
  873. */
  874. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  875. {
  876. int blk, ch;
  877. int mantissa_bits;
  878. int mant_cnt[5];
  879. snr_offset = (snr_offset - 240) << 2;
  880. reset_block_bap(s);
  881. mantissa_bits = 0;
  882. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  883. AC3Block *block = &s->blocks[blk];
  884. // initialize grouped mantissa counts. these are set so that they are
  885. // padded to the next whole group size when bits are counted in
  886. // compute_mantissa_size_final
  887. mant_cnt[0] = mant_cnt[3] = 0;
  888. mant_cnt[1] = mant_cnt[2] = 2;
  889. mant_cnt[4] = 1;
  890. for (ch = 0; ch < s->channels; ch++) {
  891. /* Currently the only bit allocation parameters which vary across
  892. blocks within a frame are the exponent values. We can take
  893. advantage of that by reusing the bit allocation pointers
  894. whenever we reuse exponents. */
  895. if (s->exp_strategy[ch][blk] == EXP_REUSE) {
  896. memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
  897. } else {
  898. ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  899. s->nb_coefs[ch], snr_offset,
  900. s->bit_alloc.floor, ff_ac3_bap_tab,
  901. block->bap[ch]);
  902. }
  903. mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  904. }
  905. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  906. }
  907. return mantissa_bits;
  908. }
  909. /**
  910. * Constant bitrate bit allocation search.
  911. * Find the largest SNR offset that will allow data to fit in the frame.
  912. */
  913. static int cbr_bit_allocation(AC3EncodeContext *s)
  914. {
  915. int ch;
  916. int bits_left;
  917. int snr_offset, snr_incr;
  918. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  919. av_assert2(bits_left >= 0);
  920. snr_offset = s->coarse_snr_offset << 4;
  921. /* if previous frame SNR offset was 1023, check if current frame can also
  922. use SNR offset of 1023. if so, skip the search. */
  923. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  924. if (bit_alloc(s, 1023) <= bits_left)
  925. return 0;
  926. }
  927. while (snr_offset >= 0 &&
  928. bit_alloc(s, snr_offset) > bits_left) {
  929. snr_offset -= 64;
  930. }
  931. if (snr_offset < 0)
  932. return AVERROR(EINVAL);
  933. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  934. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  935. while (snr_offset + snr_incr <= 1023 &&
  936. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  937. snr_offset += snr_incr;
  938. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  939. }
  940. }
  941. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  942. reset_block_bap(s);
  943. s->coarse_snr_offset = snr_offset >> 4;
  944. for (ch = 0; ch < s->channels; ch++)
  945. s->fine_snr_offset[ch] = snr_offset & 0xF;
  946. return 0;
  947. }
  948. /**
  949. * Downgrade exponent strategies to reduce the bits used by the exponents.
  950. * This is a fallback for when bit allocation fails with the normal exponent
  951. * strategies. Each time this function is run it only downgrades the
  952. * strategy in 1 channel of 1 block.
  953. * @return non-zero if downgrade was unsuccessful
  954. */
  955. static int downgrade_exponents(AC3EncodeContext *s)
  956. {
  957. int ch, blk;
  958. for (ch = 0; ch < s->fbw_channels; ch++) {
  959. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  960. if (s->exp_strategy[ch][blk] == EXP_D15) {
  961. s->exp_strategy[ch][blk] = EXP_D25;
  962. return 0;
  963. }
  964. }
  965. }
  966. for (ch = 0; ch < s->fbw_channels; ch++) {
  967. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  968. if (s->exp_strategy[ch][blk] == EXP_D25) {
  969. s->exp_strategy[ch][blk] = EXP_D45;
  970. return 0;
  971. }
  972. }
  973. }
  974. for (ch = 0; ch < s->fbw_channels; ch++) {
  975. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  976. the block number > 0 */
  977. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  978. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  979. s->exp_strategy[ch][blk] = EXP_REUSE;
  980. return 0;
  981. }
  982. }
  983. }
  984. return -1;
  985. }
  986. /**
  987. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  988. * This is a second fallback for when bit allocation still fails after exponents
  989. * have been downgraded.
  990. * @return non-zero if bandwidth reduction was unsuccessful
  991. */
  992. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  993. {
  994. int ch;
  995. if (s->bandwidth_code[0] > min_bw_code) {
  996. for (ch = 0; ch < s->fbw_channels; ch++) {
  997. s->bandwidth_code[ch]--;
  998. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  999. }
  1000. return 0;
  1001. }
  1002. return -1;
  1003. }
  1004. /**
  1005. * Perform bit allocation search.
  1006. * Finds the SNR offset value that maximizes quality and fits in the specified
  1007. * frame size. Output is the SNR offset and a set of bit allocation pointers
  1008. * used to quantize the mantissas.
  1009. */
  1010. static int compute_bit_allocation(AC3EncodeContext *s)
  1011. {
  1012. int ret;
  1013. count_frame_bits(s);
  1014. bit_alloc_masking(s);
  1015. ret = cbr_bit_allocation(s);
  1016. while (ret) {
  1017. /* fallback 1: downgrade exponents */
  1018. if (!downgrade_exponents(s)) {
  1019. extract_exponents(s);
  1020. encode_exponents(s);
  1021. group_exponents(s);
  1022. ret = compute_bit_allocation(s);
  1023. continue;
  1024. }
  1025. /* fallback 2: reduce bandwidth */
  1026. /* only do this if the user has not specified a specific cutoff
  1027. frequency */
  1028. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  1029. process_exponents(s);
  1030. ret = compute_bit_allocation(s);
  1031. continue;
  1032. }
  1033. /* fallbacks were not enough... */
  1034. break;
  1035. }
  1036. return ret;
  1037. }
  1038. /**
  1039. * Symmetric quantization on 'levels' levels.
  1040. */
  1041. static inline int sym_quant(int c, int e, int levels)
  1042. {
  1043. int v = ((((levels * c) >> (24 - e)) + 1) >> 1) + (levels >> 1);
  1044. av_assert2(v >= 0 && v < levels);
  1045. return v;
  1046. }
  1047. /**
  1048. * Asymmetric quantization on 2^qbits levels.
  1049. */
  1050. static inline int asym_quant(int c, int e, int qbits)
  1051. {
  1052. int lshift, m, v;
  1053. lshift = e + qbits - 24;
  1054. if (lshift >= 0)
  1055. v = c << lshift;
  1056. else
  1057. v = c >> (-lshift);
  1058. /* rounding */
  1059. v = (v + 1) >> 1;
  1060. m = (1 << (qbits-1));
  1061. if (v >= m)
  1062. v = m - 1;
  1063. av_assert2(v >= -m);
  1064. return v & ((1 << qbits)-1);
  1065. }
  1066. /**
  1067. * Quantize a set of mantissas for a single channel in a single block.
  1068. */
  1069. static void quantize_mantissas_blk_ch(AC3EncodeContext *s, int32_t *fixed_coef,
  1070. uint8_t *exp,
  1071. uint8_t *bap, uint16_t *qmant, int n)
  1072. {
  1073. int i;
  1074. for (i = 0; i < n; i++) {
  1075. int v;
  1076. int c = fixed_coef[i];
  1077. int e = exp[i];
  1078. int b = bap[i];
  1079. switch (b) {
  1080. case 0:
  1081. v = 0;
  1082. break;
  1083. case 1:
  1084. v = sym_quant(c, e, 3);
  1085. switch (s->mant1_cnt) {
  1086. case 0:
  1087. s->qmant1_ptr = &qmant[i];
  1088. v = 9 * v;
  1089. s->mant1_cnt = 1;
  1090. break;
  1091. case 1:
  1092. *s->qmant1_ptr += 3 * v;
  1093. s->mant1_cnt = 2;
  1094. v = 128;
  1095. break;
  1096. default:
  1097. *s->qmant1_ptr += v;
  1098. s->mant1_cnt = 0;
  1099. v = 128;
  1100. break;
  1101. }
  1102. break;
  1103. case 2:
  1104. v = sym_quant(c, e, 5);
  1105. switch (s->mant2_cnt) {
  1106. case 0:
  1107. s->qmant2_ptr = &qmant[i];
  1108. v = 25 * v;
  1109. s->mant2_cnt = 1;
  1110. break;
  1111. case 1:
  1112. *s->qmant2_ptr += 5 * v;
  1113. s->mant2_cnt = 2;
  1114. v = 128;
  1115. break;
  1116. default:
  1117. *s->qmant2_ptr += v;
  1118. s->mant2_cnt = 0;
  1119. v = 128;
  1120. break;
  1121. }
  1122. break;
  1123. case 3:
  1124. v = sym_quant(c, e, 7);
  1125. break;
  1126. case 4:
  1127. v = sym_quant(c, e, 11);
  1128. switch (s->mant4_cnt) {
  1129. case 0:
  1130. s->qmant4_ptr = &qmant[i];
  1131. v = 11 * v;
  1132. s->mant4_cnt = 1;
  1133. break;
  1134. default:
  1135. *s->qmant4_ptr += v;
  1136. s->mant4_cnt = 0;
  1137. v = 128;
  1138. break;
  1139. }
  1140. break;
  1141. case 5:
  1142. v = sym_quant(c, e, 15);
  1143. break;
  1144. case 14:
  1145. v = asym_quant(c, e, 14);
  1146. break;
  1147. case 15:
  1148. v = asym_quant(c, e, 16);
  1149. break;
  1150. default:
  1151. v = asym_quant(c, e, b - 1);
  1152. break;
  1153. }
  1154. qmant[i] = v;
  1155. }
  1156. }
  1157. /**
  1158. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1159. */
  1160. static void quantize_mantissas(AC3EncodeContext *s)
  1161. {
  1162. int blk, ch;
  1163. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1164. AC3Block *block = &s->blocks[blk];
  1165. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  1166. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  1167. for (ch = 0; ch < s->channels; ch++) {
  1168. quantize_mantissas_blk_ch(s, block->fixed_coef[ch],
  1169. block->exp[ch], block->bap[ch],
  1170. block->qmant[ch], s->nb_coefs[ch]);
  1171. }
  1172. }
  1173. }
  1174. /**
  1175. * Write the AC-3 frame header to the output bitstream.
  1176. */
  1177. static void output_frame_header(AC3EncodeContext *s)
  1178. {
  1179. AC3EncOptions *opt = &s->options;
  1180. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1181. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1182. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1183. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1184. put_bits(&s->pb, 5, s->bitstream_id);
  1185. put_bits(&s->pb, 3, s->bitstream_mode);
  1186. put_bits(&s->pb, 3, s->channel_mode);
  1187. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1188. put_bits(&s->pb, 2, s->center_mix_level);
  1189. if (s->channel_mode & 0x04)
  1190. put_bits(&s->pb, 2, s->surround_mix_level);
  1191. if (s->channel_mode == AC3_CHMODE_STEREO)
  1192. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1193. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1194. put_bits(&s->pb, 5, -opt->dialogue_level);
  1195. put_bits(&s->pb, 1, 0); /* no compression control word */
  1196. put_bits(&s->pb, 1, 0); /* no lang code */
  1197. put_bits(&s->pb, 1, opt->audio_production_info);
  1198. if (opt->audio_production_info) {
  1199. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1200. put_bits(&s->pb, 2, opt->room_type);
  1201. }
  1202. put_bits(&s->pb, 1, opt->copyright);
  1203. put_bits(&s->pb, 1, opt->original);
  1204. if (s->bitstream_id == 6) {
  1205. /* alternate bit stream syntax */
  1206. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1207. if (opt->extended_bsi_1) {
  1208. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1209. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1210. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1211. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1212. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1213. }
  1214. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1215. if (opt->extended_bsi_2) {
  1216. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1217. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1218. put_bits(&s->pb, 1, opt->ad_converter_type);
  1219. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1220. }
  1221. } else {
  1222. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1223. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1224. }
  1225. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1226. }
  1227. /**
  1228. * Write one audio block to the output bitstream.
  1229. */
  1230. static void output_audio_block(AC3EncodeContext *s, int blk)
  1231. {
  1232. int ch, i, baie, rbnd;
  1233. AC3Block *block = &s->blocks[blk];
  1234. /* block switching */
  1235. for (ch = 0; ch < s->fbw_channels; ch++)
  1236. put_bits(&s->pb, 1, 0);
  1237. /* dither flags */
  1238. for (ch = 0; ch < s->fbw_channels; ch++)
  1239. put_bits(&s->pb, 1, 1);
  1240. /* dynamic range codes */
  1241. put_bits(&s->pb, 1, 0);
  1242. /* channel coupling */
  1243. if (!blk) {
  1244. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1245. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1246. } else {
  1247. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1248. }
  1249. /* stereo rematrixing */
  1250. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1251. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1252. if (block->new_rematrixing_strategy) {
  1253. /* rematrixing flags */
  1254. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1255. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1256. }
  1257. }
  1258. /* exponent strategy */
  1259. for (ch = 0; ch < s->fbw_channels; ch++)
  1260. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1261. if (s->lfe_on)
  1262. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1263. /* bandwidth */
  1264. for (ch = 0; ch < s->fbw_channels; ch++) {
  1265. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1266. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1267. }
  1268. /* exponents */
  1269. for (ch = 0; ch < s->channels; ch++) {
  1270. int nb_groups;
  1271. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1272. continue;
  1273. /* DC exponent */
  1274. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1275. /* exponent groups */
  1276. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1277. for (i = 1; i <= nb_groups; i++)
  1278. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1279. /* gain range info */
  1280. if (ch != s->lfe_channel)
  1281. put_bits(&s->pb, 2, 0);
  1282. }
  1283. /* bit allocation info */
  1284. baie = (blk == 0);
  1285. put_bits(&s->pb, 1, baie);
  1286. if (baie) {
  1287. put_bits(&s->pb, 2, s->slow_decay_code);
  1288. put_bits(&s->pb, 2, s->fast_decay_code);
  1289. put_bits(&s->pb, 2, s->slow_gain_code);
  1290. put_bits(&s->pb, 2, s->db_per_bit_code);
  1291. put_bits(&s->pb, 3, s->floor_code);
  1292. }
  1293. /* snr offset */
  1294. put_bits(&s->pb, 1, baie);
  1295. if (baie) {
  1296. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1297. for (ch = 0; ch < s->channels; ch++) {
  1298. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1299. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1300. }
  1301. }
  1302. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1303. put_bits(&s->pb, 1, 0); /* no data to skip */
  1304. /* mantissas */
  1305. for (ch = 0; ch < s->channels; ch++) {
  1306. int b, q;
  1307. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1308. q = block->qmant[ch][i];
  1309. b = block->bap[ch][i];
  1310. switch (b) {
  1311. case 0: break;
  1312. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1313. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1314. case 3: put_bits(&s->pb, 3, q); break;
  1315. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1316. case 14: put_bits(&s->pb, 14, q); break;
  1317. case 15: put_bits(&s->pb, 16, q); break;
  1318. default: put_bits(&s->pb, b-1, q); break;
  1319. }
  1320. }
  1321. }
  1322. }
  1323. /** CRC-16 Polynomial */
  1324. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1325. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1326. {
  1327. unsigned int c;
  1328. c = 0;
  1329. while (a) {
  1330. if (a & 1)
  1331. c ^= b;
  1332. a = a >> 1;
  1333. b = b << 1;
  1334. if (b & (1 << 16))
  1335. b ^= poly;
  1336. }
  1337. return c;
  1338. }
  1339. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1340. {
  1341. unsigned int r;
  1342. r = 1;
  1343. while (n) {
  1344. if (n & 1)
  1345. r = mul_poly(r, a, poly);
  1346. a = mul_poly(a, a, poly);
  1347. n >>= 1;
  1348. }
  1349. return r;
  1350. }
  1351. /**
  1352. * Fill the end of the frame with 0's and compute the two CRCs.
  1353. */
  1354. static void output_frame_end(AC3EncodeContext *s)
  1355. {
  1356. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1357. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1358. uint8_t *frame;
  1359. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1360. /* pad the remainder of the frame with zeros */
  1361. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1362. flush_put_bits(&s->pb);
  1363. frame = s->pb.buf;
  1364. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1365. av_assert2(pad_bytes >= 0);
  1366. if (pad_bytes > 0)
  1367. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1368. /* compute crc1 */
  1369. /* this is not so easy because it is at the beginning of the data... */
  1370. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1371. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1372. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1373. AV_WB16(frame + 2, crc1);
  1374. /* compute crc2 */
  1375. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1376. s->frame_size - frame_size_58 - 3);
  1377. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1378. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1379. if (crc2 == 0x770B) {
  1380. frame[s->frame_size - 3] ^= 0x1;
  1381. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1382. }
  1383. crc2 = av_bswap16(crc2);
  1384. AV_WB16(frame + s->frame_size - 2, crc2);
  1385. }
  1386. /**
  1387. * Write the frame to the output bitstream.
  1388. */
  1389. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1390. {
  1391. int blk;
  1392. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1393. output_frame_header(s);
  1394. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1395. output_audio_block(s, blk);
  1396. output_frame_end(s);
  1397. }
  1398. static void dprint_options(AVCodecContext *avctx)
  1399. {
  1400. #ifdef DEBUG
  1401. AC3EncodeContext *s = avctx->priv_data;
  1402. AC3EncOptions *opt = &s->options;
  1403. char strbuf[32];
  1404. switch (s->bitstream_id) {
  1405. case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1406. case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
  1407. case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1408. case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
  1409. default: snprintf(strbuf, 32, "ERROR");
  1410. }
  1411. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1412. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1413. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1414. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1415. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1416. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1417. if (s->cutoff)
  1418. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1419. av_dlog(avctx, "per_frame_metadata: %s\n",
  1420. opt->allow_per_frame_metadata?"on":"off");
  1421. if (s->has_center)
  1422. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1423. s->center_mix_level);
  1424. else
  1425. av_dlog(avctx, "center_mixlev: {not written}\n");
  1426. if (s->has_surround)
  1427. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1428. s->surround_mix_level);
  1429. else
  1430. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1431. if (opt->audio_production_info) {
  1432. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1433. switch (opt->room_type) {
  1434. case 0: strncpy(strbuf, "notindicated", 32); break;
  1435. case 1: strncpy(strbuf, "large", 32); break;
  1436. case 2: strncpy(strbuf, "small", 32); break;
  1437. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1438. }
  1439. av_dlog(avctx, "room_type: %s\n", strbuf);
  1440. } else {
  1441. av_dlog(avctx, "mixing_level: {not written}\n");
  1442. av_dlog(avctx, "room_type: {not written}\n");
  1443. }
  1444. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1445. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1446. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1447. switch (opt->dolby_surround_mode) {
  1448. case 0: strncpy(strbuf, "notindicated", 32); break;
  1449. case 1: strncpy(strbuf, "on", 32); break;
  1450. case 2: strncpy(strbuf, "off", 32); break;
  1451. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  1452. }
  1453. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1454. } else {
  1455. av_dlog(avctx, "dsur_mode: {not written}\n");
  1456. }
  1457. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1458. if (s->bitstream_id == 6) {
  1459. if (opt->extended_bsi_1) {
  1460. switch (opt->preferred_stereo_downmix) {
  1461. case 0: strncpy(strbuf, "notindicated", 32); break;
  1462. case 1: strncpy(strbuf, "ltrt", 32); break;
  1463. case 2: strncpy(strbuf, "loro", 32); break;
  1464. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1465. }
  1466. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1467. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1468. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1469. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1470. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1471. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1472. opt->loro_center_mix_level, s->loro_center_mix_level);
  1473. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1474. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1475. } else {
  1476. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1477. }
  1478. if (opt->extended_bsi_2) {
  1479. switch (opt->dolby_surround_ex_mode) {
  1480. case 0: strncpy(strbuf, "notindicated", 32); break;
  1481. case 1: strncpy(strbuf, "on", 32); break;
  1482. case 2: strncpy(strbuf, "off", 32); break;
  1483. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1484. }
  1485. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1486. switch (opt->dolby_headphone_mode) {
  1487. case 0: strncpy(strbuf, "notindicated", 32); break;
  1488. case 1: strncpy(strbuf, "on", 32); break;
  1489. case 2: strncpy(strbuf, "off", 32); break;
  1490. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1491. }
  1492. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1493. switch (opt->ad_converter_type) {
  1494. case 0: strncpy(strbuf, "standard", 32); break;
  1495. case 1: strncpy(strbuf, "hdcd", 32); break;
  1496. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1497. }
  1498. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1499. } else {
  1500. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1501. }
  1502. }
  1503. #endif
  1504. }
  1505. #define FLT_OPTION_THRESHOLD 0.01
  1506. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1507. {
  1508. int i;
  1509. for (i = 0; i < v_list_size; i++) {
  1510. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1511. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1512. break;
  1513. }
  1514. if (i == v_list_size)
  1515. return -1;
  1516. return i;
  1517. }
  1518. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1519. float *opt_param, const float *list,
  1520. int list_size, int default_value, int min_value,
  1521. int *ctx_param)
  1522. {
  1523. int mixlev = validate_float_option(*opt_param, list, list_size);
  1524. if (mixlev < min_value) {
  1525. mixlev = default_value;
  1526. if (*opt_param >= 0.0) {
  1527. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1528. "default value: %0.3f\n", opt_name, list[mixlev]);
  1529. }
  1530. }
  1531. *opt_param = list[mixlev];
  1532. *ctx_param = mixlev;
  1533. }
  1534. /**
  1535. * Validate metadata options as set by AVOption system.
  1536. * These values can optionally be changed per-frame.
  1537. */
  1538. static int validate_metadata(AVCodecContext *avctx)
  1539. {
  1540. AC3EncodeContext *s = avctx->priv_data;
  1541. AC3EncOptions *opt = &s->options;
  1542. /* validate mixing levels */
  1543. if (s->has_center) {
  1544. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1545. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1546. &s->center_mix_level);
  1547. }
  1548. if (s->has_surround) {
  1549. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1550. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1551. &s->surround_mix_level);
  1552. }
  1553. /* set audio production info flag */
  1554. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1555. if (opt->mixing_level < 0) {
  1556. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1557. "room_type is set\n");
  1558. return AVERROR(EINVAL);
  1559. }
  1560. if (opt->mixing_level < 80) {
  1561. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1562. "80dB and 111dB\n");
  1563. return AVERROR(EINVAL);
  1564. }
  1565. /* default room type */
  1566. if (opt->room_type < 0)
  1567. opt->room_type = 0;
  1568. opt->audio_production_info = 1;
  1569. } else {
  1570. opt->audio_production_info = 0;
  1571. }
  1572. /* set extended bsi 1 flag */
  1573. if ((s->has_center || s->has_surround) &&
  1574. (opt->preferred_stereo_downmix >= 0 ||
  1575. opt->ltrt_center_mix_level >= 0 ||
  1576. opt->ltrt_surround_mix_level >= 0 ||
  1577. opt->loro_center_mix_level >= 0 ||
  1578. opt->loro_surround_mix_level >= 0)) {
  1579. /* default preferred stereo downmix */
  1580. if (opt->preferred_stereo_downmix < 0)
  1581. opt->preferred_stereo_downmix = 0;
  1582. /* validate Lt/Rt center mix level */
  1583. validate_mix_level(avctx, "ltrt_center_mix_level",
  1584. &opt->ltrt_center_mix_level, extmixlev_options,
  1585. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1586. &s->ltrt_center_mix_level);
  1587. /* validate Lt/Rt surround mix level */
  1588. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1589. &opt->ltrt_surround_mix_level, extmixlev_options,
  1590. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1591. &s->ltrt_surround_mix_level);
  1592. /* validate Lo/Ro center mix level */
  1593. validate_mix_level(avctx, "loro_center_mix_level",
  1594. &opt->loro_center_mix_level, extmixlev_options,
  1595. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1596. &s->loro_center_mix_level);
  1597. /* validate Lo/Ro surround mix level */
  1598. validate_mix_level(avctx, "loro_surround_mix_level",
  1599. &opt->loro_surround_mix_level, extmixlev_options,
  1600. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1601. &s->loro_surround_mix_level);
  1602. opt->extended_bsi_1 = 1;
  1603. } else {
  1604. opt->extended_bsi_1 = 0;
  1605. }
  1606. /* set extended bsi 2 flag */
  1607. if (opt->dolby_surround_ex_mode >= 0 ||
  1608. opt->dolby_headphone_mode >= 0 ||
  1609. opt->ad_converter_type >= 0) {
  1610. /* default dolby surround ex mode */
  1611. if (opt->dolby_surround_ex_mode < 0)
  1612. opt->dolby_surround_ex_mode = 0;
  1613. /* default dolby headphone mode */
  1614. if (opt->dolby_headphone_mode < 0)
  1615. opt->dolby_headphone_mode = 0;
  1616. /* default A/D converter type */
  1617. if (opt->ad_converter_type < 0)
  1618. opt->ad_converter_type = 0;
  1619. opt->extended_bsi_2 = 1;
  1620. } else {
  1621. opt->extended_bsi_2 = 0;
  1622. }
  1623. /* set bitstream id for alternate bitstream syntax */
  1624. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1625. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1626. static int warn_once = 1;
  1627. if (warn_once) {
  1628. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1629. "not compatible with reduced samplerates. writing of "
  1630. "extended bitstream information will be disabled.\n");
  1631. warn_once = 0;
  1632. }
  1633. } else {
  1634. s->bitstream_id = 6;
  1635. }
  1636. }
  1637. return 0;
  1638. }
  1639. /**
  1640. * Encode a single AC-3 frame.
  1641. */
  1642. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1643. int buf_size, void *data)
  1644. {
  1645. AC3EncodeContext *s = avctx->priv_data;
  1646. const SampleType *samples = data;
  1647. int ret;
  1648. if (s->options.allow_per_frame_metadata) {
  1649. ret = validate_metadata(avctx);
  1650. if (ret)
  1651. return ret;
  1652. }
  1653. if (s->bit_alloc.sr_code == 1)
  1654. adjust_frame_size(s);
  1655. deinterleave_input_samples(s, samples);
  1656. apply_mdct(s);
  1657. scale_coefficients(s);
  1658. compute_rematrixing_strategy(s);
  1659. apply_rematrixing(s);
  1660. process_exponents(s);
  1661. ret = compute_bit_allocation(s);
  1662. if (ret) {
  1663. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1664. return ret;
  1665. }
  1666. quantize_mantissas(s);
  1667. output_frame(s, frame);
  1668. return s->frame_size;
  1669. }
  1670. /**
  1671. * Finalize encoding and free any memory allocated by the encoder.
  1672. */
  1673. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1674. {
  1675. int blk, ch;
  1676. AC3EncodeContext *s = avctx->priv_data;
  1677. for (ch = 0; ch < s->channels; ch++)
  1678. av_freep(&s->planar_samples[ch]);
  1679. av_freep(&s->planar_samples);
  1680. av_freep(&s->bap_buffer);
  1681. av_freep(&s->bap1_buffer);
  1682. av_freep(&s->mdct_coef_buffer);
  1683. av_freep(&s->fixed_coef_buffer);
  1684. av_freep(&s->exp_buffer);
  1685. av_freep(&s->grouped_exp_buffer);
  1686. av_freep(&s->psd_buffer);
  1687. av_freep(&s->band_psd_buffer);
  1688. av_freep(&s->mask_buffer);
  1689. av_freep(&s->qmant_buffer);
  1690. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1691. AC3Block *block = &s->blocks[blk];
  1692. av_freep(&block->bap);
  1693. av_freep(&block->mdct_coef);
  1694. av_freep(&block->fixed_coef);
  1695. av_freep(&block->exp);
  1696. av_freep(&block->grouped_exp);
  1697. av_freep(&block->psd);
  1698. av_freep(&block->band_psd);
  1699. av_freep(&block->mask);
  1700. av_freep(&block->qmant);
  1701. }
  1702. mdct_end(&s->mdct);
  1703. av_freep(&avctx->coded_frame);
  1704. return 0;
  1705. }
  1706. /**
  1707. * Set channel information during initialization.
  1708. */
  1709. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1710. int64_t *channel_layout)
  1711. {
  1712. int ch_layout;
  1713. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1714. return AVERROR(EINVAL);
  1715. if ((uint64_t)*channel_layout > 0x7FF)
  1716. return AVERROR(EINVAL);
  1717. ch_layout = *channel_layout;
  1718. if (!ch_layout)
  1719. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1720. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1721. return AVERROR(EINVAL);
  1722. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1723. s->channels = channels;
  1724. s->fbw_channels = channels - s->lfe_on;
  1725. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1726. if (s->lfe_on)
  1727. ch_layout -= AV_CH_LOW_FREQUENCY;
  1728. switch (ch_layout) {
  1729. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1730. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1731. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1732. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1733. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1734. case AV_CH_LAYOUT_QUAD:
  1735. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1736. case AV_CH_LAYOUT_5POINT0:
  1737. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1738. default:
  1739. return AVERROR(EINVAL);
  1740. }
  1741. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1742. s->has_surround = s->channel_mode & 0x04;
  1743. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1744. *channel_layout = ch_layout;
  1745. if (s->lfe_on)
  1746. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1747. return 0;
  1748. }
  1749. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1750. {
  1751. int i, ret;
  1752. /* validate channel layout */
  1753. if (!avctx->channel_layout) {
  1754. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1755. "encoder will guess the layout, but it "
  1756. "might be incorrect.\n");
  1757. }
  1758. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1759. if (ret) {
  1760. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1761. return ret;
  1762. }
  1763. /* validate sample rate */
  1764. for (i = 0; i < 9; i++) {
  1765. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1766. break;
  1767. }
  1768. if (i == 9) {
  1769. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1770. return AVERROR(EINVAL);
  1771. }
  1772. s->sample_rate = avctx->sample_rate;
  1773. s->bit_alloc.sr_shift = i % 3;
  1774. s->bit_alloc.sr_code = i / 3;
  1775. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1776. /* validate bit rate */
  1777. for (i = 0; i < 19; i++) {
  1778. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1779. break;
  1780. }
  1781. if (i == 19) {
  1782. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1783. return AVERROR(EINVAL);
  1784. }
  1785. s->bit_rate = avctx->bit_rate;
  1786. s->frame_size_code = i << 1;
  1787. /* validate cutoff */
  1788. if (avctx->cutoff < 0) {
  1789. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1790. return AVERROR(EINVAL);
  1791. }
  1792. s->cutoff = avctx->cutoff;
  1793. if (s->cutoff > (s->sample_rate >> 1))
  1794. s->cutoff = s->sample_rate >> 1;
  1795. /* validate audio service type / channels combination */
  1796. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1797. avctx->channels == 1) ||
  1798. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1799. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1800. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1801. && avctx->channels > 1)) {
  1802. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1803. "specified number of channels\n");
  1804. return AVERROR(EINVAL);
  1805. }
  1806. ret = validate_metadata(avctx);
  1807. if (ret)
  1808. return ret;
  1809. return 0;
  1810. }
  1811. /**
  1812. * Set bandwidth for all channels.
  1813. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1814. * default value will be used.
  1815. */
  1816. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1817. {
  1818. int ch, bw_code;
  1819. if (s->cutoff) {
  1820. /* calculate bandwidth based on user-specified cutoff frequency */
  1821. int fbw_coeffs;
  1822. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1823. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1824. } else {
  1825. /* use default bandwidth setting */
  1826. /* XXX: should compute the bandwidth according to the frame
  1827. size, so that we avoid annoying high frequency artifacts */
  1828. bw_code = 50;
  1829. }
  1830. /* set number of coefficients for each channel */
  1831. for (ch = 0; ch < s->fbw_channels; ch++) {
  1832. s->bandwidth_code[ch] = bw_code;
  1833. s->nb_coefs[ch] = bw_code * 3 + 73;
  1834. }
  1835. if (s->lfe_on)
  1836. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1837. }
  1838. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1839. {
  1840. int blk, ch;
  1841. AC3EncodeContext *s = avctx->priv_data;
  1842. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1843. alloc_fail);
  1844. for (ch = 0; ch < s->channels; ch++) {
  1845. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1846. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1847. alloc_fail);
  1848. }
  1849. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1850. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1851. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1852. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1853. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1854. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1855. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1856. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1857. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1858. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1859. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1860. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1861. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1862. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1863. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1864. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1865. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1866. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1867. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1868. AC3Block *block = &s->blocks[blk];
  1869. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1870. alloc_fail);
  1871. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1872. alloc_fail);
  1873. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1874. alloc_fail);
  1875. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1876. alloc_fail);
  1877. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1878. alloc_fail);
  1879. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1880. alloc_fail);
  1881. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1882. alloc_fail);
  1883. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1884. alloc_fail);
  1885. for (ch = 0; ch < s->channels; ch++) {
  1886. /* arrangement: block, channel, coeff */
  1887. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1888. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1889. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1890. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1891. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1892. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1893. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1894. /* arrangement: channel, block, coeff */
  1895. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1896. }
  1897. }
  1898. if (CONFIG_AC3ENC_FLOAT) {
  1899. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1900. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1901. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1902. AC3Block *block = &s->blocks[blk];
  1903. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1904. sizeof(*block->fixed_coef), alloc_fail);
  1905. for (ch = 0; ch < s->channels; ch++)
  1906. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1907. }
  1908. } else {
  1909. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1910. AC3Block *block = &s->blocks[blk];
  1911. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1912. sizeof(*block->fixed_coef), alloc_fail);
  1913. for (ch = 0; ch < s->channels; ch++)
  1914. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1915. }
  1916. }
  1917. return 0;
  1918. alloc_fail:
  1919. return AVERROR(ENOMEM);
  1920. }
  1921. /**
  1922. * Initialize the encoder.
  1923. */
  1924. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1925. {
  1926. AC3EncodeContext *s = avctx->priv_data;
  1927. int ret, frame_size_58;
  1928. avctx->frame_size = AC3_FRAME_SIZE;
  1929. ff_ac3_common_init();
  1930. ret = validate_options(avctx, s);
  1931. if (ret)
  1932. return ret;
  1933. s->bitstream_mode = avctx->audio_service_type;
  1934. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  1935. s->bitstream_mode = 0x7;
  1936. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1937. s->bits_written = 0;
  1938. s->samples_written = 0;
  1939. s->frame_size = s->frame_size_min;
  1940. /* calculate crc_inv for both possible frame sizes */
  1941. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1942. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1943. if (s->bit_alloc.sr_code == 1) {
  1944. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1945. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1946. }
  1947. set_bandwidth(s);
  1948. rematrixing_init(s);
  1949. exponent_init(s);
  1950. bit_alloc_init(s);
  1951. ret = mdct_init(avctx, &s->mdct, 9);
  1952. if (ret)
  1953. goto init_fail;
  1954. ret = allocate_buffers(avctx);
  1955. if (ret)
  1956. goto init_fail;
  1957. avctx->coded_frame= avcodec_alloc_frame();
  1958. dsputil_init(&s->dsp, avctx);
  1959. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1960. dprint_options(avctx);
  1961. return 0;
  1962. init_fail:
  1963. ac3_encode_close(avctx);
  1964. return ret;
  1965. }