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.

2402 lines
80KB

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