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.

2217 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 */
  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. /* block switch flags */
  677. frame_bits += s->fbw_channels;
  678. /* dither flags */
  679. frame_bits += s->fbw_channels;
  680. /* dynamic range */
  681. frame_bits++;
  682. /* coupling strategy */
  683. frame_bits++;
  684. if (!blk)
  685. frame_bits++;
  686. /* exponent strategy */
  687. frame_bits += 2 * s->fbw_channels;
  688. if (s->lfe_on)
  689. frame_bits++;
  690. /* bit allocation params */
  691. frame_bits++;
  692. if (!blk)
  693. frame_bits += 2 + 2 + 2 + 2 + 3;
  694. /* snr offsets and fast gain codes */
  695. frame_bits++;
  696. if (!blk)
  697. frame_bits += 6 + s->channels * (4 + 3);
  698. /* delta bit allocation */
  699. frame_bits++;
  700. /* skipped data */
  701. frame_bits++;
  702. }
  703. /* auxiliary data */
  704. frame_bits++;
  705. /* CRC */
  706. frame_bits += 1 + 16;
  707. s->frame_bits_fixed = frame_bits;
  708. }
  709. /**
  710. * Initialize bit allocation.
  711. * Set default parameter codes and calculate parameter values.
  712. */
  713. static void bit_alloc_init(AC3EncodeContext *s)
  714. {
  715. int ch;
  716. /* init default parameters */
  717. s->slow_decay_code = 2;
  718. s->fast_decay_code = 1;
  719. s->slow_gain_code = 1;
  720. s->db_per_bit_code = 3;
  721. s->floor_code = 7;
  722. for (ch = 0; ch < s->channels; ch++)
  723. s->fast_gain_code[ch] = 4;
  724. /* initial snr offset */
  725. s->coarse_snr_offset = 40;
  726. /* compute real values */
  727. /* currently none of these values change during encoding, so we can just
  728. set them once at initialization */
  729. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  730. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  731. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  732. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  733. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  734. count_frame_bits_fixed(s);
  735. }
  736. /**
  737. * Count the bits used to encode the frame, minus exponents and mantissas.
  738. * Bits based on fixed parameters have already been counted, so now we just
  739. * have to add the bits based on parameters that change during encoding.
  740. */
  741. static void count_frame_bits(AC3EncodeContext *s)
  742. {
  743. AC3EncOptions *opt = &s->options;
  744. int blk, ch;
  745. int frame_bits = 0;
  746. /* header */
  747. if (opt->audio_production_info)
  748. frame_bits += 7;
  749. if (s->bitstream_id == 6) {
  750. if (opt->extended_bsi_1)
  751. frame_bits += 14;
  752. if (opt->extended_bsi_2)
  753. frame_bits += 14;
  754. }
  755. /* audio blocks */
  756. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  757. /* stereo rematrixing */
  758. if (s->channel_mode == AC3_CHMODE_STEREO) {
  759. frame_bits++;
  760. if (s->blocks[blk].new_rematrixing_strategy)
  761. frame_bits += s->num_rematrixing_bands;
  762. }
  763. /* bandwidth codes & gain range */
  764. for (ch = 0; ch < s->fbw_channels; ch++) {
  765. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  766. frame_bits += 6 + 2;
  767. }
  768. }
  769. s->frame_bits = s->frame_bits_fixed + frame_bits;
  770. }
  771. /**
  772. * Finalize the mantissa bit count by adding in the grouped mantissas.
  773. */
  774. static int compute_mantissa_size_final(int mant_cnt[5])
  775. {
  776. // bap=1 : 3 mantissas in 5 bits
  777. int bits = (mant_cnt[1] / 3) * 5;
  778. // bap=2 : 3 mantissas in 7 bits
  779. // bap=4 : 2 mantissas in 7 bits
  780. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  781. // bap=3 : each mantissa is 3 bits
  782. bits += mant_cnt[3] * 3;
  783. return bits;
  784. }
  785. /**
  786. * Calculate masking curve based on the final exponents.
  787. * Also calculate the power spectral densities to use in future calculations.
  788. */
  789. static void bit_alloc_masking(AC3EncodeContext *s)
  790. {
  791. int blk, ch;
  792. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  793. AC3Block *block = &s->blocks[blk];
  794. for (ch = 0; ch < s->channels; ch++) {
  795. /* We only need psd and mask for calculating bap.
  796. Since we currently do not calculate bap when exponent
  797. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  798. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  799. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  800. s->nb_coefs[ch],
  801. block->psd[ch], block->band_psd[ch]);
  802. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  803. 0, s->nb_coefs[ch],
  804. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  805. ch == s->lfe_channel,
  806. DBA_NONE, 0, NULL, NULL, NULL,
  807. block->mask[ch]);
  808. }
  809. }
  810. }
  811. }
  812. /**
  813. * Ensure that bap for each block and channel point to the current bap_buffer.
  814. * They may have been switched during the bit allocation search.
  815. */
  816. static void reset_block_bap(AC3EncodeContext *s)
  817. {
  818. int blk, ch;
  819. if (s->blocks[0].bap[0] == s->bap_buffer)
  820. return;
  821. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  822. for (ch = 0; ch < s->channels; ch++) {
  823. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  824. }
  825. }
  826. }
  827. /**
  828. * Run the bit allocation with a given SNR offset.
  829. * This calculates the bit allocation pointers that will be used to determine
  830. * the quantization of each mantissa.
  831. * @return the number of bits needed for mantissas if the given SNR offset is
  832. * is used.
  833. */
  834. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  835. {
  836. int blk, ch;
  837. int mantissa_bits;
  838. int mant_cnt[5];
  839. snr_offset = (snr_offset - 240) << 2;
  840. reset_block_bap(s);
  841. mantissa_bits = 0;
  842. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  843. AC3Block *block = &s->blocks[blk];
  844. AC3Block *ref_block;
  845. // initialize grouped mantissa counts. these are set so that they are
  846. // padded to the next whole group size when bits are counted in
  847. // compute_mantissa_size_final
  848. mant_cnt[0] = mant_cnt[3] = 0;
  849. mant_cnt[1] = mant_cnt[2] = 2;
  850. mant_cnt[4] = 1;
  851. for (ch = 0; ch < s->channels; ch++) {
  852. /* Currently the only bit allocation parameters which vary across
  853. blocks within a frame are the exponent values. We can take
  854. advantage of that by reusing the bit allocation pointers
  855. whenever we reuse exponents. */
  856. ref_block = block->exp_ref_block[ch];
  857. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  858. s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
  859. ref_block->psd[ch], 0,
  860. s->nb_coefs[ch], snr_offset,
  861. s->bit_alloc.floor, ff_ac3_bap_tab,
  862. ref_block->bap[ch]);
  863. }
  864. mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
  865. ref_block->bap[ch],
  866. s->nb_coefs[ch]);
  867. }
  868. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  869. }
  870. return mantissa_bits;
  871. }
  872. /**
  873. * Constant bitrate bit allocation search.
  874. * Find the largest SNR offset that will allow data to fit in the frame.
  875. */
  876. static int cbr_bit_allocation(AC3EncodeContext *s)
  877. {
  878. int ch;
  879. int bits_left;
  880. int snr_offset, snr_incr;
  881. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  882. if (bits_left < 0)
  883. return AVERROR(EINVAL);
  884. snr_offset = s->coarse_snr_offset << 4;
  885. /* if previous frame SNR offset was 1023, check if current frame can also
  886. use SNR offset of 1023. if so, skip the search. */
  887. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  888. if (bit_alloc(s, 1023) <= bits_left)
  889. return 0;
  890. }
  891. while (snr_offset >= 0 &&
  892. bit_alloc(s, snr_offset) > bits_left) {
  893. snr_offset -= 64;
  894. }
  895. if (snr_offset < 0)
  896. return AVERROR(EINVAL);
  897. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  898. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  899. while (snr_offset + snr_incr <= 1023 &&
  900. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  901. snr_offset += snr_incr;
  902. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  903. }
  904. }
  905. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  906. reset_block_bap(s);
  907. s->coarse_snr_offset = snr_offset >> 4;
  908. for (ch = 0; ch < s->channels; ch++)
  909. s->fine_snr_offset[ch] = snr_offset & 0xF;
  910. return 0;
  911. }
  912. /**
  913. * Downgrade exponent strategies to reduce the bits used by the exponents.
  914. * This is a fallback for when bit allocation fails with the normal exponent
  915. * strategies. Each time this function is run it only downgrades the
  916. * strategy in 1 channel of 1 block.
  917. * @return non-zero if downgrade was unsuccessful
  918. */
  919. static int downgrade_exponents(AC3EncodeContext *s)
  920. {
  921. int ch, blk;
  922. for (ch = 0; ch < s->fbw_channels; ch++) {
  923. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  924. if (s->exp_strategy[ch][blk] == EXP_D15) {
  925. s->exp_strategy[ch][blk] = EXP_D25;
  926. return 0;
  927. }
  928. }
  929. }
  930. for (ch = 0; ch < s->fbw_channels; ch++) {
  931. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  932. if (s->exp_strategy[ch][blk] == EXP_D25) {
  933. s->exp_strategy[ch][blk] = EXP_D45;
  934. return 0;
  935. }
  936. }
  937. }
  938. for (ch = 0; ch < s->fbw_channels; ch++) {
  939. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  940. the block number > 0 */
  941. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  942. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  943. s->exp_strategy[ch][blk] = EXP_REUSE;
  944. return 0;
  945. }
  946. }
  947. }
  948. return -1;
  949. }
  950. /**
  951. * Perform bit allocation search.
  952. * Finds the SNR offset value that maximizes quality and fits in the specified
  953. * frame size. Output is the SNR offset and a set of bit allocation pointers
  954. * used to quantize the mantissas.
  955. */
  956. static int compute_bit_allocation(AC3EncodeContext *s)
  957. {
  958. int ret;
  959. count_frame_bits(s);
  960. bit_alloc_masking(s);
  961. ret = cbr_bit_allocation(s);
  962. while (ret) {
  963. /* fallback 1: downgrade exponents */
  964. if (!downgrade_exponents(s)) {
  965. extract_exponents(s);
  966. encode_exponents(s);
  967. group_exponents(s);
  968. ret = compute_bit_allocation(s);
  969. continue;
  970. }
  971. /* fallbacks were not enough... */
  972. break;
  973. }
  974. return ret;
  975. }
  976. /**
  977. * Symmetric quantization on 'levels' levels.
  978. */
  979. static inline int sym_quant(int c, int e, int levels)
  980. {
  981. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  982. av_assert2(v >= 0 && v < levels);
  983. return v;
  984. }
  985. /**
  986. * Asymmetric quantization on 2^qbits levels.
  987. */
  988. static inline int asym_quant(int c, int e, int qbits)
  989. {
  990. int lshift, m, v;
  991. lshift = e + qbits - 24;
  992. if (lshift >= 0)
  993. v = c << lshift;
  994. else
  995. v = c >> (-lshift);
  996. /* rounding */
  997. v = (v + 1) >> 1;
  998. m = (1 << (qbits-1));
  999. if (v >= m)
  1000. v = m - 1;
  1001. av_assert2(v >= -m);
  1002. return v & ((1 << qbits)-1);
  1003. }
  1004. /**
  1005. * Quantize a set of mantissas for a single channel in a single block.
  1006. */
  1007. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1008. uint8_t *exp,
  1009. uint8_t *bap, uint16_t *qmant, int n)
  1010. {
  1011. int i;
  1012. for (i = 0; i < n; i++) {
  1013. int v;
  1014. int c = fixed_coef[i];
  1015. int e = exp[i];
  1016. int b = bap[i];
  1017. switch (b) {
  1018. case 0:
  1019. v = 0;
  1020. break;
  1021. case 1:
  1022. v = sym_quant(c, e, 3);
  1023. switch (s->mant1_cnt) {
  1024. case 0:
  1025. s->qmant1_ptr = &qmant[i];
  1026. v = 9 * v;
  1027. s->mant1_cnt = 1;
  1028. break;
  1029. case 1:
  1030. *s->qmant1_ptr += 3 * v;
  1031. s->mant1_cnt = 2;
  1032. v = 128;
  1033. break;
  1034. default:
  1035. *s->qmant1_ptr += v;
  1036. s->mant1_cnt = 0;
  1037. v = 128;
  1038. break;
  1039. }
  1040. break;
  1041. case 2:
  1042. v = sym_quant(c, e, 5);
  1043. switch (s->mant2_cnt) {
  1044. case 0:
  1045. s->qmant2_ptr = &qmant[i];
  1046. v = 25 * v;
  1047. s->mant2_cnt = 1;
  1048. break;
  1049. case 1:
  1050. *s->qmant2_ptr += 5 * v;
  1051. s->mant2_cnt = 2;
  1052. v = 128;
  1053. break;
  1054. default:
  1055. *s->qmant2_ptr += v;
  1056. s->mant2_cnt = 0;
  1057. v = 128;
  1058. break;
  1059. }
  1060. break;
  1061. case 3:
  1062. v = sym_quant(c, e, 7);
  1063. break;
  1064. case 4:
  1065. v = sym_quant(c, e, 11);
  1066. switch (s->mant4_cnt) {
  1067. case 0:
  1068. s->qmant4_ptr = &qmant[i];
  1069. v = 11 * v;
  1070. s->mant4_cnt = 1;
  1071. break;
  1072. default:
  1073. *s->qmant4_ptr += v;
  1074. s->mant4_cnt = 0;
  1075. v = 128;
  1076. break;
  1077. }
  1078. break;
  1079. case 5:
  1080. v = sym_quant(c, e, 15);
  1081. break;
  1082. case 14:
  1083. v = asym_quant(c, e, 14);
  1084. break;
  1085. case 15:
  1086. v = asym_quant(c, e, 16);
  1087. break;
  1088. default:
  1089. v = asym_quant(c, e, b - 1);
  1090. break;
  1091. }
  1092. qmant[i] = v;
  1093. }
  1094. }
  1095. /**
  1096. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1097. */
  1098. static void quantize_mantissas(AC3EncodeContext *s)
  1099. {
  1100. int blk, ch;
  1101. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1102. AC3Block *block = &s->blocks[blk];
  1103. AC3Block *ref_block;
  1104. AC3Mant m = { 0 };
  1105. for (ch = 0; ch < s->channels; ch++) {
  1106. ref_block = block->exp_ref_block[ch];
  1107. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1108. ref_block->exp[ch], ref_block->bap[ch],
  1109. block->qmant[ch], s->nb_coefs[ch]);
  1110. }
  1111. }
  1112. }
  1113. /**
  1114. * Write the AC-3 frame header to the output bitstream.
  1115. */
  1116. static void output_frame_header(AC3EncodeContext *s)
  1117. {
  1118. AC3EncOptions *opt = &s->options;
  1119. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1120. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1121. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1122. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1123. put_bits(&s->pb, 5, s->bitstream_id);
  1124. put_bits(&s->pb, 3, s->bitstream_mode);
  1125. put_bits(&s->pb, 3, s->channel_mode);
  1126. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1127. put_bits(&s->pb, 2, s->center_mix_level);
  1128. if (s->channel_mode & 0x04)
  1129. put_bits(&s->pb, 2, s->surround_mix_level);
  1130. if (s->channel_mode == AC3_CHMODE_STEREO)
  1131. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1132. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1133. put_bits(&s->pb, 5, -opt->dialogue_level);
  1134. put_bits(&s->pb, 1, 0); /* no compression control word */
  1135. put_bits(&s->pb, 1, 0); /* no lang code */
  1136. put_bits(&s->pb, 1, opt->audio_production_info);
  1137. if (opt->audio_production_info) {
  1138. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1139. put_bits(&s->pb, 2, opt->room_type);
  1140. }
  1141. put_bits(&s->pb, 1, opt->copyright);
  1142. put_bits(&s->pb, 1, opt->original);
  1143. if (s->bitstream_id == 6) {
  1144. /* alternate bit stream syntax */
  1145. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1146. if (opt->extended_bsi_1) {
  1147. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1148. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1149. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1150. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1151. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1152. }
  1153. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1154. if (opt->extended_bsi_2) {
  1155. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1156. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1157. put_bits(&s->pb, 1, opt->ad_converter_type);
  1158. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1159. }
  1160. } else {
  1161. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1162. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1163. }
  1164. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1165. }
  1166. /**
  1167. * Write one audio block to the output bitstream.
  1168. */
  1169. static void output_audio_block(AC3EncodeContext *s, int blk)
  1170. {
  1171. int ch, i, baie, rbnd;
  1172. AC3Block *block = &s->blocks[blk];
  1173. /* block switching */
  1174. for (ch = 0; ch < s->fbw_channels; ch++)
  1175. put_bits(&s->pb, 1, 0);
  1176. /* dither flags */
  1177. for (ch = 0; ch < s->fbw_channels; ch++)
  1178. put_bits(&s->pb, 1, 1);
  1179. /* dynamic range codes */
  1180. put_bits(&s->pb, 1, 0);
  1181. /* channel coupling */
  1182. if (!blk) {
  1183. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1184. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1185. } else {
  1186. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1187. }
  1188. /* stereo rematrixing */
  1189. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1190. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1191. if (block->new_rematrixing_strategy) {
  1192. /* rematrixing flags */
  1193. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1194. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1195. }
  1196. }
  1197. /* exponent strategy */
  1198. for (ch = 0; ch < s->fbw_channels; ch++)
  1199. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1200. if (s->lfe_on)
  1201. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1202. /* bandwidth */
  1203. for (ch = 0; ch < s->fbw_channels; ch++) {
  1204. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1205. put_bits(&s->pb, 6, s->bandwidth_code);
  1206. }
  1207. /* exponents */
  1208. for (ch = 0; ch < s->channels; ch++) {
  1209. int nb_groups;
  1210. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1211. continue;
  1212. /* DC exponent */
  1213. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1214. /* exponent groups */
  1215. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1216. for (i = 1; i <= nb_groups; i++)
  1217. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1218. /* gain range info */
  1219. if (ch != s->lfe_channel)
  1220. put_bits(&s->pb, 2, 0);
  1221. }
  1222. /* bit allocation info */
  1223. baie = (blk == 0);
  1224. put_bits(&s->pb, 1, baie);
  1225. if (baie) {
  1226. put_bits(&s->pb, 2, s->slow_decay_code);
  1227. put_bits(&s->pb, 2, s->fast_decay_code);
  1228. put_bits(&s->pb, 2, s->slow_gain_code);
  1229. put_bits(&s->pb, 2, s->db_per_bit_code);
  1230. put_bits(&s->pb, 3, s->floor_code);
  1231. }
  1232. /* snr offset */
  1233. put_bits(&s->pb, 1, baie);
  1234. if (baie) {
  1235. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1236. for (ch = 0; ch < s->channels; ch++) {
  1237. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1238. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1239. }
  1240. }
  1241. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1242. put_bits(&s->pb, 1, 0); /* no data to skip */
  1243. /* mantissas */
  1244. for (ch = 0; ch < s->channels; ch++) {
  1245. int b, q;
  1246. AC3Block *ref_block = block->exp_ref_block[ch];
  1247. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1248. q = block->qmant[ch][i];
  1249. b = ref_block->bap[ch][i];
  1250. switch (b) {
  1251. case 0: break;
  1252. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1253. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1254. case 3: put_bits(&s->pb, 3, q); break;
  1255. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1256. case 14: put_bits(&s->pb, 14, q); break;
  1257. case 15: put_bits(&s->pb, 16, q); break;
  1258. default: put_bits(&s->pb, b-1, q); break;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. /** CRC-16 Polynomial */
  1264. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1265. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1266. {
  1267. unsigned int c;
  1268. c = 0;
  1269. while (a) {
  1270. if (a & 1)
  1271. c ^= b;
  1272. a = a >> 1;
  1273. b = b << 1;
  1274. if (b & (1 << 16))
  1275. b ^= poly;
  1276. }
  1277. return c;
  1278. }
  1279. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1280. {
  1281. unsigned int r;
  1282. r = 1;
  1283. while (n) {
  1284. if (n & 1)
  1285. r = mul_poly(r, a, poly);
  1286. a = mul_poly(a, a, poly);
  1287. n >>= 1;
  1288. }
  1289. return r;
  1290. }
  1291. /**
  1292. * Fill the end of the frame with 0's and compute the two CRCs.
  1293. */
  1294. static void output_frame_end(AC3EncodeContext *s)
  1295. {
  1296. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1297. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1298. uint8_t *frame;
  1299. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1300. /* pad the remainder of the frame with zeros */
  1301. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1302. flush_put_bits(&s->pb);
  1303. frame = s->pb.buf;
  1304. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1305. av_assert2(pad_bytes >= 0);
  1306. if (pad_bytes > 0)
  1307. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1308. /* compute crc1 */
  1309. /* this is not so easy because it is at the beginning of the data... */
  1310. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1311. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1312. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1313. AV_WB16(frame + 2, crc1);
  1314. /* compute crc2 */
  1315. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1316. s->frame_size - frame_size_58 - 3);
  1317. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1318. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1319. if (crc2 == 0x770B) {
  1320. frame[s->frame_size - 3] ^= 0x1;
  1321. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1322. }
  1323. crc2 = av_bswap16(crc2);
  1324. AV_WB16(frame + s->frame_size - 2, crc2);
  1325. }
  1326. /**
  1327. * Write the frame to the output bitstream.
  1328. */
  1329. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1330. {
  1331. int blk;
  1332. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1333. output_frame_header(s);
  1334. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1335. output_audio_block(s, blk);
  1336. output_frame_end(s);
  1337. }
  1338. static void dprint_options(AVCodecContext *avctx)
  1339. {
  1340. #ifdef DEBUG
  1341. AC3EncodeContext *s = avctx->priv_data;
  1342. AC3EncOptions *opt = &s->options;
  1343. char strbuf[32];
  1344. switch (s->bitstream_id) {
  1345. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1346. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1347. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1348. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
  1349. default: snprintf(strbuf, 32, "ERROR");
  1350. }
  1351. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1352. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1353. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1354. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1355. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1356. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1357. if (s->cutoff)
  1358. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1359. av_dlog(avctx, "per_frame_metadata: %s\n",
  1360. opt->allow_per_frame_metadata?"on":"off");
  1361. if (s->has_center)
  1362. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1363. s->center_mix_level);
  1364. else
  1365. av_dlog(avctx, "center_mixlev: {not written}\n");
  1366. if (s->has_surround)
  1367. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1368. s->surround_mix_level);
  1369. else
  1370. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1371. if (opt->audio_production_info) {
  1372. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1373. switch (opt->room_type) {
  1374. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1375. case 1: av_strlcpy(strbuf, "large", 32); break;
  1376. case 2: av_strlcpy(strbuf, "small", 32); break;
  1377. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1378. }
  1379. av_dlog(avctx, "room_type: %s\n", strbuf);
  1380. } else {
  1381. av_dlog(avctx, "mixing_level: {not written}\n");
  1382. av_dlog(avctx, "room_type: {not written}\n");
  1383. }
  1384. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1385. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1386. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1387. switch (opt->dolby_surround_mode) {
  1388. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1389. case 1: av_strlcpy(strbuf, "on", 32); break;
  1390. case 2: av_strlcpy(strbuf, "off", 32); break;
  1391. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  1392. }
  1393. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1394. } else {
  1395. av_dlog(avctx, "dsur_mode: {not written}\n");
  1396. }
  1397. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1398. if (s->bitstream_id == 6) {
  1399. if (opt->extended_bsi_1) {
  1400. switch (opt->preferred_stereo_downmix) {
  1401. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1402. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  1403. case 2: av_strlcpy(strbuf, "loro", 32); break;
  1404. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1405. }
  1406. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1407. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1408. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1409. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1410. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1411. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1412. opt->loro_center_mix_level, s->loro_center_mix_level);
  1413. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1414. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1415. } else {
  1416. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1417. }
  1418. if (opt->extended_bsi_2) {
  1419. switch (opt->dolby_surround_ex_mode) {
  1420. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1421. case 1: av_strlcpy(strbuf, "on", 32); break;
  1422. case 2: av_strlcpy(strbuf, "off", 32); break;
  1423. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1424. }
  1425. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1426. switch (opt->dolby_headphone_mode) {
  1427. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1428. case 1: av_strlcpy(strbuf, "on", 32); break;
  1429. case 2: av_strlcpy(strbuf, "off", 32); break;
  1430. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1431. }
  1432. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1433. switch (opt->ad_converter_type) {
  1434. case 0: av_strlcpy(strbuf, "standard", 32); break;
  1435. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  1436. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1437. }
  1438. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1439. } else {
  1440. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1441. }
  1442. }
  1443. #endif
  1444. }
  1445. #define FLT_OPTION_THRESHOLD 0.01
  1446. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1447. {
  1448. int i;
  1449. for (i = 0; i < v_list_size; i++) {
  1450. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1451. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1452. break;
  1453. }
  1454. if (i == v_list_size)
  1455. return -1;
  1456. return i;
  1457. }
  1458. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1459. float *opt_param, const float *list,
  1460. int list_size, int default_value, int min_value,
  1461. int *ctx_param)
  1462. {
  1463. int mixlev = validate_float_option(*opt_param, list, list_size);
  1464. if (mixlev < min_value) {
  1465. mixlev = default_value;
  1466. if (*opt_param >= 0.0) {
  1467. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1468. "default value: %0.3f\n", opt_name, list[mixlev]);
  1469. }
  1470. }
  1471. *opt_param = list[mixlev];
  1472. *ctx_param = mixlev;
  1473. }
  1474. /**
  1475. * Validate metadata options as set by AVOption system.
  1476. * These values can optionally be changed per-frame.
  1477. */
  1478. static int validate_metadata(AVCodecContext *avctx)
  1479. {
  1480. AC3EncodeContext *s = avctx->priv_data;
  1481. AC3EncOptions *opt = &s->options;
  1482. /* validate mixing levels */
  1483. if (s->has_center) {
  1484. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1485. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1486. &s->center_mix_level);
  1487. }
  1488. if (s->has_surround) {
  1489. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1490. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1491. &s->surround_mix_level);
  1492. }
  1493. /* set audio production info flag */
  1494. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1495. if (opt->mixing_level < 0) {
  1496. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1497. "room_type is set\n");
  1498. return AVERROR(EINVAL);
  1499. }
  1500. if (opt->mixing_level < 80) {
  1501. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1502. "80dB and 111dB\n");
  1503. return AVERROR(EINVAL);
  1504. }
  1505. /* default room type */
  1506. if (opt->room_type < 0)
  1507. opt->room_type = 0;
  1508. opt->audio_production_info = 1;
  1509. } else {
  1510. opt->audio_production_info = 0;
  1511. }
  1512. /* set extended bsi 1 flag */
  1513. if ((s->has_center || s->has_surround) &&
  1514. (opt->preferred_stereo_downmix >= 0 ||
  1515. opt->ltrt_center_mix_level >= 0 ||
  1516. opt->ltrt_surround_mix_level >= 0 ||
  1517. opt->loro_center_mix_level >= 0 ||
  1518. opt->loro_surround_mix_level >= 0)) {
  1519. /* default preferred stereo downmix */
  1520. if (opt->preferred_stereo_downmix < 0)
  1521. opt->preferred_stereo_downmix = 0;
  1522. /* validate Lt/Rt center mix level */
  1523. validate_mix_level(avctx, "ltrt_center_mix_level",
  1524. &opt->ltrt_center_mix_level, extmixlev_options,
  1525. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1526. &s->ltrt_center_mix_level);
  1527. /* validate Lt/Rt surround mix level */
  1528. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1529. &opt->ltrt_surround_mix_level, extmixlev_options,
  1530. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1531. &s->ltrt_surround_mix_level);
  1532. /* validate Lo/Ro center mix level */
  1533. validate_mix_level(avctx, "loro_center_mix_level",
  1534. &opt->loro_center_mix_level, extmixlev_options,
  1535. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1536. &s->loro_center_mix_level);
  1537. /* validate Lo/Ro surround mix level */
  1538. validate_mix_level(avctx, "loro_surround_mix_level",
  1539. &opt->loro_surround_mix_level, extmixlev_options,
  1540. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1541. &s->loro_surround_mix_level);
  1542. opt->extended_bsi_1 = 1;
  1543. } else {
  1544. opt->extended_bsi_1 = 0;
  1545. }
  1546. /* set extended bsi 2 flag */
  1547. if (opt->dolby_surround_ex_mode >= 0 ||
  1548. opt->dolby_headphone_mode >= 0 ||
  1549. opt->ad_converter_type >= 0) {
  1550. /* default dolby surround ex mode */
  1551. if (opt->dolby_surround_ex_mode < 0)
  1552. opt->dolby_surround_ex_mode = 0;
  1553. /* default dolby headphone mode */
  1554. if (opt->dolby_headphone_mode < 0)
  1555. opt->dolby_headphone_mode = 0;
  1556. /* default A/D converter type */
  1557. if (opt->ad_converter_type < 0)
  1558. opt->ad_converter_type = 0;
  1559. opt->extended_bsi_2 = 1;
  1560. } else {
  1561. opt->extended_bsi_2 = 0;
  1562. }
  1563. /* set bitstream id for alternate bitstream syntax */
  1564. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1565. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1566. static int warn_once = 1;
  1567. if (warn_once) {
  1568. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1569. "not compatible with reduced samplerates. writing of "
  1570. "extended bitstream information will be disabled.\n");
  1571. warn_once = 0;
  1572. }
  1573. } else {
  1574. s->bitstream_id = 6;
  1575. }
  1576. }
  1577. return 0;
  1578. }
  1579. /**
  1580. * Encode a single AC-3 frame.
  1581. */
  1582. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1583. int buf_size, void *data)
  1584. {
  1585. AC3EncodeContext *s = avctx->priv_data;
  1586. const SampleType *samples = data;
  1587. int ret;
  1588. if (s->options.allow_per_frame_metadata) {
  1589. ret = validate_metadata(avctx);
  1590. if (ret)
  1591. return ret;
  1592. }
  1593. if (s->bit_alloc.sr_code == 1)
  1594. adjust_frame_size(s);
  1595. deinterleave_input_samples(s, samples);
  1596. apply_mdct(s);
  1597. scale_coefficients(s);
  1598. compute_rematrixing_strategy(s);
  1599. apply_rematrixing(s);
  1600. process_exponents(s);
  1601. ret = compute_bit_allocation(s);
  1602. if (ret) {
  1603. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1604. return ret;
  1605. }
  1606. quantize_mantissas(s);
  1607. output_frame(s, frame);
  1608. return s->frame_size;
  1609. }
  1610. /**
  1611. * Finalize encoding and free any memory allocated by the encoder.
  1612. */
  1613. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1614. {
  1615. int blk, ch;
  1616. AC3EncodeContext *s = avctx->priv_data;
  1617. for (ch = 0; ch < s->channels; ch++)
  1618. av_freep(&s->planar_samples[ch]);
  1619. av_freep(&s->planar_samples);
  1620. av_freep(&s->bap_buffer);
  1621. av_freep(&s->bap1_buffer);
  1622. av_freep(&s->mdct_coef_buffer);
  1623. av_freep(&s->fixed_coef_buffer);
  1624. av_freep(&s->exp_buffer);
  1625. av_freep(&s->grouped_exp_buffer);
  1626. av_freep(&s->psd_buffer);
  1627. av_freep(&s->band_psd_buffer);
  1628. av_freep(&s->mask_buffer);
  1629. av_freep(&s->qmant_buffer);
  1630. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1631. AC3Block *block = &s->blocks[blk];
  1632. av_freep(&block->bap);
  1633. av_freep(&block->mdct_coef);
  1634. av_freep(&block->fixed_coef);
  1635. av_freep(&block->exp);
  1636. av_freep(&block->grouped_exp);
  1637. av_freep(&block->psd);
  1638. av_freep(&block->band_psd);
  1639. av_freep(&block->mask);
  1640. av_freep(&block->qmant);
  1641. }
  1642. mdct_end(&s->mdct);
  1643. av_freep(&avctx->coded_frame);
  1644. return 0;
  1645. }
  1646. /**
  1647. * Set channel information during initialization.
  1648. */
  1649. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1650. int64_t *channel_layout)
  1651. {
  1652. int ch_layout;
  1653. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1654. return AVERROR(EINVAL);
  1655. if ((uint64_t)*channel_layout > 0x7FF)
  1656. return AVERROR(EINVAL);
  1657. ch_layout = *channel_layout;
  1658. if (!ch_layout)
  1659. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1660. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1661. s->channels = channels;
  1662. s->fbw_channels = channels - s->lfe_on;
  1663. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1664. if (s->lfe_on)
  1665. ch_layout -= AV_CH_LOW_FREQUENCY;
  1666. switch (ch_layout) {
  1667. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1668. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1669. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1670. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1671. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1672. case AV_CH_LAYOUT_QUAD:
  1673. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1674. case AV_CH_LAYOUT_5POINT0:
  1675. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1676. default:
  1677. return AVERROR(EINVAL);
  1678. }
  1679. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1680. s->has_surround = s->channel_mode & 0x04;
  1681. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1682. *channel_layout = ch_layout;
  1683. if (s->lfe_on)
  1684. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1685. return 0;
  1686. }
  1687. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1688. {
  1689. int i, ret;
  1690. /* validate channel layout */
  1691. if (!avctx->channel_layout) {
  1692. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1693. "encoder will guess the layout, but it "
  1694. "might be incorrect.\n");
  1695. }
  1696. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1697. if (ret) {
  1698. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1699. return ret;
  1700. }
  1701. /* validate sample rate */
  1702. for (i = 0; i < 9; i++) {
  1703. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1704. break;
  1705. }
  1706. if (i == 9) {
  1707. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1708. return AVERROR(EINVAL);
  1709. }
  1710. s->sample_rate = avctx->sample_rate;
  1711. s->bit_alloc.sr_shift = i % 3;
  1712. s->bit_alloc.sr_code = i / 3;
  1713. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1714. /* validate bit rate */
  1715. for (i = 0; i < 19; i++) {
  1716. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1717. break;
  1718. }
  1719. if (i == 19) {
  1720. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1721. return AVERROR(EINVAL);
  1722. }
  1723. s->bit_rate = avctx->bit_rate;
  1724. s->frame_size_code = i << 1;
  1725. /* validate cutoff */
  1726. if (avctx->cutoff < 0) {
  1727. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1728. return AVERROR(EINVAL);
  1729. }
  1730. s->cutoff = avctx->cutoff;
  1731. if (s->cutoff > (s->sample_rate >> 1))
  1732. s->cutoff = s->sample_rate >> 1;
  1733. /* validate audio service type / channels combination */
  1734. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1735. avctx->channels == 1) ||
  1736. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1737. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1738. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1739. && avctx->channels > 1)) {
  1740. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1741. "specified number of channels\n");
  1742. return AVERROR(EINVAL);
  1743. }
  1744. ret = validate_metadata(avctx);
  1745. if (ret)
  1746. return ret;
  1747. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  1748. (s->channel_mode == AC3_CHMODE_STEREO);
  1749. return 0;
  1750. }
  1751. /**
  1752. * Set bandwidth for all channels.
  1753. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1754. * default value will be used.
  1755. */
  1756. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1757. {
  1758. int ch;
  1759. if (s->cutoff) {
  1760. /* calculate bandwidth based on user-specified cutoff frequency */
  1761. int fbw_coeffs;
  1762. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1763. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1764. } else {
  1765. /* use default bandwidth setting */
  1766. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  1767. }
  1768. /* set number of coefficients for each channel */
  1769. for (ch = 0; ch < s->fbw_channels; ch++) {
  1770. s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
  1771. }
  1772. if (s->lfe_on)
  1773. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1774. }
  1775. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1776. {
  1777. int blk, ch;
  1778. AC3EncodeContext *s = avctx->priv_data;
  1779. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1780. alloc_fail);
  1781. for (ch = 0; ch < s->channels; ch++) {
  1782. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1783. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1784. alloc_fail);
  1785. }
  1786. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1787. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1788. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1789. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1790. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1791. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1792. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1793. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1794. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1795. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1796. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1797. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1798. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1799. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1800. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1801. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1802. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1803. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1804. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1805. AC3Block *block = &s->blocks[blk];
  1806. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1807. alloc_fail);
  1808. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1809. alloc_fail);
  1810. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1811. alloc_fail);
  1812. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1813. alloc_fail);
  1814. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1815. alloc_fail);
  1816. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1817. alloc_fail);
  1818. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1819. alloc_fail);
  1820. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1821. alloc_fail);
  1822. for (ch = 0; ch < s->channels; ch++) {
  1823. /* arrangement: block, channel, coeff */
  1824. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1825. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1826. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1827. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1828. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1829. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1830. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1831. /* arrangement: channel, block, coeff */
  1832. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1833. }
  1834. }
  1835. if (CONFIG_AC3ENC_FLOAT) {
  1836. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1837. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1838. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1839. AC3Block *block = &s->blocks[blk];
  1840. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1841. sizeof(*block->fixed_coef), alloc_fail);
  1842. for (ch = 0; ch < s->channels; ch++)
  1843. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1844. }
  1845. } else {
  1846. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1847. AC3Block *block = &s->blocks[blk];
  1848. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1849. sizeof(*block->fixed_coef), alloc_fail);
  1850. for (ch = 0; ch < s->channels; ch++)
  1851. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1852. }
  1853. }
  1854. return 0;
  1855. alloc_fail:
  1856. return AVERROR(ENOMEM);
  1857. }
  1858. /**
  1859. * Initialize the encoder.
  1860. */
  1861. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1862. {
  1863. AC3EncodeContext *s = avctx->priv_data;
  1864. int ret, frame_size_58;
  1865. avctx->frame_size = AC3_FRAME_SIZE;
  1866. ff_ac3_common_init();
  1867. ret = validate_options(avctx, s);
  1868. if (ret)
  1869. return ret;
  1870. s->bitstream_mode = avctx->audio_service_type;
  1871. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  1872. s->bitstream_mode = 0x7;
  1873. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1874. s->bits_written = 0;
  1875. s->samples_written = 0;
  1876. s->frame_size = s->frame_size_min;
  1877. /* calculate crc_inv for both possible frame sizes */
  1878. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1879. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1880. if (s->bit_alloc.sr_code == 1) {
  1881. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1882. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1883. }
  1884. set_bandwidth(s);
  1885. exponent_init(s);
  1886. bit_alloc_init(s);
  1887. ret = mdct_init(avctx, &s->mdct, 9);
  1888. if (ret)
  1889. goto init_fail;
  1890. ret = allocate_buffers(avctx);
  1891. if (ret)
  1892. goto init_fail;
  1893. avctx->coded_frame= avcodec_alloc_frame();
  1894. dsputil_init(&s->dsp, avctx);
  1895. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1896. dprint_options(avctx);
  1897. return 0;
  1898. init_fail:
  1899. ac3_encode_close(avctx);
  1900. return ret;
  1901. }