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.

2322 lines
78KB

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