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.

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