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.

2401 lines
81KB

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