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.

3009 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 ch = !s->cpl_on;
  751. int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
  752. AC3Block *block = &s->blocks[0];
  753. s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
  754. }
  755. /**
  756. * Exponent Difference Threshold.
  757. * New exponents are sent if their SAD exceed this number.
  758. */
  759. #define EXP_DIFF_THRESHOLD 500
  760. /**
  761. * Calculate exponent strategies for all channels.
  762. * Array arrangement is reversed to simplify the per-channel calculation.
  763. */
  764. static void compute_exp_strategy(AC3EncodeContext *s)
  765. {
  766. int ch, blk, blk1;
  767. for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
  768. uint8_t *exp_strategy = s->exp_strategy[ch];
  769. uint8_t *exp = s->blocks[0].exp[ch];
  770. int exp_diff;
  771. /* estimate if the exponent variation & decide if they should be
  772. reused in the next frame */
  773. exp_strategy[0] = EXP_NEW;
  774. exp += AC3_MAX_COEFS;
  775. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
  776. if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
  777. (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
  778. exp_strategy[blk] = EXP_NEW;
  779. continue;
  780. }
  781. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  782. exp_strategy[blk] = EXP_REUSE;
  783. if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
  784. exp_strategy[blk] = EXP_NEW;
  785. else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
  786. exp_strategy[blk] = EXP_NEW;
  787. }
  788. /* now select the encoding strategy type : if exponents are often
  789. recoded, we use a coarse encoding */
  790. blk = 0;
  791. while (blk < AC3_MAX_BLOCKS) {
  792. blk1 = blk + 1;
  793. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  794. blk1++;
  795. switch (blk1 - blk) {
  796. case 1: exp_strategy[blk] = EXP_D45; break;
  797. case 2:
  798. case 3: exp_strategy[blk] = EXP_D25; break;
  799. default: exp_strategy[blk] = EXP_D15; break;
  800. }
  801. blk = blk1;
  802. }
  803. }
  804. if (s->lfe_on) {
  805. ch = s->lfe_channel;
  806. s->exp_strategy[ch][0] = EXP_D15;
  807. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  808. s->exp_strategy[ch][blk] = EXP_REUSE;
  809. }
  810. }
  811. /**
  812. * Update the exponents so that they are the ones the decoder will decode.
  813. */
  814. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
  815. int cpl)
  816. {
  817. int nb_groups, i, k;
  818. nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
  819. /* for each group, compute the minimum exponent */
  820. switch(exp_strategy) {
  821. case EXP_D25:
  822. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  823. uint8_t exp_min = exp[k];
  824. if (exp[k+1] < exp_min)
  825. exp_min = exp[k+1];
  826. exp[i-cpl] = exp_min;
  827. k += 2;
  828. }
  829. break;
  830. case EXP_D45:
  831. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  832. uint8_t exp_min = exp[k];
  833. if (exp[k+1] < exp_min)
  834. exp_min = exp[k+1];
  835. if (exp[k+2] < exp_min)
  836. exp_min = exp[k+2];
  837. if (exp[k+3] < exp_min)
  838. exp_min = exp[k+3];
  839. exp[i-cpl] = exp_min;
  840. k += 4;
  841. }
  842. break;
  843. }
  844. /* constraint for DC exponent */
  845. if (!cpl && exp[0] > 15)
  846. exp[0] = 15;
  847. /* decrease the delta between each groups to within 2 so that they can be
  848. differentially encoded */
  849. for (i = 1; i <= nb_groups; i++)
  850. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  851. i--;
  852. while (--i >= 0)
  853. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  854. if (cpl)
  855. exp[-1] = exp[0] & ~1;
  856. /* now we have the exponent values the decoder will see */
  857. switch (exp_strategy) {
  858. case EXP_D25:
  859. for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
  860. uint8_t exp1 = exp[i-cpl];
  861. exp[k--] = exp1;
  862. exp[k--] = exp1;
  863. }
  864. break;
  865. case EXP_D45:
  866. for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
  867. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
  868. k -= 4;
  869. }
  870. break;
  871. }
  872. }
  873. /**
  874. * Encode exponents from original extracted form to what the decoder will see.
  875. * This copies and groups exponents based on exponent strategy and reduces
  876. * deltas between adjacent exponent groups so that they can be differentially
  877. * encoded.
  878. */
  879. static void encode_exponents(AC3EncodeContext *s)
  880. {
  881. int blk, blk1, ch, cpl;
  882. uint8_t *exp, *exp_strategy;
  883. int nb_coefs, num_reuse_blocks;
  884. for (ch = !s->cpl_on; ch <= s->channels; ch++) {
  885. exp = s->blocks[0].exp[ch] + s->start_freq[ch];
  886. exp_strategy = s->exp_strategy[ch];
  887. cpl = (ch == CPL_CH);
  888. blk = 0;
  889. while (blk < AC3_MAX_BLOCKS) {
  890. AC3Block *block = &s->blocks[blk];
  891. if (cpl && !block->cpl_in_use) {
  892. exp += AC3_MAX_COEFS;
  893. blk++;
  894. continue;
  895. }
  896. nb_coefs = block->end_freq[ch] - s->start_freq[ch];
  897. blk1 = blk + 1;
  898. /* count the number of EXP_REUSE blocks after the current block
  899. and set exponent reference block numbers */
  900. s->exp_ref_block[ch][blk] = blk;
  901. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  902. s->exp_ref_block[ch][blk1] = blk;
  903. blk1++;
  904. }
  905. num_reuse_blocks = blk1 - blk - 1;
  906. /* for the EXP_REUSE case we select the min of the exponents */
  907. s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
  908. AC3_MAX_COEFS);
  909. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
  910. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  911. blk = blk1;
  912. }
  913. }
  914. /* reference block numbers have been changed, so reset ref_bap_set */
  915. s->ref_bap_set = 0;
  916. }
  917. /**
  918. * Group exponents.
  919. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  920. * varies depending on exponent strategy and bandwidth.
  921. */
  922. static void group_exponents(AC3EncodeContext *s)
  923. {
  924. int blk, ch, i, cpl;
  925. int group_size, nb_groups, bit_count;
  926. uint8_t *p;
  927. int delta0, delta1, delta2;
  928. int exp0, exp1;
  929. bit_count = 0;
  930. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  931. AC3Block *block = &s->blocks[blk];
  932. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  933. int exp_strategy = s->exp_strategy[ch][blk];
  934. if (exp_strategy == EXP_REUSE)
  935. continue;
  936. cpl = (ch == CPL_CH);
  937. group_size = exp_strategy + (exp_strategy == EXP_D45);
  938. nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
  939. bit_count += 4 + (nb_groups * 7);
  940. p = block->exp[ch] + s->start_freq[ch] - cpl;
  941. /* DC exponent */
  942. exp1 = *p++;
  943. block->grouped_exp[ch][0] = exp1;
  944. /* remaining exponents are delta encoded */
  945. for (i = 1; i <= nb_groups; i++) {
  946. /* merge three delta in one code */
  947. exp0 = exp1;
  948. exp1 = p[0];
  949. p += group_size;
  950. delta0 = exp1 - exp0 + 2;
  951. av_assert2(delta0 >= 0 && delta0 <= 4);
  952. exp0 = exp1;
  953. exp1 = p[0];
  954. p += group_size;
  955. delta1 = exp1 - exp0 + 2;
  956. av_assert2(delta1 >= 0 && delta1 <= 4);
  957. exp0 = exp1;
  958. exp1 = p[0];
  959. p += group_size;
  960. delta2 = exp1 - exp0 + 2;
  961. av_assert2(delta2 >= 0 && delta2 <= 4);
  962. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  963. }
  964. }
  965. }
  966. s->exponent_bits = bit_count;
  967. }
  968. /**
  969. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  970. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  971. * and encode final exponents.
  972. */
  973. static void process_exponents(AC3EncodeContext *s)
  974. {
  975. extract_exponents(s);
  976. compute_exp_strategy(s);
  977. encode_exponents(s);
  978. group_exponents(s);
  979. emms_c();
  980. }
  981. /**
  982. * Count frame bits that are based solely on fixed parameters.
  983. * This only has to be run once when the encoder is initialized.
  984. */
  985. static void count_frame_bits_fixed(AC3EncodeContext *s)
  986. {
  987. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  988. int blk;
  989. int frame_bits;
  990. /* assumptions:
  991. * no dynamic range codes
  992. * bit allocation parameters do not change between blocks
  993. * no delta bit allocation
  994. * no skipped data
  995. * no auxilliary data
  996. * no E-AC-3 metadata
  997. */
  998. /* header */
  999. frame_bits = 16; /* sync info */
  1000. if (s->eac3) {
  1001. /* bitstream info header */
  1002. frame_bits += 35;
  1003. frame_bits += 1 + 1 + 1;
  1004. /* audio frame header */
  1005. frame_bits += 2;
  1006. frame_bits += 10;
  1007. /* exponent strategy */
  1008. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1009. frame_bits += 2 * s->fbw_channels + s->lfe_on;
  1010. /* converter exponent strategy */
  1011. frame_bits += s->fbw_channels * 5;
  1012. /* snr offsets */
  1013. frame_bits += 10;
  1014. /* block start info */
  1015. frame_bits++;
  1016. } else {
  1017. frame_bits += 49;
  1018. frame_bits += frame_bits_inc[s->channel_mode];
  1019. }
  1020. /* audio blocks */
  1021. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1022. if (!s->eac3) {
  1023. /* block switch flags */
  1024. frame_bits += s->fbw_channels;
  1025. /* dither flags */
  1026. frame_bits += s->fbw_channels;
  1027. }
  1028. /* dynamic range */
  1029. frame_bits++;
  1030. /* spectral extension */
  1031. if (s->eac3)
  1032. frame_bits++;
  1033. if (!s->eac3) {
  1034. /* exponent strategy */
  1035. frame_bits += 2 * s->fbw_channels;
  1036. if (s->lfe_on)
  1037. frame_bits++;
  1038. /* bit allocation params */
  1039. frame_bits++;
  1040. if (!blk)
  1041. frame_bits += 2 + 2 + 2 + 2 + 3;
  1042. }
  1043. /* converter snr offset */
  1044. if (s->eac3)
  1045. frame_bits++;
  1046. if (!s->eac3) {
  1047. /* delta bit allocation */
  1048. frame_bits++;
  1049. /* skipped data */
  1050. frame_bits++;
  1051. }
  1052. }
  1053. /* auxiliary data */
  1054. frame_bits++;
  1055. /* CRC */
  1056. frame_bits += 1 + 16;
  1057. s->frame_bits_fixed = frame_bits;
  1058. }
  1059. /**
  1060. * Initialize bit allocation.
  1061. * Set default parameter codes and calculate parameter values.
  1062. */
  1063. static void bit_alloc_init(AC3EncodeContext *s)
  1064. {
  1065. int ch;
  1066. /* init default parameters */
  1067. s->slow_decay_code = 2;
  1068. s->fast_decay_code = 1;
  1069. s->slow_gain_code = 1;
  1070. s->db_per_bit_code = s->eac3 ? 2 : 3;
  1071. s->floor_code = 7;
  1072. for (ch = 0; ch <= s->channels; ch++)
  1073. s->fast_gain_code[ch] = 4;
  1074. /* initial snr offset */
  1075. s->coarse_snr_offset = 40;
  1076. /* compute real values */
  1077. /* currently none of these values change during encoding, so we can just
  1078. set them once at initialization */
  1079. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  1080. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  1081. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  1082. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  1083. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  1084. s->bit_alloc.cpl_fast_leak = 0;
  1085. s->bit_alloc.cpl_slow_leak = 0;
  1086. count_frame_bits_fixed(s);
  1087. }
  1088. /**
  1089. * Count the bits used to encode the frame, minus exponents and mantissas.
  1090. * Bits based on fixed parameters have already been counted, so now we just
  1091. * have to add the bits based on parameters that change during encoding.
  1092. */
  1093. static void count_frame_bits(AC3EncodeContext *s)
  1094. {
  1095. AC3EncOptions *opt = &s->options;
  1096. int blk, ch;
  1097. int frame_bits = 0;
  1098. /* header */
  1099. if (s->eac3) {
  1100. /* coupling */
  1101. if (s->channel_mode > AC3_CHMODE_MONO) {
  1102. frame_bits++;
  1103. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1104. AC3Block *block = &s->blocks[blk];
  1105. frame_bits++;
  1106. if (block->new_cpl_strategy)
  1107. frame_bits++;
  1108. }
  1109. }
  1110. /* coupling exponent strategy */
  1111. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1112. frame_bits += 2 * s->blocks[blk].cpl_in_use;
  1113. } else {
  1114. if (opt->audio_production_info)
  1115. frame_bits += 7;
  1116. if (s->bitstream_id == 6) {
  1117. if (opt->extended_bsi_1)
  1118. frame_bits += 14;
  1119. if (opt->extended_bsi_2)
  1120. frame_bits += 14;
  1121. }
  1122. }
  1123. /* audio blocks */
  1124. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1125. AC3Block *block = &s->blocks[blk];
  1126. /* coupling strategy */
  1127. if (!s->eac3)
  1128. frame_bits++;
  1129. if (block->new_cpl_strategy) {
  1130. if (!s->eac3)
  1131. frame_bits++;
  1132. if (block->cpl_in_use) {
  1133. if (s->eac3)
  1134. frame_bits++;
  1135. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
  1136. frame_bits += s->fbw_channels;
  1137. if (s->channel_mode == AC3_CHMODE_STEREO)
  1138. frame_bits++;
  1139. frame_bits += 4 + 4;
  1140. if (s->eac3)
  1141. frame_bits++;
  1142. else
  1143. frame_bits += s->num_cpl_subbands - 1;
  1144. }
  1145. }
  1146. /* coupling coordinates */
  1147. if (block->cpl_in_use) {
  1148. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1149. if (block->channel_in_cpl[ch]) {
  1150. if (!s->eac3 || block->new_cpl_coords != 2)
  1151. frame_bits++;
  1152. if (block->new_cpl_coords) {
  1153. frame_bits += 2;
  1154. frame_bits += (4 + 4) * s->num_cpl_bands;
  1155. }
  1156. }
  1157. }
  1158. }
  1159. /* stereo rematrixing */
  1160. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1161. if (!s->eac3 || blk > 0)
  1162. frame_bits++;
  1163. if (s->blocks[blk].new_rematrixing_strategy)
  1164. frame_bits += block->num_rematrixing_bands;
  1165. }
  1166. /* bandwidth codes & gain range */
  1167. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1168. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1169. if (!block->channel_in_cpl[ch])
  1170. frame_bits += 6;
  1171. frame_bits += 2;
  1172. }
  1173. }
  1174. /* coupling exponent strategy */
  1175. if (!s->eac3 && block->cpl_in_use)
  1176. frame_bits += 2;
  1177. /* snr offsets and fast gain codes */
  1178. if (!s->eac3) {
  1179. frame_bits++;
  1180. if (block->new_snr_offsets)
  1181. frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
  1182. }
  1183. /* coupling leak info */
  1184. if (block->cpl_in_use) {
  1185. if (!s->eac3 || block->new_cpl_leak != 2)
  1186. frame_bits++;
  1187. if (block->new_cpl_leak)
  1188. frame_bits += 3 + 3;
  1189. }
  1190. }
  1191. s->frame_bits = s->frame_bits_fixed + frame_bits;
  1192. }
  1193. /**
  1194. * Calculate masking curve based on the final exponents.
  1195. * Also calculate the power spectral densities to use in future calculations.
  1196. */
  1197. static void bit_alloc_masking(AC3EncodeContext *s)
  1198. {
  1199. int blk, ch;
  1200. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1201. AC3Block *block = &s->blocks[blk];
  1202. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1203. /* We only need psd and mask for calculating bap.
  1204. Since we currently do not calculate bap when exponent
  1205. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  1206. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1207. ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
  1208. block->end_freq[ch], block->psd[ch],
  1209. block->band_psd[ch]);
  1210. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  1211. s->start_freq[ch], block->end_freq[ch],
  1212. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  1213. ch == s->lfe_channel,
  1214. DBA_NONE, 0, NULL, NULL, NULL,
  1215. block->mask[ch]);
  1216. }
  1217. }
  1218. }
  1219. }
  1220. /**
  1221. * Ensure that bap for each block and channel point to the current bap_buffer.
  1222. * They may have been switched during the bit allocation search.
  1223. */
  1224. static void reset_block_bap(AC3EncodeContext *s)
  1225. {
  1226. int blk, ch;
  1227. uint8_t *ref_bap;
  1228. if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
  1229. return;
  1230. ref_bap = s->bap_buffer;
  1231. for (ch = 0; ch <= s->channels; ch++) {
  1232. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1233. s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
  1234. ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
  1235. }
  1236. s->ref_bap_set = 1;
  1237. }
  1238. /**
  1239. * Initialize mantissa counts.
  1240. * These are set so that they are padded to the next whole group size when bits
  1241. * are counted in compute_mantissa_size.
  1242. */
  1243. static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
  1244. {
  1245. int blk;
  1246. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1247. memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
  1248. mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
  1249. mant_cnt[blk][4] = 1;
  1250. }
  1251. }
  1252. /**
  1253. * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
  1254. * range.
  1255. */
  1256. static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
  1257. uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
  1258. int start, int end)
  1259. {
  1260. int blk;
  1261. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1262. AC3Block *block = &s->blocks[blk];
  1263. if (ch == CPL_CH && !block->cpl_in_use)
  1264. continue;
  1265. s->ac3dsp.update_bap_counts(mant_cnt[blk],
  1266. s->ref_bap[ch][blk] + start,
  1267. FFMIN(end, block->end_freq[ch]) - start);
  1268. }
  1269. }
  1270. /**
  1271. * Count the number of mantissa bits in the frame based on the bap values.
  1272. */
  1273. static int count_mantissa_bits(AC3EncodeContext *s)
  1274. {
  1275. int ch, max_end_freq;
  1276. LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
  1277. count_mantissa_bits_init(mant_cnt);
  1278. max_end_freq = s->bandwidth_code * 3 + 73;
  1279. for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
  1280. count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
  1281. max_end_freq);
  1282. return s->ac3dsp.compute_mantissa_size(mant_cnt);
  1283. }
  1284. /**
  1285. * Run the bit allocation with a given SNR offset.
  1286. * This calculates the bit allocation pointers that will be used to determine
  1287. * the quantization of each mantissa.
  1288. * @return the number of bits needed for mantissas if the given SNR offset is
  1289. * is used.
  1290. */
  1291. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  1292. {
  1293. int blk, ch;
  1294. snr_offset = (snr_offset - 240) << 2;
  1295. reset_block_bap(s);
  1296. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1297. AC3Block *block = &s->blocks[blk];
  1298. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1299. /* Currently the only bit allocation parameters which vary across
  1300. blocks within a frame are the exponent values. We can take
  1301. advantage of that by reusing the bit allocation pointers
  1302. whenever we reuse exponents. */
  1303. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1304. s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
  1305. s->start_freq[ch], block->end_freq[ch],
  1306. snr_offset, s->bit_alloc.floor,
  1307. ff_ac3_bap_tab, s->ref_bap[ch][blk]);
  1308. }
  1309. }
  1310. }
  1311. return count_mantissa_bits(s);
  1312. }
  1313. /**
  1314. * Constant bitrate bit allocation search.
  1315. * Find the largest SNR offset that will allow data to fit in the frame.
  1316. */
  1317. static int cbr_bit_allocation(AC3EncodeContext *s)
  1318. {
  1319. int ch;
  1320. int bits_left;
  1321. int snr_offset, snr_incr;
  1322. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  1323. if (bits_left < 0)
  1324. return AVERROR(EINVAL);
  1325. snr_offset = s->coarse_snr_offset << 4;
  1326. /* if previous frame SNR offset was 1023, check if current frame can also
  1327. use SNR offset of 1023. if so, skip the search. */
  1328. if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
  1329. if (bit_alloc(s, 1023) <= bits_left)
  1330. return 0;
  1331. }
  1332. while (snr_offset >= 0 &&
  1333. bit_alloc(s, snr_offset) > bits_left) {
  1334. snr_offset -= 64;
  1335. }
  1336. if (snr_offset < 0)
  1337. return AVERROR(EINVAL);
  1338. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1339. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  1340. while (snr_offset + snr_incr <= 1023 &&
  1341. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  1342. snr_offset += snr_incr;
  1343. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1344. }
  1345. }
  1346. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1347. reset_block_bap(s);
  1348. s->coarse_snr_offset = snr_offset >> 4;
  1349. for (ch = !s->cpl_on; ch <= s->channels; ch++)
  1350. s->fine_snr_offset[ch] = snr_offset & 0xF;
  1351. return 0;
  1352. }
  1353. /**
  1354. * Downgrade exponent strategies to reduce the bits used by the exponents.
  1355. * This is a fallback for when bit allocation fails with the normal exponent
  1356. * strategies. Each time this function is run it only downgrades the
  1357. * strategy in 1 channel of 1 block.
  1358. * @return non-zero if downgrade was unsuccessful
  1359. */
  1360. static int downgrade_exponents(AC3EncodeContext *s)
  1361. {
  1362. int ch, blk;
  1363. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1364. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1365. if (s->exp_strategy[ch][blk] == EXP_D15) {
  1366. s->exp_strategy[ch][blk] = EXP_D25;
  1367. return 0;
  1368. }
  1369. }
  1370. }
  1371. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1372. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1373. if (s->exp_strategy[ch][blk] == EXP_D25) {
  1374. s->exp_strategy[ch][blk] = EXP_D45;
  1375. return 0;
  1376. }
  1377. }
  1378. }
  1379. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  1380. the block number > 0 */
  1381. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  1382. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1383. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  1384. s->exp_strategy[ch][blk] = EXP_REUSE;
  1385. return 0;
  1386. }
  1387. }
  1388. }
  1389. return -1;
  1390. }
  1391. /**
  1392. * Perform bit allocation search.
  1393. * Finds the SNR offset value that maximizes quality and fits in the specified
  1394. * frame size. Output is the SNR offset and a set of bit allocation pointers
  1395. * used to quantize the mantissas.
  1396. */
  1397. static int compute_bit_allocation(AC3EncodeContext *s)
  1398. {
  1399. int ret;
  1400. count_frame_bits(s);
  1401. bit_alloc_masking(s);
  1402. ret = cbr_bit_allocation(s);
  1403. while (ret) {
  1404. /* fallback 1: disable channel coupling */
  1405. if (s->cpl_on) {
  1406. s->cpl_on = 0;
  1407. compute_coupling_strategy(s);
  1408. compute_rematrixing_strategy(s);
  1409. apply_rematrixing(s);
  1410. process_exponents(s);
  1411. ret = compute_bit_allocation(s);
  1412. continue;
  1413. }
  1414. /* fallback 2: downgrade exponents */
  1415. if (!downgrade_exponents(s)) {
  1416. extract_exponents(s);
  1417. encode_exponents(s);
  1418. group_exponents(s);
  1419. ret = compute_bit_allocation(s);
  1420. continue;
  1421. }
  1422. /* fallbacks were not enough... */
  1423. break;
  1424. }
  1425. return ret;
  1426. }
  1427. /**
  1428. * Symmetric quantization on 'levels' levels.
  1429. */
  1430. static inline int sym_quant(int c, int e, int levels)
  1431. {
  1432. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  1433. av_assert2(v >= 0 && v < levels);
  1434. return v;
  1435. }
  1436. /**
  1437. * Asymmetric quantization on 2^qbits levels.
  1438. */
  1439. static inline int asym_quant(int c, int e, int qbits)
  1440. {
  1441. int lshift, m, v;
  1442. lshift = e + qbits - 24;
  1443. if (lshift >= 0)
  1444. v = c << lshift;
  1445. else
  1446. v = c >> (-lshift);
  1447. /* rounding */
  1448. v = (v + 1) >> 1;
  1449. m = (1 << (qbits-1));
  1450. if (v >= m)
  1451. v = m - 1;
  1452. av_assert2(v >= -m);
  1453. return v & ((1 << qbits)-1);
  1454. }
  1455. /**
  1456. * Quantize a set of mantissas for a single channel in a single block.
  1457. */
  1458. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1459. uint8_t *exp, uint8_t *bap,
  1460. uint16_t *qmant, int start_freq,
  1461. int end_freq)
  1462. {
  1463. int i;
  1464. for (i = start_freq; i < end_freq; i++) {
  1465. int v;
  1466. int c = fixed_coef[i];
  1467. int e = exp[i];
  1468. int b = bap[i];
  1469. switch (b) {
  1470. case 0:
  1471. v = 0;
  1472. break;
  1473. case 1:
  1474. v = sym_quant(c, e, 3);
  1475. switch (s->mant1_cnt) {
  1476. case 0:
  1477. s->qmant1_ptr = &qmant[i];
  1478. v = 9 * v;
  1479. s->mant1_cnt = 1;
  1480. break;
  1481. case 1:
  1482. *s->qmant1_ptr += 3 * v;
  1483. s->mant1_cnt = 2;
  1484. v = 128;
  1485. break;
  1486. default:
  1487. *s->qmant1_ptr += v;
  1488. s->mant1_cnt = 0;
  1489. v = 128;
  1490. break;
  1491. }
  1492. break;
  1493. case 2:
  1494. v = sym_quant(c, e, 5);
  1495. switch (s->mant2_cnt) {
  1496. case 0:
  1497. s->qmant2_ptr = &qmant[i];
  1498. v = 25 * v;
  1499. s->mant2_cnt = 1;
  1500. break;
  1501. case 1:
  1502. *s->qmant2_ptr += 5 * v;
  1503. s->mant2_cnt = 2;
  1504. v = 128;
  1505. break;
  1506. default:
  1507. *s->qmant2_ptr += v;
  1508. s->mant2_cnt = 0;
  1509. v = 128;
  1510. break;
  1511. }
  1512. break;
  1513. case 3:
  1514. v = sym_quant(c, e, 7);
  1515. break;
  1516. case 4:
  1517. v = sym_quant(c, e, 11);
  1518. switch (s->mant4_cnt) {
  1519. case 0:
  1520. s->qmant4_ptr = &qmant[i];
  1521. v = 11 * v;
  1522. s->mant4_cnt = 1;
  1523. break;
  1524. default:
  1525. *s->qmant4_ptr += v;
  1526. s->mant4_cnt = 0;
  1527. v = 128;
  1528. break;
  1529. }
  1530. break;
  1531. case 5:
  1532. v = sym_quant(c, e, 15);
  1533. break;
  1534. case 14:
  1535. v = asym_quant(c, e, 14);
  1536. break;
  1537. case 15:
  1538. v = asym_quant(c, e, 16);
  1539. break;
  1540. default:
  1541. v = asym_quant(c, e, b - 1);
  1542. break;
  1543. }
  1544. qmant[i] = v;
  1545. }
  1546. }
  1547. /**
  1548. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1549. */
  1550. static void quantize_mantissas(AC3EncodeContext *s)
  1551. {
  1552. int blk, ch, ch0=0, got_cpl;
  1553. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1554. AC3Block *block = &s->blocks[blk];
  1555. AC3Mant m = { 0 };
  1556. got_cpl = !block->cpl_in_use;
  1557. for (ch = 1; ch <= s->channels; ch++) {
  1558. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1559. ch0 = ch - 1;
  1560. ch = CPL_CH;
  1561. got_cpl = 1;
  1562. }
  1563. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1564. s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
  1565. s->ref_bap[ch][blk], block->qmant[ch],
  1566. s->start_freq[ch], block->end_freq[ch]);
  1567. if (ch == CPL_CH)
  1568. ch = ch0;
  1569. }
  1570. }
  1571. }
  1572. /**
  1573. * Write the AC-3 frame header to the output bitstream.
  1574. */
  1575. static void ac3_output_frame_header(AC3EncodeContext *s)
  1576. {
  1577. AC3EncOptions *opt = &s->options;
  1578. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1579. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1580. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1581. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1582. put_bits(&s->pb, 5, s->bitstream_id);
  1583. put_bits(&s->pb, 3, s->bitstream_mode);
  1584. put_bits(&s->pb, 3, s->channel_mode);
  1585. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1586. put_bits(&s->pb, 2, s->center_mix_level);
  1587. if (s->channel_mode & 0x04)
  1588. put_bits(&s->pb, 2, s->surround_mix_level);
  1589. if (s->channel_mode == AC3_CHMODE_STEREO)
  1590. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1591. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1592. put_bits(&s->pb, 5, -opt->dialogue_level);
  1593. put_bits(&s->pb, 1, 0); /* no compression control word */
  1594. put_bits(&s->pb, 1, 0); /* no lang code */
  1595. put_bits(&s->pb, 1, opt->audio_production_info);
  1596. if (opt->audio_production_info) {
  1597. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1598. put_bits(&s->pb, 2, opt->room_type);
  1599. }
  1600. put_bits(&s->pb, 1, opt->copyright);
  1601. put_bits(&s->pb, 1, opt->original);
  1602. if (s->bitstream_id == 6) {
  1603. /* alternate bit stream syntax */
  1604. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1605. if (opt->extended_bsi_1) {
  1606. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1607. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1608. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1609. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1610. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1611. }
  1612. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1613. if (opt->extended_bsi_2) {
  1614. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1615. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1616. put_bits(&s->pb, 1, opt->ad_converter_type);
  1617. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1618. }
  1619. } else {
  1620. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1621. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1622. }
  1623. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1624. }
  1625. /**
  1626. * Write the E-AC-3 frame header to the output bitstream.
  1627. */
  1628. static void eac3_output_frame_header(AC3EncodeContext *s)
  1629. {
  1630. int blk, ch;
  1631. AC3EncOptions *opt = &s->options;
  1632. put_bits(&s->pb, 16, 0x0b77); /* sync word */
  1633. /* BSI header */
  1634. put_bits(&s->pb, 2, 0); /* stream type = independent */
  1635. put_bits(&s->pb, 3, 0); /* substream id = 0 */
  1636. put_bits(&s->pb, 11, (s->frame_size / 2) - 1); /* frame size */
  1637. if (s->bit_alloc.sr_shift) {
  1638. put_bits(&s->pb, 2, 0x3); /* fscod2 */
  1639. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1640. } else {
  1641. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1642. put_bits(&s->pb, 2, 0x3); /* number of blocks = 6 */
  1643. }
  1644. put_bits(&s->pb, 3, s->channel_mode); /* audio coding mode */
  1645. put_bits(&s->pb, 1, s->lfe_on); /* LFE channel indicator */
  1646. put_bits(&s->pb, 5, s->bitstream_id); /* bitstream id (EAC3=16) */
  1647. put_bits(&s->pb, 5, -opt->dialogue_level); /* dialogue normalization level */
  1648. put_bits(&s->pb, 1, 0); /* no compression gain */
  1649. put_bits(&s->pb, 1, 0); /* no mixing metadata */
  1650. /* TODO: mixing metadata */
  1651. put_bits(&s->pb, 1, 0); /* no info metadata */
  1652. /* TODO: info metadata */
  1653. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1654. /* frame header */
  1655. put_bits(&s->pb, 1, 1); /* exponent strategy syntax = each block */
  1656. put_bits(&s->pb, 1, 0); /* aht enabled = no */
  1657. put_bits(&s->pb, 2, 0); /* snr offset strategy = 1 */
  1658. put_bits(&s->pb, 1, 0); /* transient pre-noise processing enabled = no */
  1659. put_bits(&s->pb, 1, 0); /* block switch syntax enabled = no */
  1660. put_bits(&s->pb, 1, 0); /* dither flag syntax enabled = no */
  1661. put_bits(&s->pb, 1, 0); /* bit allocation model syntax enabled = no */
  1662. put_bits(&s->pb, 1, 0); /* fast gain codes enabled = no */
  1663. put_bits(&s->pb, 1, 0); /* dba syntax enabled = no */
  1664. put_bits(&s->pb, 1, 0); /* skip field syntax enabled = no */
  1665. put_bits(&s->pb, 1, 0); /* spx enabled = no */
  1666. /* coupling strategy use flags */
  1667. if (s->channel_mode > AC3_CHMODE_MONO) {
  1668. put_bits(&s->pb, 1, s->blocks[0].cpl_in_use);
  1669. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1670. AC3Block *block = &s->blocks[blk];
  1671. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1672. if (block->new_cpl_strategy)
  1673. put_bits(&s->pb, 1, block->cpl_in_use);
  1674. }
  1675. }
  1676. /* exponent strategy */
  1677. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1678. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++)
  1679. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1680. if (s->lfe_on) {
  1681. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1682. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1683. }
  1684. /* E-AC-3 to AC-3 converter exponent strategy (unfortunately not optional...) */
  1685. for (ch = 1; ch <= s->fbw_channels; ch++)
  1686. put_bits(&s->pb, 5, 0);
  1687. /* snr offsets */
  1688. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1689. put_bits(&s->pb, 4, s->fine_snr_offset[1]);
  1690. /* block start info */
  1691. put_bits(&s->pb, 1, 0);
  1692. }
  1693. /**
  1694. * Write one audio block to the output bitstream.
  1695. */
  1696. static void output_audio_block(AC3EncodeContext *s, int blk)
  1697. {
  1698. int ch, i, baie, bnd, got_cpl;
  1699. int av_uninit(ch0);
  1700. AC3Block *block = &s->blocks[blk];
  1701. /* block switching */
  1702. if (!s->eac3) {
  1703. for (ch = 0; ch < s->fbw_channels; ch++)
  1704. put_bits(&s->pb, 1, 0);
  1705. }
  1706. /* dither flags */
  1707. if (!s->eac3) {
  1708. for (ch = 0; ch < s->fbw_channels; ch++)
  1709. put_bits(&s->pb, 1, 1);
  1710. }
  1711. /* dynamic range codes */
  1712. put_bits(&s->pb, 1, 0);
  1713. /* spectral extension */
  1714. if (s->eac3)
  1715. put_bits(&s->pb, 1, 0);
  1716. /* channel coupling */
  1717. if (!s->eac3)
  1718. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1719. if (block->new_cpl_strategy) {
  1720. if (!s->eac3)
  1721. put_bits(&s->pb, 1, block->cpl_in_use);
  1722. if (block->cpl_in_use) {
  1723. int start_sub, end_sub;
  1724. if (s->eac3)
  1725. put_bits(&s->pb, 1, 0); /* enhanced coupling */
  1726. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
  1727. for (ch = 1; ch <= s->fbw_channels; ch++)
  1728. put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
  1729. }
  1730. if (s->channel_mode == AC3_CHMODE_STEREO)
  1731. put_bits(&s->pb, 1, 0); /* phase flags in use */
  1732. start_sub = (s->start_freq[CPL_CH] - 37) / 12;
  1733. end_sub = (s->cpl_end_freq - 37) / 12;
  1734. put_bits(&s->pb, 4, start_sub);
  1735. put_bits(&s->pb, 4, end_sub - 3);
  1736. /* coupling band structure */
  1737. if (s->eac3) {
  1738. put_bits(&s->pb, 1, 0); /* use default */
  1739. } else {
  1740. for (bnd = start_sub+1; bnd < end_sub; bnd++)
  1741. put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
  1742. }
  1743. }
  1744. }
  1745. /* coupling coordinates */
  1746. if (block->cpl_in_use) {
  1747. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1748. if (block->channel_in_cpl[ch]) {
  1749. if (!s->eac3 || block->new_cpl_coords != 2)
  1750. put_bits(&s->pb, 1, block->new_cpl_coords);
  1751. if (block->new_cpl_coords) {
  1752. put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
  1753. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  1754. put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
  1755. put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
  1756. }
  1757. }
  1758. }
  1759. }
  1760. }
  1761. /* stereo rematrixing */
  1762. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1763. if (!s->eac3 || blk > 0)
  1764. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1765. if (block->new_rematrixing_strategy) {
  1766. /* rematrixing flags */
  1767. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
  1768. put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
  1769. }
  1770. }
  1771. /* exponent strategy */
  1772. if (!s->eac3) {
  1773. for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
  1774. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1775. if (s->lfe_on)
  1776. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1777. }
  1778. /* bandwidth */
  1779. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1780. if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
  1781. put_bits(&s->pb, 6, s->bandwidth_code);
  1782. }
  1783. /* exponents */
  1784. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1785. int nb_groups;
  1786. int cpl = (ch == CPL_CH);
  1787. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1788. continue;
  1789. /* DC exponent */
  1790. put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
  1791. /* exponent groups */
  1792. nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
  1793. for (i = 1; i <= nb_groups; i++)
  1794. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1795. /* gain range info */
  1796. if (ch != s->lfe_channel && !cpl)
  1797. put_bits(&s->pb, 2, 0);
  1798. }
  1799. /* bit allocation info */
  1800. if (!s->eac3) {
  1801. baie = (blk == 0);
  1802. put_bits(&s->pb, 1, baie);
  1803. if (baie) {
  1804. put_bits(&s->pb, 2, s->slow_decay_code);
  1805. put_bits(&s->pb, 2, s->fast_decay_code);
  1806. put_bits(&s->pb, 2, s->slow_gain_code);
  1807. put_bits(&s->pb, 2, s->db_per_bit_code);
  1808. put_bits(&s->pb, 3, s->floor_code);
  1809. }
  1810. }
  1811. /* snr offset */
  1812. if (!s->eac3) {
  1813. put_bits(&s->pb, 1, block->new_snr_offsets);
  1814. if (block->new_snr_offsets) {
  1815. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1816. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1817. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1818. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1819. }
  1820. }
  1821. } else {
  1822. put_bits(&s->pb, 1, 0); /* no converter snr offset */
  1823. }
  1824. /* coupling leak */
  1825. if (block->cpl_in_use) {
  1826. if (!s->eac3 || block->new_cpl_leak != 2)
  1827. put_bits(&s->pb, 1, block->new_cpl_leak);
  1828. if (block->new_cpl_leak) {
  1829. put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
  1830. put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
  1831. }
  1832. }
  1833. if (!s->eac3) {
  1834. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1835. put_bits(&s->pb, 1, 0); /* no data to skip */
  1836. }
  1837. /* mantissas */
  1838. got_cpl = !block->cpl_in_use;
  1839. for (ch = 1; ch <= s->channels; ch++) {
  1840. int b, q;
  1841. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1842. ch0 = ch - 1;
  1843. ch = CPL_CH;
  1844. got_cpl = 1;
  1845. }
  1846. for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
  1847. q = block->qmant[ch][i];
  1848. b = s->ref_bap[ch][blk][i];
  1849. switch (b) {
  1850. case 0: break;
  1851. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1852. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1853. case 3: put_bits(&s->pb, 3, q); break;
  1854. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1855. case 14: put_bits(&s->pb, 14, q); break;
  1856. case 15: put_bits(&s->pb, 16, q); break;
  1857. default: put_bits(&s->pb, b-1, q); break;
  1858. }
  1859. }
  1860. if (ch == CPL_CH)
  1861. ch = ch0;
  1862. }
  1863. }
  1864. /** CRC-16 Polynomial */
  1865. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1866. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1867. {
  1868. unsigned int c;
  1869. c = 0;
  1870. while (a) {
  1871. if (a & 1)
  1872. c ^= b;
  1873. a = a >> 1;
  1874. b = b << 1;
  1875. if (b & (1 << 16))
  1876. b ^= poly;
  1877. }
  1878. return c;
  1879. }
  1880. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1881. {
  1882. unsigned int r;
  1883. r = 1;
  1884. while (n) {
  1885. if (n & 1)
  1886. r = mul_poly(r, a, poly);
  1887. a = mul_poly(a, a, poly);
  1888. n >>= 1;
  1889. }
  1890. return r;
  1891. }
  1892. /**
  1893. * Fill the end of the frame with 0's and compute the two CRCs.
  1894. */
  1895. static void output_frame_end(AC3EncodeContext *s)
  1896. {
  1897. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1898. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1899. uint8_t *frame;
  1900. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1901. /* pad the remainder of the frame with zeros */
  1902. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1903. flush_put_bits(&s->pb);
  1904. frame = s->pb.buf;
  1905. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1906. av_assert2(pad_bytes >= 0);
  1907. if (pad_bytes > 0)
  1908. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1909. if (s->eac3) {
  1910. /* compute crc2 */
  1911. crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
  1912. } else {
  1913. /* compute crc1 */
  1914. /* this is not so easy because it is at the beginning of the data... */
  1915. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1916. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1917. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1918. AV_WB16(frame + 2, crc1);
  1919. /* compute crc2 */
  1920. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1921. s->frame_size - frame_size_58 - 3);
  1922. }
  1923. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1924. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1925. if (crc2 == 0x770B) {
  1926. frame[s->frame_size - 3] ^= 0x1;
  1927. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1928. }
  1929. crc2 = av_bswap16(crc2);
  1930. AV_WB16(frame + s->frame_size - 2, crc2);
  1931. }
  1932. /**
  1933. * Write the frame to the output bitstream.
  1934. */
  1935. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1936. {
  1937. int blk;
  1938. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1939. if (s->eac3)
  1940. eac3_output_frame_header(s);
  1941. else
  1942. ac3_output_frame_header(s);
  1943. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1944. output_audio_block(s, blk);
  1945. output_frame_end(s);
  1946. }
  1947. static void dprint_options(AVCodecContext *avctx)
  1948. {
  1949. #ifdef DEBUG
  1950. AC3EncodeContext *s = avctx->priv_data;
  1951. AC3EncOptions *opt = &s->options;
  1952. char strbuf[32];
  1953. switch (s->bitstream_id) {
  1954. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1955. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1956. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1957. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
  1958. case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
  1959. default: snprintf(strbuf, 32, "ERROR");
  1960. }
  1961. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1962. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1963. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1964. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1965. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1966. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1967. if (s->cutoff)
  1968. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1969. av_dlog(avctx, "per_frame_metadata: %s\n",
  1970. opt->allow_per_frame_metadata?"on":"off");
  1971. if (s->has_center)
  1972. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1973. s->center_mix_level);
  1974. else
  1975. av_dlog(avctx, "center_mixlev: {not written}\n");
  1976. if (s->has_surround)
  1977. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1978. s->surround_mix_level);
  1979. else
  1980. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1981. if (opt->audio_production_info) {
  1982. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1983. switch (opt->room_type) {
  1984. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1985. case 1: av_strlcpy(strbuf, "large", 32); break;
  1986. case 2: av_strlcpy(strbuf, "small", 32); break;
  1987. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1988. }
  1989. av_dlog(avctx, "room_type: %s\n", strbuf);
  1990. } else {
  1991. av_dlog(avctx, "mixing_level: {not written}\n");
  1992. av_dlog(avctx, "room_type: {not written}\n");
  1993. }
  1994. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1995. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1996. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1997. switch (opt->dolby_surround_mode) {
  1998. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1999. case 1: av_strlcpy(strbuf, "on", 32); break;
  2000. case 2: av_strlcpy(strbuf, "off", 32); break;
  2001. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  2002. }
  2003. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  2004. } else {
  2005. av_dlog(avctx, "dsur_mode: {not written}\n");
  2006. }
  2007. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  2008. if (s->bitstream_id == 6) {
  2009. if (opt->extended_bsi_1) {
  2010. switch (opt->preferred_stereo_downmix) {
  2011. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2012. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  2013. case 2: av_strlcpy(strbuf, "loro", 32); break;
  2014. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  2015. }
  2016. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  2017. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  2018. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  2019. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  2020. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  2021. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  2022. opt->loro_center_mix_level, s->loro_center_mix_level);
  2023. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  2024. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  2025. } else {
  2026. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  2027. }
  2028. if (opt->extended_bsi_2) {
  2029. switch (opt->dolby_surround_ex_mode) {
  2030. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2031. case 1: av_strlcpy(strbuf, "on", 32); break;
  2032. case 2: av_strlcpy(strbuf, "off", 32); break;
  2033. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  2034. }
  2035. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  2036. switch (opt->dolby_headphone_mode) {
  2037. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2038. case 1: av_strlcpy(strbuf, "on", 32); break;
  2039. case 2: av_strlcpy(strbuf, "off", 32); break;
  2040. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  2041. }
  2042. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  2043. switch (opt->ad_converter_type) {
  2044. case 0: av_strlcpy(strbuf, "standard", 32); break;
  2045. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  2046. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  2047. }
  2048. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  2049. } else {
  2050. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  2051. }
  2052. }
  2053. #endif
  2054. }
  2055. #define FLT_OPTION_THRESHOLD 0.01
  2056. static int validate_float_option(float v, const float *v_list, int v_list_size)
  2057. {
  2058. int i;
  2059. for (i = 0; i < v_list_size; i++) {
  2060. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  2061. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  2062. break;
  2063. }
  2064. if (i == v_list_size)
  2065. return -1;
  2066. return i;
  2067. }
  2068. static void validate_mix_level(void *log_ctx, const char *opt_name,
  2069. float *opt_param, const float *list,
  2070. int list_size, int default_value, int min_value,
  2071. int *ctx_param)
  2072. {
  2073. int mixlev = validate_float_option(*opt_param, list, list_size);
  2074. if (mixlev < min_value) {
  2075. mixlev = default_value;
  2076. if (*opt_param >= 0.0) {
  2077. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  2078. "default value: %0.3f\n", opt_name, list[mixlev]);
  2079. }
  2080. }
  2081. *opt_param = list[mixlev];
  2082. *ctx_param = mixlev;
  2083. }
  2084. /**
  2085. * Validate metadata options as set by AVOption system.
  2086. * These values can optionally be changed per-frame.
  2087. */
  2088. static int validate_metadata(AVCodecContext *avctx)
  2089. {
  2090. AC3EncodeContext *s = avctx->priv_data;
  2091. AC3EncOptions *opt = &s->options;
  2092. /* validate mixing levels */
  2093. if (s->has_center) {
  2094. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  2095. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  2096. &s->center_mix_level);
  2097. }
  2098. if (s->has_surround) {
  2099. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  2100. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  2101. &s->surround_mix_level);
  2102. }
  2103. /* set audio production info flag */
  2104. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  2105. if (opt->mixing_level < 0) {
  2106. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  2107. "room_type is set\n");
  2108. return AVERROR(EINVAL);
  2109. }
  2110. if (opt->mixing_level < 80) {
  2111. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  2112. "80dB and 111dB\n");
  2113. return AVERROR(EINVAL);
  2114. }
  2115. /* default room type */
  2116. if (opt->room_type < 0)
  2117. opt->room_type = 0;
  2118. opt->audio_production_info = 1;
  2119. } else {
  2120. opt->audio_production_info = 0;
  2121. }
  2122. /* set extended bsi 1 flag */
  2123. if ((s->has_center || s->has_surround) &&
  2124. (opt->preferred_stereo_downmix >= 0 ||
  2125. opt->ltrt_center_mix_level >= 0 ||
  2126. opt->ltrt_surround_mix_level >= 0 ||
  2127. opt->loro_center_mix_level >= 0 ||
  2128. opt->loro_surround_mix_level >= 0)) {
  2129. /* default preferred stereo downmix */
  2130. if (opt->preferred_stereo_downmix < 0)
  2131. opt->preferred_stereo_downmix = 0;
  2132. /* validate Lt/Rt center mix level */
  2133. validate_mix_level(avctx, "ltrt_center_mix_level",
  2134. &opt->ltrt_center_mix_level, extmixlev_options,
  2135. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2136. &s->ltrt_center_mix_level);
  2137. /* validate Lt/Rt surround mix level */
  2138. validate_mix_level(avctx, "ltrt_surround_mix_level",
  2139. &opt->ltrt_surround_mix_level, extmixlev_options,
  2140. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2141. &s->ltrt_surround_mix_level);
  2142. /* validate Lo/Ro center mix level */
  2143. validate_mix_level(avctx, "loro_center_mix_level",
  2144. &opt->loro_center_mix_level, extmixlev_options,
  2145. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2146. &s->loro_center_mix_level);
  2147. /* validate Lo/Ro surround mix level */
  2148. validate_mix_level(avctx, "loro_surround_mix_level",
  2149. &opt->loro_surround_mix_level, extmixlev_options,
  2150. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2151. &s->loro_surround_mix_level);
  2152. opt->extended_bsi_1 = 1;
  2153. } else {
  2154. opt->extended_bsi_1 = 0;
  2155. }
  2156. /* set extended bsi 2 flag */
  2157. if (opt->dolby_surround_ex_mode >= 0 ||
  2158. opt->dolby_headphone_mode >= 0 ||
  2159. opt->ad_converter_type >= 0) {
  2160. /* default dolby surround ex mode */
  2161. if (opt->dolby_surround_ex_mode < 0)
  2162. opt->dolby_surround_ex_mode = 0;
  2163. /* default dolby headphone mode */
  2164. if (opt->dolby_headphone_mode < 0)
  2165. opt->dolby_headphone_mode = 0;
  2166. /* default A/D converter type */
  2167. if (opt->ad_converter_type < 0)
  2168. opt->ad_converter_type = 0;
  2169. opt->extended_bsi_2 = 1;
  2170. } else {
  2171. opt->extended_bsi_2 = 0;
  2172. }
  2173. /* set bitstream id for alternate bitstream syntax */
  2174. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  2175. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  2176. static int warn_once = 1;
  2177. if (warn_once) {
  2178. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  2179. "not compatible with reduced samplerates. writing of "
  2180. "extended bitstream information will be disabled.\n");
  2181. warn_once = 0;
  2182. }
  2183. } else {
  2184. s->bitstream_id = 6;
  2185. }
  2186. }
  2187. return 0;
  2188. }
  2189. /**
  2190. * Encode a single AC-3 frame.
  2191. */
  2192. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  2193. int buf_size, void *data)
  2194. {
  2195. AC3EncodeContext *s = avctx->priv_data;
  2196. const SampleType *samples = data;
  2197. int ret;
  2198. if (!s->eac3 && s->options.allow_per_frame_metadata) {
  2199. ret = validate_metadata(avctx);
  2200. if (ret)
  2201. return ret;
  2202. }
  2203. if (s->bit_alloc.sr_code == 1 || s->eac3)
  2204. adjust_frame_size(s);
  2205. deinterleave_input_samples(s, samples);
  2206. apply_mdct(s);
  2207. scale_coefficients(s);
  2208. s->cpl_on = s->cpl_enabled;
  2209. compute_coupling_strategy(s);
  2210. if (s->cpl_on)
  2211. apply_channel_coupling(s);
  2212. compute_rematrixing_strategy(s);
  2213. apply_rematrixing(s);
  2214. process_exponents(s);
  2215. ret = compute_bit_allocation(s);
  2216. if (ret) {
  2217. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  2218. return ret;
  2219. }
  2220. quantize_mantissas(s);
  2221. output_frame(s, frame);
  2222. return s->frame_size;
  2223. }
  2224. /**
  2225. * Finalize encoding and free any memory allocated by the encoder.
  2226. */
  2227. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  2228. {
  2229. int blk, ch;
  2230. AC3EncodeContext *s = avctx->priv_data;
  2231. for (ch = 0; ch < s->channels; ch++)
  2232. av_freep(&s->planar_samples[ch]);
  2233. av_freep(&s->planar_samples);
  2234. av_freep(&s->bap_buffer);
  2235. av_freep(&s->bap1_buffer);
  2236. av_freep(&s->mdct_coef_buffer);
  2237. av_freep(&s->fixed_coef_buffer);
  2238. av_freep(&s->exp_buffer);
  2239. av_freep(&s->grouped_exp_buffer);
  2240. av_freep(&s->psd_buffer);
  2241. av_freep(&s->band_psd_buffer);
  2242. av_freep(&s->mask_buffer);
  2243. av_freep(&s->qmant_buffer);
  2244. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2245. AC3Block *block = &s->blocks[blk];
  2246. av_freep(&block->mdct_coef);
  2247. av_freep(&block->fixed_coef);
  2248. av_freep(&block->exp);
  2249. av_freep(&block->grouped_exp);
  2250. av_freep(&block->psd);
  2251. av_freep(&block->band_psd);
  2252. av_freep(&block->mask);
  2253. av_freep(&block->qmant);
  2254. }
  2255. mdct_end(&s->mdct);
  2256. av_freep(&avctx->coded_frame);
  2257. return 0;
  2258. }
  2259. /**
  2260. * Set channel information during initialization.
  2261. */
  2262. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  2263. int64_t *channel_layout)
  2264. {
  2265. int ch_layout;
  2266. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  2267. return AVERROR(EINVAL);
  2268. if ((uint64_t)*channel_layout > 0x7FF)
  2269. return AVERROR(EINVAL);
  2270. ch_layout = *channel_layout;
  2271. if (!ch_layout)
  2272. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  2273. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  2274. s->channels = channels;
  2275. s->fbw_channels = channels - s->lfe_on;
  2276. s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
  2277. if (s->lfe_on)
  2278. ch_layout -= AV_CH_LOW_FREQUENCY;
  2279. switch (ch_layout) {
  2280. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  2281. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  2282. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  2283. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  2284. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  2285. case AV_CH_LAYOUT_QUAD:
  2286. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  2287. case AV_CH_LAYOUT_5POINT0:
  2288. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  2289. default:
  2290. return AVERROR(EINVAL);
  2291. }
  2292. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  2293. s->has_surround = s->channel_mode & 0x04;
  2294. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  2295. *channel_layout = ch_layout;
  2296. if (s->lfe_on)
  2297. *channel_layout |= AV_CH_LOW_FREQUENCY;
  2298. return 0;
  2299. }
  2300. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  2301. {
  2302. int i, ret, max_sr;
  2303. /* validate channel layout */
  2304. if (!avctx->channel_layout) {
  2305. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  2306. "encoder will guess the layout, but it "
  2307. "might be incorrect.\n");
  2308. }
  2309. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  2310. if (ret) {
  2311. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  2312. return ret;
  2313. }
  2314. /* validate sample rate */
  2315. /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
  2316. decoder that supports half sample rate so we can validate that
  2317. the generated files are correct. */
  2318. max_sr = s->eac3 ? 2 : 8;
  2319. for (i = 0; i <= max_sr; i++) {
  2320. if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
  2321. break;
  2322. }
  2323. if (i > max_sr) {
  2324. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  2325. return AVERROR(EINVAL);
  2326. }
  2327. s->sample_rate = avctx->sample_rate;
  2328. s->bit_alloc.sr_shift = i / 3;
  2329. s->bit_alloc.sr_code = i % 3;
  2330. s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
  2331. /* validate bit rate */
  2332. if (s->eac3) {
  2333. int max_br, min_br, wpf, min_br_dist, min_br_code;
  2334. /* calculate min/max bitrate */
  2335. max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
  2336. min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
  2337. if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
  2338. av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
  2339. "for this sample rate\n", min_br, max_br);
  2340. return AVERROR(EINVAL);
  2341. }
  2342. /* calculate words-per-frame for the selected bitrate */
  2343. wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
  2344. av_assert1(wpf > 0 && wpf <= 2048);
  2345. /* find the closest AC-3 bitrate code to the selected bitrate.
  2346. this is needed for lookup tables for bandwidth and coupling
  2347. parameter selection */
  2348. min_br_code = -1;
  2349. min_br_dist = INT_MAX;
  2350. for (i = 0; i < 19; i++) {
  2351. int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
  2352. if (br_dist < min_br_dist) {
  2353. min_br_dist = br_dist;
  2354. min_br_code = i;
  2355. }
  2356. }
  2357. /* make sure the minimum frame size is below the average frame size */
  2358. s->frame_size_code = min_br_code << 1;
  2359. while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
  2360. wpf--;
  2361. s->frame_size_min = 2 * wpf;
  2362. } else {
  2363. for (i = 0; i < 19; i++) {
  2364. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  2365. break;
  2366. }
  2367. if (i == 19) {
  2368. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  2369. return AVERROR(EINVAL);
  2370. }
  2371. s->frame_size_code = i << 1;
  2372. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  2373. }
  2374. s->bit_rate = avctx->bit_rate;
  2375. s->frame_size = s->frame_size_min;
  2376. /* validate cutoff */
  2377. if (avctx->cutoff < 0) {
  2378. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  2379. return AVERROR(EINVAL);
  2380. }
  2381. s->cutoff = avctx->cutoff;
  2382. if (s->cutoff > (s->sample_rate >> 1))
  2383. s->cutoff = s->sample_rate >> 1;
  2384. /* validate audio service type / channels combination */
  2385. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  2386. avctx->channels == 1) ||
  2387. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  2388. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  2389. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  2390. && avctx->channels > 1)) {
  2391. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  2392. "specified number of channels\n");
  2393. return AVERROR(EINVAL);
  2394. }
  2395. if (!s->eac3) {
  2396. ret = validate_metadata(avctx);
  2397. if (ret)
  2398. return ret;
  2399. }
  2400. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  2401. (s->channel_mode == AC3_CHMODE_STEREO);
  2402. s->cpl_enabled = s->options.channel_coupling &&
  2403. s->channel_mode >= AC3_CHMODE_STEREO &&
  2404. CONFIG_AC3ENC_FLOAT;
  2405. return 0;
  2406. }
  2407. /**
  2408. * Set bandwidth for all channels.
  2409. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  2410. * default value will be used.
  2411. */
  2412. static av_cold void set_bandwidth(AC3EncodeContext *s)
  2413. {
  2414. int blk, ch;
  2415. int av_uninit(cpl_start);
  2416. if (s->cutoff) {
  2417. /* calculate bandwidth based on user-specified cutoff frequency */
  2418. int fbw_coeffs;
  2419. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  2420. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  2421. } else {
  2422. /* use default bandwidth setting */
  2423. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  2424. }
  2425. /* set number of coefficients for each channel */
  2426. for (ch = 1; ch <= s->fbw_channels; ch++) {
  2427. s->start_freq[ch] = 0;
  2428. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2429. s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
  2430. }
  2431. /* LFE channel always has 7 coefs */
  2432. if (s->lfe_on) {
  2433. s->start_freq[s->lfe_channel] = 0;
  2434. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2435. s->blocks[blk].end_freq[ch] = 7;
  2436. }
  2437. /* initialize coupling strategy */
  2438. if (s->cpl_enabled) {
  2439. if (s->options.cpl_start >= 0) {
  2440. cpl_start = s->options.cpl_start;
  2441. } else {
  2442. cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
  2443. if (cpl_start < 0)
  2444. s->cpl_enabled = 0;
  2445. }
  2446. }
  2447. if (s->cpl_enabled) {
  2448. int i, cpl_start_band, cpl_end_band;
  2449. uint8_t *cpl_band_sizes = s->cpl_band_sizes;
  2450. cpl_end_band = s->bandwidth_code / 4 + 3;
  2451. cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
  2452. s->num_cpl_subbands = cpl_end_band - cpl_start_band;
  2453. s->num_cpl_bands = 1;
  2454. *cpl_band_sizes = 12;
  2455. for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
  2456. if (ff_eac3_default_cpl_band_struct[i]) {
  2457. *cpl_band_sizes += 12;
  2458. } else {
  2459. s->num_cpl_bands++;
  2460. cpl_band_sizes++;
  2461. *cpl_band_sizes = 12;
  2462. }
  2463. }
  2464. s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
  2465. s->cpl_end_freq = cpl_end_band * 12 + 37;
  2466. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2467. s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
  2468. }
  2469. }
  2470. static av_cold int allocate_buffers(AVCodecContext *avctx)
  2471. {
  2472. int blk, ch;
  2473. AC3EncodeContext *s = avctx->priv_data;
  2474. int channels = s->channels + 1; /* includes coupling channel */
  2475. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  2476. alloc_fail);
  2477. for (ch = 0; ch < s->channels; ch++) {
  2478. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  2479. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  2480. alloc_fail);
  2481. }
  2482. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
  2483. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  2484. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
  2485. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  2486. FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
  2487. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  2488. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
  2489. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  2490. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
  2491. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  2492. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
  2493. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  2494. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
  2495. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  2496. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
  2497. 64 * sizeof(*s->mask_buffer), alloc_fail);
  2498. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
  2499. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  2500. if (s->cpl_enabled) {
  2501. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
  2502. 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
  2503. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
  2504. 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
  2505. }
  2506. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2507. AC3Block *block = &s->blocks[blk];
  2508. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
  2509. alloc_fail);
  2510. FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
  2511. alloc_fail);
  2512. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
  2513. alloc_fail);
  2514. FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
  2515. alloc_fail);
  2516. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
  2517. alloc_fail);
  2518. FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
  2519. alloc_fail);
  2520. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
  2521. alloc_fail);
  2522. if (s->cpl_enabled) {
  2523. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
  2524. alloc_fail);
  2525. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
  2526. alloc_fail);
  2527. }
  2528. for (ch = 0; ch < channels; ch++) {
  2529. /* arrangement: block, channel, coeff */
  2530. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
  2531. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2532. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
  2533. block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
  2534. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2535. if (s->cpl_enabled) {
  2536. block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
  2537. block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
  2538. }
  2539. /* arrangement: channel, block, coeff */
  2540. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2541. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2542. }
  2543. }
  2544. if (CONFIG_AC3ENC_FLOAT) {
  2545. FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
  2546. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  2547. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2548. AC3Block *block = &s->blocks[blk];
  2549. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2550. sizeof(*block->fixed_coef), alloc_fail);
  2551. for (ch = 0; ch < channels; ch++)
  2552. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2553. }
  2554. } else {
  2555. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2556. AC3Block *block = &s->blocks[blk];
  2557. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2558. sizeof(*block->fixed_coef), alloc_fail);
  2559. for (ch = 0; ch < channels; ch++)
  2560. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  2561. }
  2562. }
  2563. return 0;
  2564. alloc_fail:
  2565. return AVERROR(ENOMEM);
  2566. }
  2567. /**
  2568. * Initialize the encoder.
  2569. */
  2570. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  2571. {
  2572. AC3EncodeContext *s = avctx->priv_data;
  2573. int ret, frame_size_58;
  2574. s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
  2575. avctx->frame_size = AC3_FRAME_SIZE;
  2576. ff_ac3_common_init();
  2577. ret = validate_options(avctx, s);
  2578. if (ret)
  2579. return ret;
  2580. s->bitstream_mode = avctx->audio_service_type;
  2581. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  2582. s->bitstream_mode = 0x7;
  2583. s->bits_written = 0;
  2584. s->samples_written = 0;
  2585. /* calculate crc_inv for both possible frame sizes */
  2586. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  2587. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2588. if (s->bit_alloc.sr_code == 1) {
  2589. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  2590. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2591. }
  2592. set_bandwidth(s);
  2593. exponent_init(s);
  2594. bit_alloc_init(s);
  2595. ret = mdct_init(avctx, &s->mdct, 9);
  2596. if (ret)
  2597. goto init_fail;
  2598. ret = allocate_buffers(avctx);
  2599. if (ret)
  2600. goto init_fail;
  2601. avctx->coded_frame= avcodec_alloc_frame();
  2602. dsputil_init(&s->dsp, avctx);
  2603. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  2604. dprint_options(avctx);
  2605. return 0;
  2606. init_fail:
  2607. ac3_encode_close(avctx);
  2608. return ret;
  2609. }