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.

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