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.

2430 lines
82KB

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