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.

3013 lines
106KB

  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. CoefType **mdct_coef; ///< MDCT coefficients
  67. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  68. uint8_t **exp; ///< original exponents
  69. uint8_t **grouped_exp; ///< grouped exponents
  70. int16_t **psd; ///< psd per frequency bin
  71. int16_t **band_psd; ///< psd per critical band
  72. int16_t **mask; ///< masking curve
  73. uint16_t **qmant; ///< quantized mantissas
  74. uint8_t **cpl_coord_exp; ///< coupling coord exponents (cplcoexp)
  75. uint8_t **cpl_coord_mant; ///< coupling coord mantissas (cplcomant)
  76. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  77. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  78. int num_rematrixing_bands; ///< number of rematrixing bands
  79. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  80. int new_cpl_strategy; ///< send new coupling strategy
  81. int cpl_in_use; ///< coupling in use for this block (cplinu)
  82. uint8_t channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
  83. int num_cpl_channels; ///< number of channels in coupling
  84. uint8_t new_cpl_coords; ///< send new coupling coordinates (cplcoe)
  85. uint8_t cpl_master_exp[AC3_MAX_CHANNELS]; ///< coupling coord master exponents (mstrcplco)
  86. int new_snr_offsets; ///< send new SNR offsets
  87. int new_cpl_leak; ///< send new coupling leak info
  88. int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
  89. } AC3Block;
  90. /**
  91. * AC-3 encoder private context.
  92. */
  93. typedef struct AC3EncodeContext {
  94. AVClass *av_class; ///< AVClass used for AVOption
  95. AC3EncOptions options; ///< encoding options
  96. PutBitContext pb; ///< bitstream writer context
  97. DSPContext dsp;
  98. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  99. AC3MDCTContext mdct; ///< MDCT context
  100. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  101. int eac3; ///< indicates if this is E-AC-3 vs. AC-3
  102. int bitstream_id; ///< bitstream id (bsid)
  103. int bitstream_mode; ///< bitstream mode (bsmod)
  104. int bit_rate; ///< target bit rate, in bits-per-second
  105. int sample_rate; ///< sampling frequency, in Hz
  106. int frame_size_min; ///< minimum frame size in case rounding is necessary
  107. int frame_size; ///< current frame size in bytes
  108. int frame_size_code; ///< frame size code (frmsizecod)
  109. uint16_t crc_inv[2];
  110. int64_t bits_written; ///< bit count (used to avg. bitrate)
  111. int64_t samples_written; ///< sample count (used to avg. bitrate)
  112. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  113. int channels; ///< total number of channels (nchans)
  114. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  115. int lfe_channel; ///< channel index of the LFE channel
  116. int has_center; ///< indicates if there is a center channel
  117. int has_surround; ///< indicates if there are one or more surround channels
  118. int channel_mode; ///< channel mode (acmod)
  119. const uint8_t *channel_map; ///< channel map used to reorder channels
  120. int center_mix_level; ///< center mix level code
  121. int surround_mix_level; ///< surround mix level code
  122. int ltrt_center_mix_level; ///< Lt/Rt center mix level code
  123. int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
  124. int loro_center_mix_level; ///< Lo/Ro center mix level code
  125. int loro_surround_mix_level; ///< Lo/Ro surround mix level code
  126. int cutoff; ///< user-specified cutoff frequency, in Hz
  127. int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
  128. int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
  129. int cpl_end_freq; ///< coupling channel end frequency bin
  130. int cpl_on; ///< coupling turned on for this frame
  131. int cpl_enabled; ///< coupling enabled for all frames
  132. int num_cpl_subbands; ///< number of coupling subbands (ncplsubnd)
  133. int num_cpl_bands; ///< number of coupling bands (ncplbnd)
  134. uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
  135. int rematrixing_enabled; ///< stereo rematrixing enabled
  136. /* bitrate allocation control */
  137. int slow_gain_code; ///< slow gain code (sgaincod)
  138. int slow_decay_code; ///< slow decay code (sdcycod)
  139. int fast_decay_code; ///< fast decay code (fdcycod)
  140. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  141. int floor_code; ///< floor code (floorcod)
  142. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  143. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  144. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  145. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  146. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  147. int frame_bits; ///< all frame bits except exponents and mantissas
  148. int exponent_bits; ///< number of bits used for exponents
  149. SampleType **planar_samples;
  150. uint8_t *bap_buffer;
  151. uint8_t *bap1_buffer;
  152. CoefType *mdct_coef_buffer;
  153. int32_t *fixed_coef_buffer;
  154. uint8_t *exp_buffer;
  155. uint8_t *grouped_exp_buffer;
  156. int16_t *psd_buffer;
  157. int16_t *band_psd_buffer;
  158. int16_t *mask_buffer;
  159. uint16_t *qmant_buffer;
  160. uint8_t *cpl_coord_exp_buffer;
  161. uint8_t *cpl_coord_mant_buffer;
  162. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  163. uint8_t exp_ref_block[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< reference blocks for EXP_REUSE
  164. uint8_t *ref_bap [AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< bit allocation pointers (bap)
  165. int ref_bap_set; ///< indicates if ref_bap pointers have been set
  166. DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  167. } AC3EncodeContext;
  168. typedef struct AC3Mant {
  169. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  170. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  171. } AC3Mant;
  172. #define CMIXLEV_NUM_OPTIONS 3
  173. static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
  174. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
  175. };
  176. #define SURMIXLEV_NUM_OPTIONS 3
  177. static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
  178. LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  179. };
  180. #define EXTMIXLEV_NUM_OPTIONS 8
  181. static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
  182. LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
  183. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  184. };
  185. #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
  186. #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  187. #define AC3ENC_TYPE_AC3_FIXED 0
  188. #define AC3ENC_TYPE_AC3 1
  189. #define AC3ENC_TYPE_EAC3 2
  190. #if CONFIG_AC3ENC_FLOAT
  191. #define AC3ENC_TYPE AC3ENC_TYPE_AC3
  192. #include "ac3enc_opts_template.c"
  193. static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
  194. ac3_options, LIBAVUTIL_VERSION_INT };
  195. #undef AC3ENC_TYPE
  196. #define AC3ENC_TYPE AC3ENC_TYPE_EAC3
  197. #include "ac3enc_opts_template.c"
  198. static AVClass eac3enc_class = { "E-AC-3 Encoder", av_default_item_name,
  199. eac3_options, LIBAVUTIL_VERSION_INT };
  200. #else
  201. #define AC3ENC_TYPE AC3ENC_TYPE_AC3_FIXED
  202. #include "ac3enc_opts_template.c"
  203. static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
  204. ac3fixed_options, LIBAVUTIL_VERSION_INT };
  205. #endif
  206. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  207. static av_cold void mdct_end(AC3MDCTContext *mdct);
  208. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  209. int nbits);
  210. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  211. const SampleType *window, unsigned int len);
  212. static int normalize_samples(AC3EncodeContext *s);
  213. static void scale_coefficients(AC3EncodeContext *s);
  214. /**
  215. * LUT for number of exponent groups.
  216. * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
  217. */
  218. static uint8_t exponent_group_tab[2][3][256];
  219. /**
  220. * List of supported channel layouts.
  221. */
  222. #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
  223. const int64_t ff_ac3_channel_layouts[] = {
  224. AV_CH_LAYOUT_MONO,
  225. AV_CH_LAYOUT_STEREO,
  226. AV_CH_LAYOUT_2_1,
  227. AV_CH_LAYOUT_SURROUND,
  228. AV_CH_LAYOUT_2_2,
  229. AV_CH_LAYOUT_QUAD,
  230. AV_CH_LAYOUT_4POINT0,
  231. AV_CH_LAYOUT_5POINT0,
  232. AV_CH_LAYOUT_5POINT0_BACK,
  233. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  234. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  235. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  236. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  237. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  238. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  239. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  240. AV_CH_LAYOUT_5POINT1,
  241. AV_CH_LAYOUT_5POINT1_BACK,
  242. 0
  243. };
  244. #endif
  245. /**
  246. * LUT to select the bandwidth code based on the bit rate, sample rate, and
  247. * number of full-bandwidth channels.
  248. * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
  249. */
  250. static const uint8_t ac3_bandwidth_tab[5][3][19] = {
  251. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  252. { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  253. { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  254. { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  255. { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  256. { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  257. { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  258. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
  259. { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
  260. { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
  261. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
  262. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
  263. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
  264. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
  265. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
  266. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
  267. };
  268. /**
  269. * LUT to select the coupling start band based on the bit rate, sample rate, and
  270. * number of full-bandwidth channels. -1 = coupling off
  271. * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
  272. *
  273. * TODO: more testing for optimal parameters.
  274. * multi-channel tests at 44.1kHz and 32kHz.
  275. */
  276. static const int8_t ac3_coupling_start_tab[6][3][19] = {
  277. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  278. // 2/0
  279. { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
  280. { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
  281. { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  282. // 3/0
  283. { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  284. { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  285. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  286. // 2/1 - untested
  287. { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  288. { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  289. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  290. // 3/1
  291. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  292. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  293. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  294. // 2/2 - untested
  295. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  296. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  297. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  298. // 3/2
  299. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
  300. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
  301. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  302. };
  303. /**
  304. * Adjust the frame size to make the average bit rate match the target bit rate.
  305. * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
  306. */
  307. static void adjust_frame_size(AC3EncodeContext *s)
  308. {
  309. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  310. s->bits_written -= s->bit_rate;
  311. s->samples_written -= s->sample_rate;
  312. }
  313. s->frame_size = s->frame_size_min +
  314. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  315. s->bits_written += s->frame_size * 8;
  316. s->samples_written += AC3_FRAME_SIZE;
  317. }
  318. /**
  319. * Deinterleave input samples.
  320. * Channels are reordered from FFmpeg's default order to AC-3 order.
  321. */
  322. static void deinterleave_input_samples(AC3EncodeContext *s,
  323. const SampleType *samples)
  324. {
  325. int ch, i;
  326. /* deinterleave and remap input samples */
  327. for (ch = 0; ch < s->channels; ch++) {
  328. const SampleType *sptr;
  329. int sinc;
  330. /* copy last 256 samples of previous frame to the start of the current frame */
  331. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  332. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  333. /* deinterleave */
  334. sinc = s->channels;
  335. sptr = samples + s->channel_map[ch];
  336. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  337. s->planar_samples[ch][i] = *sptr;
  338. sptr += sinc;
  339. }
  340. }
  341. }
  342. /**
  343. * Apply the MDCT to input samples to generate frequency coefficients.
  344. * This applies the KBD window and normalizes the input to reduce precision
  345. * loss due to fixed-point calculations.
  346. */
  347. static void apply_mdct(AC3EncodeContext *s)
  348. {
  349. int blk, ch;
  350. for (ch = 0; ch < s->channels; ch++) {
  351. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  352. AC3Block *block = &s->blocks[blk];
  353. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  354. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  355. block->coeff_shift[ch+1] = normalize_samples(s);
  356. s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
  357. s->windowed_samples);
  358. }
  359. }
  360. }
  361. static void compute_coupling_strategy(AC3EncodeContext *s)
  362. {
  363. int blk, ch;
  364. int got_cpl_snr;
  365. /* set coupling use flags for each block/channel */
  366. /* TODO: turn coupling on/off and adjust start band based on bit usage */
  367. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  368. AC3Block *block = &s->blocks[blk];
  369. for (ch = 1; ch <= s->fbw_channels; ch++)
  370. block->channel_in_cpl[ch] = s->cpl_on;
  371. }
  372. /* enable coupling for each block if at least 2 channels have coupling
  373. enabled for that block */
  374. got_cpl_snr = 0;
  375. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  376. AC3Block *block = &s->blocks[blk];
  377. block->num_cpl_channels = 0;
  378. for (ch = 1; ch <= s->fbw_channels; ch++)
  379. block->num_cpl_channels += block->channel_in_cpl[ch];
  380. block->cpl_in_use = block->num_cpl_channels > 1;
  381. if (!block->cpl_in_use) {
  382. block->num_cpl_channels = 0;
  383. for (ch = 1; ch <= s->fbw_channels; ch++)
  384. block->channel_in_cpl[ch] = 0;
  385. }
  386. block->new_cpl_strategy = !blk;
  387. if (blk) {
  388. for (ch = 1; ch <= s->fbw_channels; ch++) {
  389. if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
  390. block->new_cpl_strategy = 1;
  391. break;
  392. }
  393. }
  394. }
  395. block->new_cpl_leak = block->new_cpl_strategy;
  396. if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
  397. block->new_snr_offsets = 1;
  398. if (block->cpl_in_use)
  399. got_cpl_snr = 1;
  400. } else {
  401. block->new_snr_offsets = 0;
  402. }
  403. }
  404. /* set bandwidth for each channel */
  405. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  406. AC3Block *block = &s->blocks[blk];
  407. for (ch = 1; ch <= s->fbw_channels; ch++) {
  408. if (block->channel_in_cpl[ch])
  409. block->end_freq[ch] = s->start_freq[CPL_CH];
  410. else
  411. block->end_freq[ch] = s->bandwidth_code * 3 + 73;
  412. }
  413. }
  414. }
  415. /**
  416. * Calculate a single coupling coordinate.
  417. */
  418. static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
  419. {
  420. float coord = 0.125;
  421. if (energy_cpl > 0)
  422. coord *= sqrtf(energy_ch / energy_cpl);
  423. return coord;
  424. }
  425. /**
  426. * Calculate coupling channel and coupling coordinates.
  427. * TODO: Currently this is only used for the floating-point encoder. I was
  428. * able to make it work for the fixed-point encoder, but quality was
  429. * generally lower in most cases than not using coupling. If a more
  430. * adaptive coupling strategy were to be implemented it might be useful
  431. * at that time to use coupling for the fixed-point encoder as well.
  432. */
  433. static void apply_channel_coupling(AC3EncodeContext *s)
  434. {
  435. #if CONFIG_AC3ENC_FLOAT
  436. LOCAL_ALIGNED_16(float, cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
  437. LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
  438. int blk, ch, bnd, i, j;
  439. CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
  440. int num_cpl_coefs = s->num_cpl_subbands * 12;
  441. memset(cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
  442. memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*fixed_cpl_coords));
  443. /* calculate coupling channel from fbw channels */
  444. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  445. AC3Block *block = &s->blocks[blk];
  446. CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
  447. if (!block->cpl_in_use)
  448. continue;
  449. memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
  450. for (ch = 1; ch <= s->fbw_channels; ch++) {
  451. CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
  452. if (!block->channel_in_cpl[ch])
  453. continue;
  454. for (i = 0; i < num_cpl_coefs; i++)
  455. cpl_coef[i] += ch_coef[i];
  456. }
  457. /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
  458. will always be a multiple of 12, so we need to subtract 1 from
  459. the start and add 4 to the length when using optimized
  460. functions which require 16-byte alignment. */
  461. /* coefficients must be clipped to +/- 1.0 in order to be encoded */
  462. s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
  463. /* scale coupling coefficients from float to 24-bit fixed-point */
  464. s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
  465. cpl_coef-1, num_cpl_coefs+4);
  466. }
  467. /* calculate energy in each band in coupling channel and each fbw channel */
  468. /* TODO: possibly use SIMD to speed up energy calculation */
  469. bnd = 0;
  470. i = s->start_freq[CPL_CH];
  471. while (i < s->cpl_end_freq) {
  472. int band_size = s->cpl_band_sizes[bnd];
  473. for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
  474. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  475. AC3Block *block = &s->blocks[blk];
  476. if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
  477. continue;
  478. for (j = 0; j < band_size; j++) {
  479. CoefType v = block->mdct_coef[ch][i+j];
  480. MAC_COEF(energy[blk][ch][bnd], v, v);
  481. }
  482. }
  483. }
  484. i += band_size;
  485. bnd++;
  486. }
  487. /* determine which blocks to send new coupling coordinates for */
  488. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  489. AC3Block *block = &s->blocks[blk];
  490. AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
  491. int new_coords = 0;
  492. CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
  493. if (block->cpl_in_use) {
  494. /* calculate coupling coordinates for all blocks and calculate the
  495. average difference between coordinates in successive blocks */
  496. for (ch = 1; ch <= s->fbw_channels; ch++) {
  497. if (!block->channel_in_cpl[ch])
  498. continue;
  499. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  500. cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
  501. energy[blk][CPL_CH][bnd]);
  502. if (blk > 0 && block0->cpl_in_use &&
  503. block0->channel_in_cpl[ch]) {
  504. coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
  505. cpl_coords[blk ][ch][bnd]);
  506. }
  507. }
  508. coord_diff[ch] /= s->num_cpl_bands;
  509. }
  510. /* send new coordinates if this is the first block, if previous
  511. * block did not use coupling but this block does, the channels
  512. * using coupling has changed from the previous block, or the
  513. * coordinate difference from the last block for any channel is
  514. * greater than a threshold value. */
  515. if (blk == 0) {
  516. new_coords = 1;
  517. } else if (!block0->cpl_in_use) {
  518. new_coords = 1;
  519. } else {
  520. for (ch = 1; ch <= s->fbw_channels; ch++) {
  521. if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
  522. new_coords = 1;
  523. break;
  524. }
  525. }
  526. if (!new_coords) {
  527. for (ch = 1; ch <= s->fbw_channels; ch++) {
  528. if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
  529. new_coords = 1;
  530. break;
  531. }
  532. }
  533. }
  534. }
  535. }
  536. block->new_cpl_coords = new_coords;
  537. }
  538. /* calculate final coupling coordinates, taking into account reusing of
  539. coordinates in successive blocks */
  540. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  541. blk = 0;
  542. while (blk < AC3_MAX_BLOCKS) {
  543. int blk1;
  544. CoefSumType energy_cpl;
  545. AC3Block *block = &s->blocks[blk];
  546. if (!block->cpl_in_use) {
  547. blk++;
  548. continue;
  549. }
  550. energy_cpl = energy[blk][CPL_CH][bnd];
  551. blk1 = blk+1;
  552. while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
  553. if (s->blocks[blk1].cpl_in_use)
  554. energy_cpl += energy[blk1][CPL_CH][bnd];
  555. blk1++;
  556. }
  557. for (ch = 1; ch <= s->fbw_channels; ch++) {
  558. CoefType energy_ch;
  559. if (!block->channel_in_cpl[ch])
  560. continue;
  561. energy_ch = energy[blk][ch][bnd];
  562. blk1 = blk+1;
  563. while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
  564. if (s->blocks[blk1].cpl_in_use)
  565. energy_ch += energy[blk1][ch][bnd];
  566. blk1++;
  567. }
  568. cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
  569. }
  570. blk = blk1;
  571. }
  572. }
  573. /* calculate exponents/mantissas for coupling coordinates */
  574. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  575. AC3Block *block = &s->blocks[blk];
  576. if (!block->cpl_in_use || !block->new_cpl_coords)
  577. continue;
  578. s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
  579. cpl_coords[blk][1],
  580. s->fbw_channels * 16);
  581. s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
  582. fixed_cpl_coords[blk][1],
  583. s->fbw_channels * 16);
  584. for (ch = 1; ch <= s->fbw_channels; ch++) {
  585. int bnd, min_exp, max_exp, master_exp;
  586. /* determine master exponent */
  587. min_exp = max_exp = block->cpl_coord_exp[ch][0];
  588. for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
  589. int exp = block->cpl_coord_exp[ch][bnd];
  590. min_exp = FFMIN(exp, min_exp);
  591. max_exp = FFMAX(exp, max_exp);
  592. }
  593. master_exp = ((max_exp - 15) + 2) / 3;
  594. master_exp = FFMAX(master_exp, 0);
  595. while (min_exp < master_exp * 3)
  596. master_exp--;
  597. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  598. block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
  599. master_exp * 3, 0, 15);
  600. }
  601. block->cpl_master_exp[ch] = master_exp;
  602. /* quantize mantissas */
  603. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  604. int cpl_exp = block->cpl_coord_exp[ch][bnd];
  605. int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
  606. if (cpl_exp == 15)
  607. cpl_mant >>= 1;
  608. else
  609. cpl_mant -= 16;
  610. block->cpl_coord_mant[ch][bnd] = cpl_mant;
  611. }
  612. }
  613. }
  614. if (s->eac3) {
  615. /* set first cpl coords */
  616. int first_cpl_coords[AC3_MAX_CHANNELS];
  617. for (ch = 1; ch <= s->fbw_channels; ch++)
  618. first_cpl_coords[ch] = 1;
  619. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  620. AC3Block *block = &s->blocks[blk];
  621. for (ch = 1; ch <= s->fbw_channels; ch++) {
  622. if (block->channel_in_cpl[ch]) {
  623. if (first_cpl_coords[ch]) {
  624. block->new_cpl_coords = 2;
  625. first_cpl_coords[ch] = 0;
  626. }
  627. } else {
  628. first_cpl_coords[ch] = 1;
  629. }
  630. }
  631. }
  632. /* set first cpl leak */
  633. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  634. AC3Block *block = &s->blocks[blk];
  635. if (block->cpl_in_use) {
  636. block->new_cpl_leak = 2;
  637. break;
  638. }
  639. }
  640. }
  641. #endif /* CONFIG_AC3ENC_FLOAT */
  642. }
  643. /**
  644. * Determine rematrixing flags for each block and band.
  645. */
  646. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  647. {
  648. int nb_coefs;
  649. int blk, bnd, i;
  650. AC3Block *block, *block0;
  651. if (s->channel_mode != AC3_CHMODE_STEREO)
  652. return;
  653. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  654. block = &s->blocks[blk];
  655. block->new_rematrixing_strategy = !blk;
  656. if (!s->rematrixing_enabled) {
  657. block0 = block;
  658. continue;
  659. }
  660. block->num_rematrixing_bands = 4;
  661. if (block->cpl_in_use) {
  662. block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
  663. block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
  664. if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
  665. block->new_rematrixing_strategy = 1;
  666. }
  667. nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
  668. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
  669. /* calculate calculate sum of squared coeffs for one band in one block */
  670. int start = ff_ac3_rematrix_band_tab[bnd];
  671. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  672. CoefSumType sum[4] = {0,};
  673. for (i = start; i < end; i++) {
  674. CoefType lt = block->mdct_coef[1][i];
  675. CoefType rt = block->mdct_coef[2][i];
  676. CoefType md = lt + rt;
  677. CoefType sd = lt - rt;
  678. MAC_COEF(sum[0], lt, lt);
  679. MAC_COEF(sum[1], rt, rt);
  680. MAC_COEF(sum[2], md, md);
  681. MAC_COEF(sum[3], sd, sd);
  682. }
  683. /* compare sums to determine if rematrixing will be used for this band */
  684. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  685. block->rematrixing_flags[bnd] = 1;
  686. else
  687. block->rematrixing_flags[bnd] = 0;
  688. /* determine if new rematrixing flags will be sent */
  689. if (blk &&
  690. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  691. block->new_rematrixing_strategy = 1;
  692. }
  693. }
  694. block0 = block;
  695. }
  696. }
  697. /**
  698. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  699. */
  700. static void apply_rematrixing(AC3EncodeContext *s)
  701. {
  702. int nb_coefs;
  703. int blk, bnd, i;
  704. int start, end;
  705. uint8_t *flags;
  706. if (!s->rematrixing_enabled)
  707. return;
  708. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  709. AC3Block *block = &s->blocks[blk];
  710. if (block->new_rematrixing_strategy)
  711. flags = block->rematrixing_flags;
  712. nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
  713. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
  714. if (flags[bnd]) {
  715. start = ff_ac3_rematrix_band_tab[bnd];
  716. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  717. for (i = start; i < end; i++) {
  718. int32_t lt = block->fixed_coef[1][i];
  719. int32_t rt = block->fixed_coef[2][i];
  720. block->fixed_coef[1][i] = (lt + rt) >> 1;
  721. block->fixed_coef[2][i] = (lt - rt) >> 1;
  722. }
  723. }
  724. }
  725. }
  726. }
  727. /**
  728. * Initialize exponent tables.
  729. */
  730. static av_cold void exponent_init(AC3EncodeContext *s)
  731. {
  732. int expstr, i, grpsize;
  733. for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
  734. grpsize = 3 << expstr;
  735. for (i = 12; i < 256; i++) {
  736. exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
  737. exponent_group_tab[1][expstr][i] = (i ) / grpsize;
  738. }
  739. }
  740. /* LFE */
  741. exponent_group_tab[0][0][7] = 2;
  742. }
  743. /**
  744. * Extract exponents from the MDCT coefficients.
  745. * This takes into account the normalization that was done to the input samples
  746. * by adjusting the exponents by the exponent shift values.
  747. */
  748. static void extract_exponents(AC3EncodeContext *s)
  749. {
  750. int blk, ch;
  751. for (ch = !s->cpl_on; ch <= s->channels; ch++) {
  752. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  753. AC3Block *block = &s->blocks[blk];
  754. s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
  755. AC3_MAX_COEFS);
  756. }
  757. }
  758. }
  759. /**
  760. * Exponent Difference Threshold.
  761. * New exponents are sent if their SAD exceed this number.
  762. */
  763. #define EXP_DIFF_THRESHOLD 500
  764. /**
  765. * Calculate exponent strategies for all channels.
  766. * Array arrangement is reversed to simplify the per-channel calculation.
  767. */
  768. static void compute_exp_strategy(AC3EncodeContext *s)
  769. {
  770. int ch, blk, blk1;
  771. for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
  772. uint8_t *exp_strategy = s->exp_strategy[ch];
  773. uint8_t *exp = s->blocks[0].exp[ch];
  774. int exp_diff;
  775. /* estimate if the exponent variation & decide if they should be
  776. reused in the next frame */
  777. exp_strategy[0] = EXP_NEW;
  778. exp += AC3_MAX_COEFS;
  779. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
  780. if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
  781. (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
  782. exp_strategy[blk] = EXP_NEW;
  783. continue;
  784. }
  785. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  786. exp_strategy[blk] = EXP_REUSE;
  787. if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
  788. exp_strategy[blk] = EXP_NEW;
  789. else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
  790. exp_strategy[blk] = EXP_NEW;
  791. }
  792. /* now select the encoding strategy type : if exponents are often
  793. recoded, we use a coarse encoding */
  794. blk = 0;
  795. while (blk < AC3_MAX_BLOCKS) {
  796. blk1 = blk + 1;
  797. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  798. blk1++;
  799. switch (blk1 - blk) {
  800. case 1: exp_strategy[blk] = EXP_D45; break;
  801. case 2:
  802. case 3: exp_strategy[blk] = EXP_D25; break;
  803. default: exp_strategy[blk] = EXP_D15; break;
  804. }
  805. blk = blk1;
  806. }
  807. }
  808. if (s->lfe_on) {
  809. ch = s->lfe_channel;
  810. s->exp_strategy[ch][0] = EXP_D15;
  811. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  812. s->exp_strategy[ch][blk] = EXP_REUSE;
  813. }
  814. }
  815. /**
  816. * Update the exponents so that they are the ones the decoder will decode.
  817. */
  818. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
  819. int cpl)
  820. {
  821. int nb_groups, i, k;
  822. nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
  823. /* for each group, compute the minimum exponent */
  824. switch(exp_strategy) {
  825. case EXP_D25:
  826. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  827. uint8_t exp_min = exp[k];
  828. if (exp[k+1] < exp_min)
  829. exp_min = exp[k+1];
  830. exp[i-cpl] = exp_min;
  831. k += 2;
  832. }
  833. break;
  834. case EXP_D45:
  835. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  836. uint8_t exp_min = exp[k];
  837. if (exp[k+1] < exp_min)
  838. exp_min = exp[k+1];
  839. if (exp[k+2] < exp_min)
  840. exp_min = exp[k+2];
  841. if (exp[k+3] < exp_min)
  842. exp_min = exp[k+3];
  843. exp[i-cpl] = exp_min;
  844. k += 4;
  845. }
  846. break;
  847. }
  848. /* constraint for DC exponent */
  849. if (!cpl && exp[0] > 15)
  850. exp[0] = 15;
  851. /* decrease the delta between each groups to within 2 so that they can be
  852. differentially encoded */
  853. for (i = 1; i <= nb_groups; i++)
  854. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  855. i--;
  856. while (--i >= 0)
  857. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  858. if (cpl)
  859. exp[-1] = exp[0] & ~1;
  860. /* now we have the exponent values the decoder will see */
  861. switch (exp_strategy) {
  862. case EXP_D25:
  863. for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
  864. uint8_t exp1 = exp[i-cpl];
  865. exp[k--] = exp1;
  866. exp[k--] = exp1;
  867. }
  868. break;
  869. case EXP_D45:
  870. for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
  871. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
  872. k -= 4;
  873. }
  874. break;
  875. }
  876. }
  877. /**
  878. * Encode exponents from original extracted form to what the decoder will see.
  879. * This copies and groups exponents based on exponent strategy and reduces
  880. * deltas between adjacent exponent groups so that they can be differentially
  881. * encoded.
  882. */
  883. static void encode_exponents(AC3EncodeContext *s)
  884. {
  885. int blk, blk1, ch, cpl;
  886. uint8_t *exp, *exp_strategy;
  887. int nb_coefs, num_reuse_blocks;
  888. for (ch = !s->cpl_on; ch <= s->channels; ch++) {
  889. exp = s->blocks[0].exp[ch] + s->start_freq[ch];
  890. exp_strategy = s->exp_strategy[ch];
  891. cpl = (ch == CPL_CH);
  892. blk = 0;
  893. while (blk < AC3_MAX_BLOCKS) {
  894. AC3Block *block = &s->blocks[blk];
  895. if (cpl && !block->cpl_in_use) {
  896. exp += AC3_MAX_COEFS;
  897. blk++;
  898. continue;
  899. }
  900. nb_coefs = block->end_freq[ch] - s->start_freq[ch];
  901. blk1 = blk + 1;
  902. /* count the number of EXP_REUSE blocks after the current block
  903. and set exponent reference block numbers */
  904. s->exp_ref_block[ch][blk] = blk;
  905. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  906. s->exp_ref_block[ch][blk1] = blk;
  907. blk1++;
  908. }
  909. num_reuse_blocks = blk1 - blk - 1;
  910. /* for the EXP_REUSE case we select the min of the exponents */
  911. s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
  912. AC3_MAX_COEFS);
  913. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
  914. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  915. blk = blk1;
  916. }
  917. }
  918. /* reference block numbers have been changed, so reset ref_bap_set */
  919. s->ref_bap_set = 0;
  920. }
  921. /**
  922. * Group exponents.
  923. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  924. * varies depending on exponent strategy and bandwidth.
  925. */
  926. static void group_exponents(AC3EncodeContext *s)
  927. {
  928. int blk, ch, i, cpl;
  929. int group_size, nb_groups, bit_count;
  930. uint8_t *p;
  931. int delta0, delta1, delta2;
  932. int exp0, exp1;
  933. bit_count = 0;
  934. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  935. AC3Block *block = &s->blocks[blk];
  936. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  937. int exp_strategy = s->exp_strategy[ch][blk];
  938. if (exp_strategy == EXP_REUSE)
  939. continue;
  940. cpl = (ch == CPL_CH);
  941. group_size = exp_strategy + (exp_strategy == EXP_D45);
  942. nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
  943. bit_count += 4 + (nb_groups * 7);
  944. p = block->exp[ch] + s->start_freq[ch] - cpl;
  945. /* DC exponent */
  946. exp1 = *p++;
  947. block->grouped_exp[ch][0] = exp1;
  948. /* remaining exponents are delta encoded */
  949. for (i = 1; i <= nb_groups; i++) {
  950. /* merge three delta in one code */
  951. exp0 = exp1;
  952. exp1 = p[0];
  953. p += group_size;
  954. delta0 = exp1 - exp0 + 2;
  955. av_assert2(delta0 >= 0 && delta0 <= 4);
  956. exp0 = exp1;
  957. exp1 = p[0];
  958. p += group_size;
  959. delta1 = exp1 - exp0 + 2;
  960. av_assert2(delta1 >= 0 && delta1 <= 4);
  961. exp0 = exp1;
  962. exp1 = p[0];
  963. p += group_size;
  964. delta2 = exp1 - exp0 + 2;
  965. av_assert2(delta2 >= 0 && delta2 <= 4);
  966. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  967. }
  968. }
  969. }
  970. s->exponent_bits = bit_count;
  971. }
  972. /**
  973. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  974. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  975. * and encode final exponents.
  976. */
  977. static void process_exponents(AC3EncodeContext *s)
  978. {
  979. extract_exponents(s);
  980. compute_exp_strategy(s);
  981. encode_exponents(s);
  982. group_exponents(s);
  983. emms_c();
  984. }
  985. /**
  986. * Count frame bits that are based solely on fixed parameters.
  987. * This only has to be run once when the encoder is initialized.
  988. */
  989. static void count_frame_bits_fixed(AC3EncodeContext *s)
  990. {
  991. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  992. int blk;
  993. int frame_bits;
  994. /* assumptions:
  995. * no dynamic range codes
  996. * bit allocation parameters do not change between blocks
  997. * no delta bit allocation
  998. * no skipped data
  999. * no auxilliary data
  1000. * no E-AC-3 metadata
  1001. */
  1002. /* header */
  1003. frame_bits = 16; /* sync info */
  1004. if (s->eac3) {
  1005. /* bitstream info header */
  1006. frame_bits += 35;
  1007. frame_bits += 1 + 1 + 1;
  1008. /* audio frame header */
  1009. frame_bits += 2;
  1010. frame_bits += 10;
  1011. /* exponent strategy */
  1012. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1013. frame_bits += 2 * s->fbw_channels + s->lfe_on;
  1014. /* converter exponent strategy */
  1015. frame_bits += s->fbw_channels * 5;
  1016. /* snr offsets */
  1017. frame_bits += 10;
  1018. /* block start info */
  1019. frame_bits++;
  1020. } else {
  1021. frame_bits += 49;
  1022. frame_bits += frame_bits_inc[s->channel_mode];
  1023. }
  1024. /* audio blocks */
  1025. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1026. if (!s->eac3) {
  1027. /* block switch flags */
  1028. frame_bits += s->fbw_channels;
  1029. /* dither flags */
  1030. frame_bits += s->fbw_channels;
  1031. }
  1032. /* dynamic range */
  1033. frame_bits++;
  1034. /* spectral extension */
  1035. if (s->eac3)
  1036. frame_bits++;
  1037. if (!s->eac3) {
  1038. /* exponent strategy */
  1039. frame_bits += 2 * s->fbw_channels;
  1040. if (s->lfe_on)
  1041. frame_bits++;
  1042. /* bit allocation params */
  1043. frame_bits++;
  1044. if (!blk)
  1045. frame_bits += 2 + 2 + 2 + 2 + 3;
  1046. }
  1047. /* converter snr offset */
  1048. if (s->eac3)
  1049. frame_bits++;
  1050. if (!s->eac3) {
  1051. /* delta bit allocation */
  1052. frame_bits++;
  1053. /* skipped data */
  1054. frame_bits++;
  1055. }
  1056. }
  1057. /* auxiliary data */
  1058. frame_bits++;
  1059. /* CRC */
  1060. frame_bits += 1 + 16;
  1061. s->frame_bits_fixed = frame_bits;
  1062. }
  1063. /**
  1064. * Initialize bit allocation.
  1065. * Set default parameter codes and calculate parameter values.
  1066. */
  1067. static void bit_alloc_init(AC3EncodeContext *s)
  1068. {
  1069. int ch;
  1070. /* init default parameters */
  1071. s->slow_decay_code = 2;
  1072. s->fast_decay_code = 1;
  1073. s->slow_gain_code = 1;
  1074. s->db_per_bit_code = s->eac3 ? 2 : 3;
  1075. s->floor_code = 7;
  1076. for (ch = 0; ch <= s->channels; ch++)
  1077. s->fast_gain_code[ch] = 4;
  1078. /* initial snr offset */
  1079. s->coarse_snr_offset = 40;
  1080. /* compute real values */
  1081. /* currently none of these values change during encoding, so we can just
  1082. set them once at initialization */
  1083. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  1084. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  1085. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  1086. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  1087. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  1088. s->bit_alloc.cpl_fast_leak = 0;
  1089. s->bit_alloc.cpl_slow_leak = 0;
  1090. count_frame_bits_fixed(s);
  1091. }
  1092. /**
  1093. * Count the bits used to encode the frame, minus exponents and mantissas.
  1094. * Bits based on fixed parameters have already been counted, so now we just
  1095. * have to add the bits based on parameters that change during encoding.
  1096. */
  1097. static void count_frame_bits(AC3EncodeContext *s)
  1098. {
  1099. AC3EncOptions *opt = &s->options;
  1100. int blk, ch;
  1101. int frame_bits = 0;
  1102. /* header */
  1103. if (s->eac3) {
  1104. /* coupling */
  1105. if (s->channel_mode > AC3_CHMODE_MONO) {
  1106. frame_bits++;
  1107. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1108. AC3Block *block = &s->blocks[blk];
  1109. frame_bits++;
  1110. if (block->new_cpl_strategy)
  1111. frame_bits++;
  1112. }
  1113. }
  1114. /* coupling exponent strategy */
  1115. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1116. frame_bits += 2 * s->blocks[blk].cpl_in_use;
  1117. } else {
  1118. if (opt->audio_production_info)
  1119. frame_bits += 7;
  1120. if (s->bitstream_id == 6) {
  1121. if (opt->extended_bsi_1)
  1122. frame_bits += 14;
  1123. if (opt->extended_bsi_2)
  1124. frame_bits += 14;
  1125. }
  1126. }
  1127. /* audio blocks */
  1128. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1129. AC3Block *block = &s->blocks[blk];
  1130. /* coupling strategy */
  1131. if (!s->eac3)
  1132. frame_bits++;
  1133. if (block->new_cpl_strategy) {
  1134. if (!s->eac3)
  1135. frame_bits++;
  1136. if (block->cpl_in_use) {
  1137. if (s->eac3)
  1138. frame_bits++;
  1139. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
  1140. frame_bits += s->fbw_channels;
  1141. if (s->channel_mode == AC3_CHMODE_STEREO)
  1142. frame_bits++;
  1143. frame_bits += 4 + 4;
  1144. if (s->eac3)
  1145. frame_bits++;
  1146. else
  1147. frame_bits += s->num_cpl_subbands - 1;
  1148. }
  1149. }
  1150. /* coupling coordinates */
  1151. if (block->cpl_in_use) {
  1152. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1153. if (block->channel_in_cpl[ch]) {
  1154. if (!s->eac3 || block->new_cpl_coords != 2)
  1155. frame_bits++;
  1156. if (block->new_cpl_coords) {
  1157. frame_bits += 2;
  1158. frame_bits += (4 + 4) * s->num_cpl_bands;
  1159. }
  1160. }
  1161. }
  1162. }
  1163. /* stereo rematrixing */
  1164. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1165. if (!s->eac3 || blk > 0)
  1166. frame_bits++;
  1167. if (s->blocks[blk].new_rematrixing_strategy)
  1168. frame_bits += block->num_rematrixing_bands;
  1169. }
  1170. /* bandwidth codes & gain range */
  1171. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1172. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1173. if (!block->channel_in_cpl[ch])
  1174. frame_bits += 6;
  1175. frame_bits += 2;
  1176. }
  1177. }
  1178. /* coupling exponent strategy */
  1179. if (!s->eac3 && block->cpl_in_use)
  1180. frame_bits += 2;
  1181. /* snr offsets and fast gain codes */
  1182. if (!s->eac3) {
  1183. frame_bits++;
  1184. if (block->new_snr_offsets)
  1185. frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
  1186. }
  1187. /* coupling leak info */
  1188. if (block->cpl_in_use) {
  1189. if (!s->eac3 || block->new_cpl_leak != 2)
  1190. frame_bits++;
  1191. if (block->new_cpl_leak)
  1192. frame_bits += 3 + 3;
  1193. }
  1194. }
  1195. s->frame_bits = s->frame_bits_fixed + frame_bits;
  1196. }
  1197. /**
  1198. * Calculate masking curve based on the final exponents.
  1199. * Also calculate the power spectral densities to use in future calculations.
  1200. */
  1201. static void bit_alloc_masking(AC3EncodeContext *s)
  1202. {
  1203. int blk, ch;
  1204. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1205. AC3Block *block = &s->blocks[blk];
  1206. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1207. /* We only need psd and mask for calculating bap.
  1208. Since we currently do not calculate bap when exponent
  1209. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  1210. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1211. ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
  1212. block->end_freq[ch], block->psd[ch],
  1213. block->band_psd[ch]);
  1214. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  1215. s->start_freq[ch], block->end_freq[ch],
  1216. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  1217. ch == s->lfe_channel,
  1218. DBA_NONE, 0, NULL, NULL, NULL,
  1219. block->mask[ch]);
  1220. }
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Ensure that bap for each block and channel point to the current bap_buffer.
  1226. * They may have been switched during the bit allocation search.
  1227. */
  1228. static void reset_block_bap(AC3EncodeContext *s)
  1229. {
  1230. int blk, ch;
  1231. uint8_t *ref_bap;
  1232. if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
  1233. return;
  1234. ref_bap = s->bap_buffer;
  1235. for (ch = 0; ch <= s->channels; ch++) {
  1236. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1237. s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
  1238. ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
  1239. }
  1240. s->ref_bap_set = 1;
  1241. }
  1242. /**
  1243. * Initialize mantissa counts.
  1244. * These are set so that they are padded to the next whole group size when bits
  1245. * are counted in compute_mantissa_size.
  1246. */
  1247. static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
  1248. {
  1249. int blk;
  1250. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1251. memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
  1252. mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
  1253. mant_cnt[blk][4] = 1;
  1254. }
  1255. }
  1256. /**
  1257. * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
  1258. * range.
  1259. */
  1260. static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
  1261. uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
  1262. int start, int end)
  1263. {
  1264. int blk;
  1265. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1266. AC3Block *block = &s->blocks[blk];
  1267. if (ch == CPL_CH && !block->cpl_in_use)
  1268. continue;
  1269. s->ac3dsp.update_bap_counts(mant_cnt[blk],
  1270. s->ref_bap[ch][blk] + start,
  1271. FFMIN(end, block->end_freq[ch]) - start);
  1272. }
  1273. }
  1274. /**
  1275. * Count the number of mantissa bits in the frame based on the bap values.
  1276. */
  1277. static int count_mantissa_bits(AC3EncodeContext *s)
  1278. {
  1279. int ch, max_end_freq;
  1280. LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
  1281. count_mantissa_bits_init(mant_cnt);
  1282. max_end_freq = s->bandwidth_code * 3 + 73;
  1283. for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
  1284. count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
  1285. max_end_freq);
  1286. return s->ac3dsp.compute_mantissa_size(mant_cnt);
  1287. }
  1288. /**
  1289. * Run the bit allocation with a given SNR offset.
  1290. * This calculates the bit allocation pointers that will be used to determine
  1291. * the quantization of each mantissa.
  1292. * @return the number of bits needed for mantissas if the given SNR offset is
  1293. * is used.
  1294. */
  1295. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  1296. {
  1297. int blk, ch;
  1298. snr_offset = (snr_offset - 240) << 2;
  1299. reset_block_bap(s);
  1300. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1301. AC3Block *block = &s->blocks[blk];
  1302. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1303. /* Currently the only bit allocation parameters which vary across
  1304. blocks within a frame are the exponent values. We can take
  1305. advantage of that by reusing the bit allocation pointers
  1306. whenever we reuse exponents. */
  1307. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1308. s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
  1309. s->start_freq[ch], block->end_freq[ch],
  1310. snr_offset, s->bit_alloc.floor,
  1311. ff_ac3_bap_tab, s->ref_bap[ch][blk]);
  1312. }
  1313. }
  1314. }
  1315. return count_mantissa_bits(s);
  1316. }
  1317. /**
  1318. * Constant bitrate bit allocation search.
  1319. * Find the largest SNR offset that will allow data to fit in the frame.
  1320. */
  1321. static int cbr_bit_allocation(AC3EncodeContext *s)
  1322. {
  1323. int ch;
  1324. int bits_left;
  1325. int snr_offset, snr_incr;
  1326. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  1327. if (bits_left < 0)
  1328. return AVERROR(EINVAL);
  1329. snr_offset = s->coarse_snr_offset << 4;
  1330. /* if previous frame SNR offset was 1023, check if current frame can also
  1331. use SNR offset of 1023. if so, skip the search. */
  1332. if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
  1333. if (bit_alloc(s, 1023) <= bits_left)
  1334. return 0;
  1335. }
  1336. while (snr_offset >= 0 &&
  1337. bit_alloc(s, snr_offset) > bits_left) {
  1338. snr_offset -= 64;
  1339. }
  1340. if (snr_offset < 0)
  1341. return AVERROR(EINVAL);
  1342. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1343. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  1344. while (snr_offset + snr_incr <= 1023 &&
  1345. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  1346. snr_offset += snr_incr;
  1347. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1348. }
  1349. }
  1350. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1351. reset_block_bap(s);
  1352. s->coarse_snr_offset = snr_offset >> 4;
  1353. for (ch = !s->cpl_on; ch <= s->channels; ch++)
  1354. s->fine_snr_offset[ch] = snr_offset & 0xF;
  1355. return 0;
  1356. }
  1357. /**
  1358. * Downgrade exponent strategies to reduce the bits used by the exponents.
  1359. * This is a fallback for when bit allocation fails with the normal exponent
  1360. * strategies. Each time this function is run it only downgrades the
  1361. * strategy in 1 channel of 1 block.
  1362. * @return non-zero if downgrade was unsuccessful
  1363. */
  1364. static int downgrade_exponents(AC3EncodeContext *s)
  1365. {
  1366. int ch, blk;
  1367. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1368. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1369. if (s->exp_strategy[ch][blk] == EXP_D15) {
  1370. s->exp_strategy[ch][blk] = EXP_D25;
  1371. return 0;
  1372. }
  1373. }
  1374. }
  1375. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1376. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1377. if (s->exp_strategy[ch][blk] == EXP_D25) {
  1378. s->exp_strategy[ch][blk] = EXP_D45;
  1379. return 0;
  1380. }
  1381. }
  1382. }
  1383. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  1384. the block number > 0 */
  1385. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  1386. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1387. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  1388. s->exp_strategy[ch][blk] = EXP_REUSE;
  1389. return 0;
  1390. }
  1391. }
  1392. }
  1393. return -1;
  1394. }
  1395. /**
  1396. * Perform bit allocation search.
  1397. * Finds the SNR offset value that maximizes quality and fits in the specified
  1398. * frame size. Output is the SNR offset and a set of bit allocation pointers
  1399. * used to quantize the mantissas.
  1400. */
  1401. static int compute_bit_allocation(AC3EncodeContext *s)
  1402. {
  1403. int ret;
  1404. count_frame_bits(s);
  1405. bit_alloc_masking(s);
  1406. ret = cbr_bit_allocation(s);
  1407. while (ret) {
  1408. /* fallback 1: disable channel coupling */
  1409. if (s->cpl_on) {
  1410. s->cpl_on = 0;
  1411. compute_coupling_strategy(s);
  1412. compute_rematrixing_strategy(s);
  1413. apply_rematrixing(s);
  1414. process_exponents(s);
  1415. ret = compute_bit_allocation(s);
  1416. continue;
  1417. }
  1418. /* fallback 2: downgrade exponents */
  1419. if (!downgrade_exponents(s)) {
  1420. extract_exponents(s);
  1421. encode_exponents(s);
  1422. group_exponents(s);
  1423. ret = compute_bit_allocation(s);
  1424. continue;
  1425. }
  1426. /* fallbacks were not enough... */
  1427. break;
  1428. }
  1429. return ret;
  1430. }
  1431. /**
  1432. * Symmetric quantization on 'levels' levels.
  1433. */
  1434. static inline int sym_quant(int c, int e, int levels)
  1435. {
  1436. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  1437. av_assert2(v >= 0 && v < levels);
  1438. return v;
  1439. }
  1440. /**
  1441. * Asymmetric quantization on 2^qbits levels.
  1442. */
  1443. static inline int asym_quant(int c, int e, int qbits)
  1444. {
  1445. int lshift, m, v;
  1446. lshift = e + qbits - 24;
  1447. if (lshift >= 0)
  1448. v = c << lshift;
  1449. else
  1450. v = c >> (-lshift);
  1451. /* rounding */
  1452. v = (v + 1) >> 1;
  1453. m = (1 << (qbits-1));
  1454. if (v >= m)
  1455. v = m - 1;
  1456. av_assert2(v >= -m);
  1457. return v & ((1 << qbits)-1);
  1458. }
  1459. /**
  1460. * Quantize a set of mantissas for a single channel in a single block.
  1461. */
  1462. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1463. uint8_t *exp, uint8_t *bap,
  1464. uint16_t *qmant, int start_freq,
  1465. int end_freq)
  1466. {
  1467. int i;
  1468. for (i = start_freq; i < end_freq; i++) {
  1469. int v;
  1470. int c = fixed_coef[i];
  1471. int e = exp[i];
  1472. int b = bap[i];
  1473. switch (b) {
  1474. case 0:
  1475. v = 0;
  1476. break;
  1477. case 1:
  1478. v = sym_quant(c, e, 3);
  1479. switch (s->mant1_cnt) {
  1480. case 0:
  1481. s->qmant1_ptr = &qmant[i];
  1482. v = 9 * v;
  1483. s->mant1_cnt = 1;
  1484. break;
  1485. case 1:
  1486. *s->qmant1_ptr += 3 * v;
  1487. s->mant1_cnt = 2;
  1488. v = 128;
  1489. break;
  1490. default:
  1491. *s->qmant1_ptr += v;
  1492. s->mant1_cnt = 0;
  1493. v = 128;
  1494. break;
  1495. }
  1496. break;
  1497. case 2:
  1498. v = sym_quant(c, e, 5);
  1499. switch (s->mant2_cnt) {
  1500. case 0:
  1501. s->qmant2_ptr = &qmant[i];
  1502. v = 25 * v;
  1503. s->mant2_cnt = 1;
  1504. break;
  1505. case 1:
  1506. *s->qmant2_ptr += 5 * v;
  1507. s->mant2_cnt = 2;
  1508. v = 128;
  1509. break;
  1510. default:
  1511. *s->qmant2_ptr += v;
  1512. s->mant2_cnt = 0;
  1513. v = 128;
  1514. break;
  1515. }
  1516. break;
  1517. case 3:
  1518. v = sym_quant(c, e, 7);
  1519. break;
  1520. case 4:
  1521. v = sym_quant(c, e, 11);
  1522. switch (s->mant4_cnt) {
  1523. case 0:
  1524. s->qmant4_ptr = &qmant[i];
  1525. v = 11 * v;
  1526. s->mant4_cnt = 1;
  1527. break;
  1528. default:
  1529. *s->qmant4_ptr += v;
  1530. s->mant4_cnt = 0;
  1531. v = 128;
  1532. break;
  1533. }
  1534. break;
  1535. case 5:
  1536. v = sym_quant(c, e, 15);
  1537. break;
  1538. case 14:
  1539. v = asym_quant(c, e, 14);
  1540. break;
  1541. case 15:
  1542. v = asym_quant(c, e, 16);
  1543. break;
  1544. default:
  1545. v = asym_quant(c, e, b - 1);
  1546. break;
  1547. }
  1548. qmant[i] = v;
  1549. }
  1550. }
  1551. /**
  1552. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1553. */
  1554. static void quantize_mantissas(AC3EncodeContext *s)
  1555. {
  1556. int blk, ch, ch0=0, got_cpl;
  1557. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1558. AC3Block *block = &s->blocks[blk];
  1559. AC3Mant m = { 0 };
  1560. got_cpl = !block->cpl_in_use;
  1561. for (ch = 1; ch <= s->channels; ch++) {
  1562. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1563. ch0 = ch - 1;
  1564. ch = CPL_CH;
  1565. got_cpl = 1;
  1566. }
  1567. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1568. s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
  1569. s->ref_bap[ch][blk], block->qmant[ch],
  1570. s->start_freq[ch], block->end_freq[ch]);
  1571. if (ch == CPL_CH)
  1572. ch = ch0;
  1573. }
  1574. }
  1575. }
  1576. /**
  1577. * Write the AC-3 frame header to the output bitstream.
  1578. */
  1579. static void ac3_output_frame_header(AC3EncodeContext *s)
  1580. {
  1581. AC3EncOptions *opt = &s->options;
  1582. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1583. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1584. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1585. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1586. put_bits(&s->pb, 5, s->bitstream_id);
  1587. put_bits(&s->pb, 3, s->bitstream_mode);
  1588. put_bits(&s->pb, 3, s->channel_mode);
  1589. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1590. put_bits(&s->pb, 2, s->center_mix_level);
  1591. if (s->channel_mode & 0x04)
  1592. put_bits(&s->pb, 2, s->surround_mix_level);
  1593. if (s->channel_mode == AC3_CHMODE_STEREO)
  1594. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1595. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1596. put_bits(&s->pb, 5, -opt->dialogue_level);
  1597. put_bits(&s->pb, 1, 0); /* no compression control word */
  1598. put_bits(&s->pb, 1, 0); /* no lang code */
  1599. put_bits(&s->pb, 1, opt->audio_production_info);
  1600. if (opt->audio_production_info) {
  1601. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1602. put_bits(&s->pb, 2, opt->room_type);
  1603. }
  1604. put_bits(&s->pb, 1, opt->copyright);
  1605. put_bits(&s->pb, 1, opt->original);
  1606. if (s->bitstream_id == 6) {
  1607. /* alternate bit stream syntax */
  1608. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1609. if (opt->extended_bsi_1) {
  1610. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1611. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1612. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1613. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1614. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1615. }
  1616. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1617. if (opt->extended_bsi_2) {
  1618. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1619. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1620. put_bits(&s->pb, 1, opt->ad_converter_type);
  1621. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1622. }
  1623. } else {
  1624. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1625. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1626. }
  1627. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1628. }
  1629. /**
  1630. * Write the E-AC-3 frame header to the output bitstream.
  1631. */
  1632. static void eac3_output_frame_header(AC3EncodeContext *s)
  1633. {
  1634. int blk, ch;
  1635. AC3EncOptions *opt = &s->options;
  1636. put_bits(&s->pb, 16, 0x0b77); /* sync word */
  1637. /* BSI header */
  1638. put_bits(&s->pb, 2, 0); /* stream type = independent */
  1639. put_bits(&s->pb, 3, 0); /* substream id = 0 */
  1640. put_bits(&s->pb, 11, (s->frame_size / 2) - 1); /* frame size */
  1641. if (s->bit_alloc.sr_shift) {
  1642. put_bits(&s->pb, 2, 0x3); /* fscod2 */
  1643. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1644. } else {
  1645. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1646. put_bits(&s->pb, 2, 0x3); /* number of blocks = 6 */
  1647. }
  1648. put_bits(&s->pb, 3, s->channel_mode); /* audio coding mode */
  1649. put_bits(&s->pb, 1, s->lfe_on); /* LFE channel indicator */
  1650. put_bits(&s->pb, 5, s->bitstream_id); /* bitstream id (EAC3=16) */
  1651. put_bits(&s->pb, 5, -opt->dialogue_level); /* dialogue normalization level */
  1652. put_bits(&s->pb, 1, 0); /* no compression gain */
  1653. put_bits(&s->pb, 1, 0); /* no mixing metadata */
  1654. /* TODO: mixing metadata */
  1655. put_bits(&s->pb, 1, 0); /* no info metadata */
  1656. /* TODO: info metadata */
  1657. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1658. /* frame header */
  1659. put_bits(&s->pb, 1, 1); /* exponent strategy syntax = each block */
  1660. put_bits(&s->pb, 1, 0); /* aht enabled = no */
  1661. put_bits(&s->pb, 2, 0); /* snr offset strategy = 1 */
  1662. put_bits(&s->pb, 1, 0); /* transient pre-noise processing enabled = no */
  1663. put_bits(&s->pb, 1, 0); /* block switch syntax enabled = no */
  1664. put_bits(&s->pb, 1, 0); /* dither flag syntax enabled = no */
  1665. put_bits(&s->pb, 1, 0); /* bit allocation model syntax enabled = no */
  1666. put_bits(&s->pb, 1, 0); /* fast gain codes enabled = no */
  1667. put_bits(&s->pb, 1, 0); /* dba syntax enabled = no */
  1668. put_bits(&s->pb, 1, 0); /* skip field syntax enabled = no */
  1669. put_bits(&s->pb, 1, 0); /* spx enabled = no */
  1670. /* coupling strategy use flags */
  1671. if (s->channel_mode > AC3_CHMODE_MONO) {
  1672. put_bits(&s->pb, 1, s->blocks[0].cpl_in_use);
  1673. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1674. AC3Block *block = &s->blocks[blk];
  1675. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1676. if (block->new_cpl_strategy)
  1677. put_bits(&s->pb, 1, block->cpl_in_use);
  1678. }
  1679. }
  1680. /* exponent strategy */
  1681. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1682. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++)
  1683. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1684. if (s->lfe_on) {
  1685. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1686. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1687. }
  1688. /* E-AC-3 to AC-3 converter exponent strategy (unfortunately not optional...) */
  1689. for (ch = 1; ch <= s->fbw_channels; ch++)
  1690. put_bits(&s->pb, 5, 0);
  1691. /* snr offsets */
  1692. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1693. put_bits(&s->pb, 4, s->fine_snr_offset[1]);
  1694. /* block start info */
  1695. put_bits(&s->pb, 1, 0);
  1696. }
  1697. /**
  1698. * Write one audio block to the output bitstream.
  1699. */
  1700. static void output_audio_block(AC3EncodeContext *s, int blk)
  1701. {
  1702. int ch, i, baie, bnd, got_cpl;
  1703. int av_uninit(ch0);
  1704. AC3Block *block = &s->blocks[blk];
  1705. /* block switching */
  1706. if (!s->eac3) {
  1707. for (ch = 0; ch < s->fbw_channels; ch++)
  1708. put_bits(&s->pb, 1, 0);
  1709. }
  1710. /* dither flags */
  1711. if (!s->eac3) {
  1712. for (ch = 0; ch < s->fbw_channels; ch++)
  1713. put_bits(&s->pb, 1, 1);
  1714. }
  1715. /* dynamic range codes */
  1716. put_bits(&s->pb, 1, 0);
  1717. /* spectral extension */
  1718. if (s->eac3)
  1719. put_bits(&s->pb, 1, 0);
  1720. /* channel coupling */
  1721. if (!s->eac3)
  1722. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1723. if (block->new_cpl_strategy) {
  1724. if (!s->eac3)
  1725. put_bits(&s->pb, 1, block->cpl_in_use);
  1726. if (block->cpl_in_use) {
  1727. int start_sub, end_sub;
  1728. if (s->eac3)
  1729. put_bits(&s->pb, 1, 0); /* enhanced coupling */
  1730. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
  1731. for (ch = 1; ch <= s->fbw_channels; ch++)
  1732. put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
  1733. }
  1734. if (s->channel_mode == AC3_CHMODE_STEREO)
  1735. put_bits(&s->pb, 1, 0); /* phase flags in use */
  1736. start_sub = (s->start_freq[CPL_CH] - 37) / 12;
  1737. end_sub = (s->cpl_end_freq - 37) / 12;
  1738. put_bits(&s->pb, 4, start_sub);
  1739. put_bits(&s->pb, 4, end_sub - 3);
  1740. /* coupling band structure */
  1741. if (s->eac3) {
  1742. put_bits(&s->pb, 1, 0); /* use default */
  1743. } else {
  1744. for (bnd = start_sub+1; bnd < end_sub; bnd++)
  1745. put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
  1746. }
  1747. }
  1748. }
  1749. /* coupling coordinates */
  1750. if (block->cpl_in_use) {
  1751. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1752. if (block->channel_in_cpl[ch]) {
  1753. if (!s->eac3 || block->new_cpl_coords != 2)
  1754. put_bits(&s->pb, 1, block->new_cpl_coords);
  1755. if (block->new_cpl_coords) {
  1756. put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
  1757. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  1758. put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
  1759. put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. }
  1765. /* stereo rematrixing */
  1766. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1767. if (!s->eac3 || blk > 0)
  1768. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1769. if (block->new_rematrixing_strategy) {
  1770. /* rematrixing flags */
  1771. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
  1772. put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
  1773. }
  1774. }
  1775. /* exponent strategy */
  1776. if (!s->eac3) {
  1777. for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
  1778. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1779. if (s->lfe_on)
  1780. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1781. }
  1782. /* bandwidth */
  1783. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1784. if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
  1785. put_bits(&s->pb, 6, s->bandwidth_code);
  1786. }
  1787. /* exponents */
  1788. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1789. int nb_groups;
  1790. int cpl = (ch == CPL_CH);
  1791. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1792. continue;
  1793. /* DC exponent */
  1794. put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
  1795. /* exponent groups */
  1796. nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
  1797. for (i = 1; i <= nb_groups; i++)
  1798. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1799. /* gain range info */
  1800. if (ch != s->lfe_channel && !cpl)
  1801. put_bits(&s->pb, 2, 0);
  1802. }
  1803. /* bit allocation info */
  1804. if (!s->eac3) {
  1805. baie = (blk == 0);
  1806. put_bits(&s->pb, 1, baie);
  1807. if (baie) {
  1808. put_bits(&s->pb, 2, s->slow_decay_code);
  1809. put_bits(&s->pb, 2, s->fast_decay_code);
  1810. put_bits(&s->pb, 2, s->slow_gain_code);
  1811. put_bits(&s->pb, 2, s->db_per_bit_code);
  1812. put_bits(&s->pb, 3, s->floor_code);
  1813. }
  1814. }
  1815. /* snr offset */
  1816. if (!s->eac3) {
  1817. put_bits(&s->pb, 1, block->new_snr_offsets);
  1818. if (block->new_snr_offsets) {
  1819. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1820. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1821. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1822. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1823. }
  1824. }
  1825. } else {
  1826. put_bits(&s->pb, 1, 0); /* no converter snr offset */
  1827. }
  1828. /* coupling leak */
  1829. if (block->cpl_in_use) {
  1830. if (!s->eac3 || block->new_cpl_leak != 2)
  1831. put_bits(&s->pb, 1, block->new_cpl_leak);
  1832. if (block->new_cpl_leak) {
  1833. put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
  1834. put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
  1835. }
  1836. }
  1837. if (!s->eac3) {
  1838. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1839. put_bits(&s->pb, 1, 0); /* no data to skip */
  1840. }
  1841. /* mantissas */
  1842. got_cpl = !block->cpl_in_use;
  1843. for (ch = 1; ch <= s->channels; ch++) {
  1844. int b, q;
  1845. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1846. ch0 = ch - 1;
  1847. ch = CPL_CH;
  1848. got_cpl = 1;
  1849. }
  1850. for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
  1851. q = block->qmant[ch][i];
  1852. b = s->ref_bap[ch][blk][i];
  1853. switch (b) {
  1854. case 0: break;
  1855. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1856. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1857. case 3: put_bits(&s->pb, 3, q); break;
  1858. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1859. case 14: put_bits(&s->pb, 14, q); break;
  1860. case 15: put_bits(&s->pb, 16, q); break;
  1861. default: put_bits(&s->pb, b-1, q); break;
  1862. }
  1863. }
  1864. if (ch == CPL_CH)
  1865. ch = ch0;
  1866. }
  1867. }
  1868. /** CRC-16 Polynomial */
  1869. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1870. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1871. {
  1872. unsigned int c;
  1873. c = 0;
  1874. while (a) {
  1875. if (a & 1)
  1876. c ^= b;
  1877. a = a >> 1;
  1878. b = b << 1;
  1879. if (b & (1 << 16))
  1880. b ^= poly;
  1881. }
  1882. return c;
  1883. }
  1884. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1885. {
  1886. unsigned int r;
  1887. r = 1;
  1888. while (n) {
  1889. if (n & 1)
  1890. r = mul_poly(r, a, poly);
  1891. a = mul_poly(a, a, poly);
  1892. n >>= 1;
  1893. }
  1894. return r;
  1895. }
  1896. /**
  1897. * Fill the end of the frame with 0's and compute the two CRCs.
  1898. */
  1899. static void output_frame_end(AC3EncodeContext *s)
  1900. {
  1901. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1902. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1903. uint8_t *frame;
  1904. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1905. /* pad the remainder of the frame with zeros */
  1906. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1907. flush_put_bits(&s->pb);
  1908. frame = s->pb.buf;
  1909. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1910. av_assert2(pad_bytes >= 0);
  1911. if (pad_bytes > 0)
  1912. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1913. if (s->eac3) {
  1914. /* compute crc2 */
  1915. crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
  1916. } else {
  1917. /* compute crc1 */
  1918. /* this is not so easy because it is at the beginning of the data... */
  1919. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1920. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1921. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1922. AV_WB16(frame + 2, crc1);
  1923. /* compute crc2 */
  1924. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1925. s->frame_size - frame_size_58 - 3);
  1926. }
  1927. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1928. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1929. if (crc2 == 0x770B) {
  1930. frame[s->frame_size - 3] ^= 0x1;
  1931. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1932. }
  1933. crc2 = av_bswap16(crc2);
  1934. AV_WB16(frame + s->frame_size - 2, crc2);
  1935. }
  1936. /**
  1937. * Write the frame to the output bitstream.
  1938. */
  1939. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1940. {
  1941. int blk;
  1942. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1943. if (s->eac3)
  1944. eac3_output_frame_header(s);
  1945. else
  1946. ac3_output_frame_header(s);
  1947. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1948. output_audio_block(s, blk);
  1949. output_frame_end(s);
  1950. }
  1951. static void dprint_options(AVCodecContext *avctx)
  1952. {
  1953. #ifdef DEBUG
  1954. AC3EncodeContext *s = avctx->priv_data;
  1955. AC3EncOptions *opt = &s->options;
  1956. char strbuf[32];
  1957. switch (s->bitstream_id) {
  1958. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1959. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1960. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1961. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
  1962. case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
  1963. default: snprintf(strbuf, 32, "ERROR");
  1964. }
  1965. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1966. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1967. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1968. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1969. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1970. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1971. if (s->cutoff)
  1972. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1973. av_dlog(avctx, "per_frame_metadata: %s\n",
  1974. opt->allow_per_frame_metadata?"on":"off");
  1975. if (s->has_center)
  1976. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1977. s->center_mix_level);
  1978. else
  1979. av_dlog(avctx, "center_mixlev: {not written}\n");
  1980. if (s->has_surround)
  1981. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1982. s->surround_mix_level);
  1983. else
  1984. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1985. if (opt->audio_production_info) {
  1986. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1987. switch (opt->room_type) {
  1988. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1989. case 1: av_strlcpy(strbuf, "large", 32); break;
  1990. case 2: av_strlcpy(strbuf, "small", 32); break;
  1991. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1992. }
  1993. av_dlog(avctx, "room_type: %s\n", strbuf);
  1994. } else {
  1995. av_dlog(avctx, "mixing_level: {not written}\n");
  1996. av_dlog(avctx, "room_type: {not written}\n");
  1997. }
  1998. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1999. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  2000. if (s->channel_mode == AC3_CHMODE_STEREO) {
  2001. switch (opt->dolby_surround_mode) {
  2002. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2003. case 1: av_strlcpy(strbuf, "on", 32); break;
  2004. case 2: av_strlcpy(strbuf, "off", 32); break;
  2005. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  2006. }
  2007. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  2008. } else {
  2009. av_dlog(avctx, "dsur_mode: {not written}\n");
  2010. }
  2011. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  2012. if (s->bitstream_id == 6) {
  2013. if (opt->extended_bsi_1) {
  2014. switch (opt->preferred_stereo_downmix) {
  2015. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2016. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  2017. case 2: av_strlcpy(strbuf, "loro", 32); break;
  2018. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  2019. }
  2020. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  2021. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  2022. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  2023. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  2024. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  2025. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  2026. opt->loro_center_mix_level, s->loro_center_mix_level);
  2027. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  2028. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  2029. } else {
  2030. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  2031. }
  2032. if (opt->extended_bsi_2) {
  2033. switch (opt->dolby_surround_ex_mode) {
  2034. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2035. case 1: av_strlcpy(strbuf, "on", 32); break;
  2036. case 2: av_strlcpy(strbuf, "off", 32); break;
  2037. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  2038. }
  2039. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  2040. switch (opt->dolby_headphone_mode) {
  2041. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2042. case 1: av_strlcpy(strbuf, "on", 32); break;
  2043. case 2: av_strlcpy(strbuf, "off", 32); break;
  2044. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  2045. }
  2046. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  2047. switch (opt->ad_converter_type) {
  2048. case 0: av_strlcpy(strbuf, "standard", 32); break;
  2049. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  2050. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  2051. }
  2052. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  2053. } else {
  2054. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  2055. }
  2056. }
  2057. #endif
  2058. }
  2059. #define FLT_OPTION_THRESHOLD 0.01
  2060. static int validate_float_option(float v, const float *v_list, int v_list_size)
  2061. {
  2062. int i;
  2063. for (i = 0; i < v_list_size; i++) {
  2064. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  2065. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  2066. break;
  2067. }
  2068. if (i == v_list_size)
  2069. return -1;
  2070. return i;
  2071. }
  2072. static void validate_mix_level(void *log_ctx, const char *opt_name,
  2073. float *opt_param, const float *list,
  2074. int list_size, int default_value, int min_value,
  2075. int *ctx_param)
  2076. {
  2077. int mixlev = validate_float_option(*opt_param, list, list_size);
  2078. if (mixlev < min_value) {
  2079. mixlev = default_value;
  2080. if (*opt_param >= 0.0) {
  2081. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  2082. "default value: %0.3f\n", opt_name, list[mixlev]);
  2083. }
  2084. }
  2085. *opt_param = list[mixlev];
  2086. *ctx_param = mixlev;
  2087. }
  2088. /**
  2089. * Validate metadata options as set by AVOption system.
  2090. * These values can optionally be changed per-frame.
  2091. */
  2092. static int validate_metadata(AVCodecContext *avctx)
  2093. {
  2094. AC3EncodeContext *s = avctx->priv_data;
  2095. AC3EncOptions *opt = &s->options;
  2096. /* validate mixing levels */
  2097. if (s->has_center) {
  2098. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  2099. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  2100. &s->center_mix_level);
  2101. }
  2102. if (s->has_surround) {
  2103. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  2104. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  2105. &s->surround_mix_level);
  2106. }
  2107. /* set audio production info flag */
  2108. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  2109. if (opt->mixing_level < 0) {
  2110. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  2111. "room_type is set\n");
  2112. return AVERROR(EINVAL);
  2113. }
  2114. if (opt->mixing_level < 80) {
  2115. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  2116. "80dB and 111dB\n");
  2117. return AVERROR(EINVAL);
  2118. }
  2119. /* default room type */
  2120. if (opt->room_type < 0)
  2121. opt->room_type = 0;
  2122. opt->audio_production_info = 1;
  2123. } else {
  2124. opt->audio_production_info = 0;
  2125. }
  2126. /* set extended bsi 1 flag */
  2127. if ((s->has_center || s->has_surround) &&
  2128. (opt->preferred_stereo_downmix >= 0 ||
  2129. opt->ltrt_center_mix_level >= 0 ||
  2130. opt->ltrt_surround_mix_level >= 0 ||
  2131. opt->loro_center_mix_level >= 0 ||
  2132. opt->loro_surround_mix_level >= 0)) {
  2133. /* default preferred stereo downmix */
  2134. if (opt->preferred_stereo_downmix < 0)
  2135. opt->preferred_stereo_downmix = 0;
  2136. /* validate Lt/Rt center mix level */
  2137. validate_mix_level(avctx, "ltrt_center_mix_level",
  2138. &opt->ltrt_center_mix_level, extmixlev_options,
  2139. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2140. &s->ltrt_center_mix_level);
  2141. /* validate Lt/Rt surround mix level */
  2142. validate_mix_level(avctx, "ltrt_surround_mix_level",
  2143. &opt->ltrt_surround_mix_level, extmixlev_options,
  2144. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2145. &s->ltrt_surround_mix_level);
  2146. /* validate Lo/Ro center mix level */
  2147. validate_mix_level(avctx, "loro_center_mix_level",
  2148. &opt->loro_center_mix_level, extmixlev_options,
  2149. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2150. &s->loro_center_mix_level);
  2151. /* validate Lo/Ro surround mix level */
  2152. validate_mix_level(avctx, "loro_surround_mix_level",
  2153. &opt->loro_surround_mix_level, extmixlev_options,
  2154. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2155. &s->loro_surround_mix_level);
  2156. opt->extended_bsi_1 = 1;
  2157. } else {
  2158. opt->extended_bsi_1 = 0;
  2159. }
  2160. /* set extended bsi 2 flag */
  2161. if (opt->dolby_surround_ex_mode >= 0 ||
  2162. opt->dolby_headphone_mode >= 0 ||
  2163. opt->ad_converter_type >= 0) {
  2164. /* default dolby surround ex mode */
  2165. if (opt->dolby_surround_ex_mode < 0)
  2166. opt->dolby_surround_ex_mode = 0;
  2167. /* default dolby headphone mode */
  2168. if (opt->dolby_headphone_mode < 0)
  2169. opt->dolby_headphone_mode = 0;
  2170. /* default A/D converter type */
  2171. if (opt->ad_converter_type < 0)
  2172. opt->ad_converter_type = 0;
  2173. opt->extended_bsi_2 = 1;
  2174. } else {
  2175. opt->extended_bsi_2 = 0;
  2176. }
  2177. /* set bitstream id for alternate bitstream syntax */
  2178. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  2179. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  2180. static int warn_once = 1;
  2181. if (warn_once) {
  2182. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  2183. "not compatible with reduced samplerates. writing of "
  2184. "extended bitstream information will be disabled.\n");
  2185. warn_once = 0;
  2186. }
  2187. } else {
  2188. s->bitstream_id = 6;
  2189. }
  2190. }
  2191. return 0;
  2192. }
  2193. /**
  2194. * Encode a single AC-3 frame.
  2195. */
  2196. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  2197. int buf_size, void *data)
  2198. {
  2199. AC3EncodeContext *s = avctx->priv_data;
  2200. const SampleType *samples = data;
  2201. int ret;
  2202. if (!s->eac3 && s->options.allow_per_frame_metadata) {
  2203. ret = validate_metadata(avctx);
  2204. if (ret)
  2205. return ret;
  2206. }
  2207. if (s->bit_alloc.sr_code == 1 || s->eac3)
  2208. adjust_frame_size(s);
  2209. deinterleave_input_samples(s, samples);
  2210. apply_mdct(s);
  2211. scale_coefficients(s);
  2212. s->cpl_on = s->cpl_enabled;
  2213. compute_coupling_strategy(s);
  2214. if (s->cpl_on)
  2215. apply_channel_coupling(s);
  2216. compute_rematrixing_strategy(s);
  2217. apply_rematrixing(s);
  2218. process_exponents(s);
  2219. ret = compute_bit_allocation(s);
  2220. if (ret) {
  2221. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  2222. return ret;
  2223. }
  2224. quantize_mantissas(s);
  2225. output_frame(s, frame);
  2226. return s->frame_size;
  2227. }
  2228. /**
  2229. * Finalize encoding and free any memory allocated by the encoder.
  2230. */
  2231. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  2232. {
  2233. int blk, ch;
  2234. AC3EncodeContext *s = avctx->priv_data;
  2235. for (ch = 0; ch < s->channels; ch++)
  2236. av_freep(&s->planar_samples[ch]);
  2237. av_freep(&s->planar_samples);
  2238. av_freep(&s->bap_buffer);
  2239. av_freep(&s->bap1_buffer);
  2240. av_freep(&s->mdct_coef_buffer);
  2241. av_freep(&s->fixed_coef_buffer);
  2242. av_freep(&s->exp_buffer);
  2243. av_freep(&s->grouped_exp_buffer);
  2244. av_freep(&s->psd_buffer);
  2245. av_freep(&s->band_psd_buffer);
  2246. av_freep(&s->mask_buffer);
  2247. av_freep(&s->qmant_buffer);
  2248. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2249. AC3Block *block = &s->blocks[blk];
  2250. av_freep(&block->mdct_coef);
  2251. av_freep(&block->fixed_coef);
  2252. av_freep(&block->exp);
  2253. av_freep(&block->grouped_exp);
  2254. av_freep(&block->psd);
  2255. av_freep(&block->band_psd);
  2256. av_freep(&block->mask);
  2257. av_freep(&block->qmant);
  2258. }
  2259. mdct_end(&s->mdct);
  2260. av_freep(&avctx->coded_frame);
  2261. return 0;
  2262. }
  2263. /**
  2264. * Set channel information during initialization.
  2265. */
  2266. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  2267. int64_t *channel_layout)
  2268. {
  2269. int ch_layout;
  2270. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  2271. return AVERROR(EINVAL);
  2272. if ((uint64_t)*channel_layout > 0x7FF)
  2273. return AVERROR(EINVAL);
  2274. ch_layout = *channel_layout;
  2275. if (!ch_layout)
  2276. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  2277. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  2278. s->channels = channels;
  2279. s->fbw_channels = channels - s->lfe_on;
  2280. s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
  2281. if (s->lfe_on)
  2282. ch_layout -= AV_CH_LOW_FREQUENCY;
  2283. switch (ch_layout) {
  2284. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  2285. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  2286. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  2287. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  2288. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  2289. case AV_CH_LAYOUT_QUAD:
  2290. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  2291. case AV_CH_LAYOUT_5POINT0:
  2292. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  2293. default:
  2294. return AVERROR(EINVAL);
  2295. }
  2296. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  2297. s->has_surround = s->channel_mode & 0x04;
  2298. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  2299. *channel_layout = ch_layout;
  2300. if (s->lfe_on)
  2301. *channel_layout |= AV_CH_LOW_FREQUENCY;
  2302. return 0;
  2303. }
  2304. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  2305. {
  2306. int i, ret, max_sr;
  2307. /* validate channel layout */
  2308. if (!avctx->channel_layout) {
  2309. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  2310. "encoder will guess the layout, but it "
  2311. "might be incorrect.\n");
  2312. }
  2313. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  2314. if (ret) {
  2315. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  2316. return ret;
  2317. }
  2318. /* validate sample rate */
  2319. /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
  2320. decoder that supports half sample rate so we can validate that
  2321. the generated files are correct. */
  2322. max_sr = s->eac3 ? 2 : 8;
  2323. for (i = 0; i <= max_sr; i++) {
  2324. if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
  2325. break;
  2326. }
  2327. if (i > max_sr) {
  2328. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  2329. return AVERROR(EINVAL);
  2330. }
  2331. s->sample_rate = avctx->sample_rate;
  2332. s->bit_alloc.sr_shift = i / 3;
  2333. s->bit_alloc.sr_code = i % 3;
  2334. s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
  2335. /* validate bit rate */
  2336. if (s->eac3) {
  2337. int max_br, min_br, wpf, min_br_dist, min_br_code;
  2338. /* calculate min/max bitrate */
  2339. max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
  2340. min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
  2341. if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
  2342. av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
  2343. "for this sample rate\n", min_br, max_br);
  2344. return AVERROR(EINVAL);
  2345. }
  2346. /* calculate words-per-frame for the selected bitrate */
  2347. wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
  2348. av_assert1(wpf > 0 && wpf <= 2048);
  2349. /* find the closest AC-3 bitrate code to the selected bitrate.
  2350. this is needed for lookup tables for bandwidth and coupling
  2351. parameter selection */
  2352. min_br_code = -1;
  2353. min_br_dist = INT_MAX;
  2354. for (i = 0; i < 19; i++) {
  2355. int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
  2356. if (br_dist < min_br_dist) {
  2357. min_br_dist = br_dist;
  2358. min_br_code = i;
  2359. }
  2360. }
  2361. /* make sure the minimum frame size is below the average frame size */
  2362. s->frame_size_code = min_br_code << 1;
  2363. while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
  2364. wpf--;
  2365. s->frame_size_min = 2 * wpf;
  2366. } else {
  2367. for (i = 0; i < 19; i++) {
  2368. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  2369. break;
  2370. }
  2371. if (i == 19) {
  2372. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  2373. return AVERROR(EINVAL);
  2374. }
  2375. s->frame_size_code = i << 1;
  2376. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  2377. }
  2378. s->bit_rate = avctx->bit_rate;
  2379. s->frame_size = s->frame_size_min;
  2380. /* validate cutoff */
  2381. if (avctx->cutoff < 0) {
  2382. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  2383. return AVERROR(EINVAL);
  2384. }
  2385. s->cutoff = avctx->cutoff;
  2386. if (s->cutoff > (s->sample_rate >> 1))
  2387. s->cutoff = s->sample_rate >> 1;
  2388. /* validate audio service type / channels combination */
  2389. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  2390. avctx->channels == 1) ||
  2391. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  2392. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  2393. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  2394. && avctx->channels > 1)) {
  2395. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  2396. "specified number of channels\n");
  2397. return AVERROR(EINVAL);
  2398. }
  2399. if (!s->eac3) {
  2400. ret = validate_metadata(avctx);
  2401. if (ret)
  2402. return ret;
  2403. }
  2404. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  2405. (s->channel_mode == AC3_CHMODE_STEREO);
  2406. s->cpl_enabled = s->options.channel_coupling &&
  2407. s->channel_mode >= AC3_CHMODE_STEREO &&
  2408. CONFIG_AC3ENC_FLOAT;
  2409. return 0;
  2410. }
  2411. /**
  2412. * Set bandwidth for all channels.
  2413. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  2414. * default value will be used.
  2415. */
  2416. static av_cold void set_bandwidth(AC3EncodeContext *s)
  2417. {
  2418. int blk, ch;
  2419. int av_uninit(cpl_start);
  2420. if (s->cutoff) {
  2421. /* calculate bandwidth based on user-specified cutoff frequency */
  2422. int fbw_coeffs;
  2423. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  2424. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  2425. } else {
  2426. /* use default bandwidth setting */
  2427. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  2428. }
  2429. /* set number of coefficients for each channel */
  2430. for (ch = 1; ch <= s->fbw_channels; ch++) {
  2431. s->start_freq[ch] = 0;
  2432. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2433. s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
  2434. }
  2435. /* LFE channel always has 7 coefs */
  2436. if (s->lfe_on) {
  2437. s->start_freq[s->lfe_channel] = 0;
  2438. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2439. s->blocks[blk].end_freq[ch] = 7;
  2440. }
  2441. /* initialize coupling strategy */
  2442. if (s->cpl_enabled) {
  2443. if (s->options.cpl_start >= 0) {
  2444. cpl_start = s->options.cpl_start;
  2445. } else {
  2446. cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
  2447. if (cpl_start < 0)
  2448. s->cpl_enabled = 0;
  2449. }
  2450. }
  2451. if (s->cpl_enabled) {
  2452. int i, cpl_start_band, cpl_end_band;
  2453. uint8_t *cpl_band_sizes = s->cpl_band_sizes;
  2454. cpl_end_band = s->bandwidth_code / 4 + 3;
  2455. cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
  2456. s->num_cpl_subbands = cpl_end_band - cpl_start_band;
  2457. s->num_cpl_bands = 1;
  2458. *cpl_band_sizes = 12;
  2459. for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
  2460. if (ff_eac3_default_cpl_band_struct[i]) {
  2461. *cpl_band_sizes += 12;
  2462. } else {
  2463. s->num_cpl_bands++;
  2464. cpl_band_sizes++;
  2465. *cpl_band_sizes = 12;
  2466. }
  2467. }
  2468. s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
  2469. s->cpl_end_freq = cpl_end_band * 12 + 37;
  2470. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2471. s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
  2472. }
  2473. }
  2474. static av_cold int allocate_buffers(AVCodecContext *avctx)
  2475. {
  2476. int blk, ch;
  2477. AC3EncodeContext *s = avctx->priv_data;
  2478. int channels = s->channels + 1; /* includes coupling channel */
  2479. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  2480. alloc_fail);
  2481. for (ch = 0; ch < s->channels; ch++) {
  2482. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  2483. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  2484. alloc_fail);
  2485. }
  2486. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
  2487. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  2488. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
  2489. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  2490. FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
  2491. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  2492. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
  2493. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  2494. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
  2495. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  2496. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
  2497. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  2498. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
  2499. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  2500. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
  2501. 64 * sizeof(*s->mask_buffer), alloc_fail);
  2502. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
  2503. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  2504. if (s->cpl_enabled) {
  2505. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
  2506. 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
  2507. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
  2508. 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
  2509. }
  2510. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2511. AC3Block *block = &s->blocks[blk];
  2512. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
  2513. alloc_fail);
  2514. FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
  2515. alloc_fail);
  2516. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
  2517. alloc_fail);
  2518. FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
  2519. alloc_fail);
  2520. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
  2521. alloc_fail);
  2522. FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
  2523. alloc_fail);
  2524. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
  2525. alloc_fail);
  2526. if (s->cpl_enabled) {
  2527. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
  2528. alloc_fail);
  2529. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
  2530. alloc_fail);
  2531. }
  2532. for (ch = 0; ch < channels; ch++) {
  2533. /* arrangement: block, channel, coeff */
  2534. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
  2535. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2536. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
  2537. block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
  2538. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2539. if (s->cpl_enabled) {
  2540. block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
  2541. block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
  2542. }
  2543. /* arrangement: channel, block, coeff */
  2544. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2545. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2546. }
  2547. }
  2548. if (CONFIG_AC3ENC_FLOAT) {
  2549. FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
  2550. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  2551. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2552. AC3Block *block = &s->blocks[blk];
  2553. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2554. sizeof(*block->fixed_coef), alloc_fail);
  2555. for (ch = 0; ch < channels; ch++)
  2556. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2557. }
  2558. } else {
  2559. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2560. AC3Block *block = &s->blocks[blk];
  2561. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2562. sizeof(*block->fixed_coef), alloc_fail);
  2563. for (ch = 0; ch < channels; ch++)
  2564. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  2565. }
  2566. }
  2567. return 0;
  2568. alloc_fail:
  2569. return AVERROR(ENOMEM);
  2570. }
  2571. /**
  2572. * Initialize the encoder.
  2573. */
  2574. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  2575. {
  2576. AC3EncodeContext *s = avctx->priv_data;
  2577. int ret, frame_size_58;
  2578. s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
  2579. avctx->frame_size = AC3_FRAME_SIZE;
  2580. ff_ac3_common_init();
  2581. ret = validate_options(avctx, s);
  2582. if (ret)
  2583. return ret;
  2584. s->bitstream_mode = avctx->audio_service_type;
  2585. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  2586. s->bitstream_mode = 0x7;
  2587. s->bits_written = 0;
  2588. s->samples_written = 0;
  2589. /* calculate crc_inv for both possible frame sizes */
  2590. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  2591. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2592. if (s->bit_alloc.sr_code == 1) {
  2593. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  2594. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2595. }
  2596. set_bandwidth(s);
  2597. exponent_init(s);
  2598. bit_alloc_init(s);
  2599. ret = mdct_init(avctx, &s->mdct, 9);
  2600. if (ret)
  2601. goto init_fail;
  2602. ret = allocate_buffers(avctx);
  2603. if (ret)
  2604. goto init_fail;
  2605. avctx->coded_frame= avcodec_alloc_frame();
  2606. dsputil_init(&s->dsp, avctx);
  2607. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  2608. dprint_options(avctx);
  2609. return 0;
  2610. init_fail:
  2611. ac3_encode_close(avctx);
  2612. return ret;
  2613. }