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.

2396 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. 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. 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 m, v;
  961. v = (((c << e) >> (24 - qbits)) + 1) >> 1;
  962. m = (1 << (qbits-1));
  963. if (v >= m)
  964. v = m - 1;
  965. av_assert2(v >= -m);
  966. return v;
  967. }
  968. /**
  969. * Quantize a set of mantissas for a single channel in a single block.
  970. */
  971. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  972. uint8_t *exp, uint8_t *bap,
  973. int16_t *qmant, int start_freq,
  974. int end_freq)
  975. {
  976. int i;
  977. for (i = start_freq; i < end_freq; i++) {
  978. int v;
  979. int c = fixed_coef[i];
  980. int e = exp[i];
  981. int b = bap[i];
  982. switch (b) {
  983. case 0:
  984. v = 0;
  985. break;
  986. case 1:
  987. v = sym_quant(c, e, 3);
  988. switch (s->mant1_cnt) {
  989. case 0:
  990. s->qmant1_ptr = &qmant[i];
  991. v = 9 * v;
  992. s->mant1_cnt = 1;
  993. break;
  994. case 1:
  995. *s->qmant1_ptr += 3 * v;
  996. s->mant1_cnt = 2;
  997. v = 128;
  998. break;
  999. default:
  1000. *s->qmant1_ptr += v;
  1001. s->mant1_cnt = 0;
  1002. v = 128;
  1003. break;
  1004. }
  1005. break;
  1006. case 2:
  1007. v = sym_quant(c, e, 5);
  1008. switch (s->mant2_cnt) {
  1009. case 0:
  1010. s->qmant2_ptr = &qmant[i];
  1011. v = 25 * v;
  1012. s->mant2_cnt = 1;
  1013. break;
  1014. case 1:
  1015. *s->qmant2_ptr += 5 * v;
  1016. s->mant2_cnt = 2;
  1017. v = 128;
  1018. break;
  1019. default:
  1020. *s->qmant2_ptr += v;
  1021. s->mant2_cnt = 0;
  1022. v = 128;
  1023. break;
  1024. }
  1025. break;
  1026. case 3:
  1027. v = sym_quant(c, e, 7);
  1028. break;
  1029. case 4:
  1030. v = sym_quant(c, e, 11);
  1031. switch (s->mant4_cnt) {
  1032. case 0:
  1033. s->qmant4_ptr = &qmant[i];
  1034. v = 11 * v;
  1035. s->mant4_cnt = 1;
  1036. break;
  1037. default:
  1038. *s->qmant4_ptr += v;
  1039. s->mant4_cnt = 0;
  1040. v = 128;
  1041. break;
  1042. }
  1043. break;
  1044. case 5:
  1045. v = sym_quant(c, e, 15);
  1046. break;
  1047. case 14:
  1048. v = asym_quant(c, e, 14);
  1049. break;
  1050. case 15:
  1051. v = asym_quant(c, e, 16);
  1052. break;
  1053. default:
  1054. v = asym_quant(c, e, b - 1);
  1055. break;
  1056. }
  1057. qmant[i] = v;
  1058. }
  1059. }
  1060. /**
  1061. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1062. */
  1063. static void quantize_mantissas(AC3EncodeContext *s)
  1064. {
  1065. int blk, ch, ch0=0, got_cpl;
  1066. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1067. AC3Block *block = &s->blocks[blk];
  1068. AC3Mant m = { 0 };
  1069. got_cpl = !block->cpl_in_use;
  1070. for (ch = 1; ch <= s->channels; ch++) {
  1071. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1072. ch0 = ch - 1;
  1073. ch = CPL_CH;
  1074. got_cpl = 1;
  1075. }
  1076. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1077. s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
  1078. s->ref_bap[ch][blk], block->qmant[ch],
  1079. s->start_freq[ch], block->end_freq[ch]);
  1080. if (ch == CPL_CH)
  1081. ch = ch0;
  1082. }
  1083. }
  1084. }
  1085. /**
  1086. * Write the AC-3 frame header to the output bitstream.
  1087. */
  1088. static void ac3_output_frame_header(AC3EncodeContext *s)
  1089. {
  1090. AC3EncOptions *opt = &s->options;
  1091. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1092. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1093. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1094. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1095. put_bits(&s->pb, 5, s->bitstream_id);
  1096. put_bits(&s->pb, 3, s->bitstream_mode);
  1097. put_bits(&s->pb, 3, s->channel_mode);
  1098. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1099. put_bits(&s->pb, 2, s->center_mix_level);
  1100. if (s->channel_mode & 0x04)
  1101. put_bits(&s->pb, 2, s->surround_mix_level);
  1102. if (s->channel_mode == AC3_CHMODE_STEREO)
  1103. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1104. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1105. put_bits(&s->pb, 5, -opt->dialogue_level);
  1106. put_bits(&s->pb, 1, 0); /* no compression control word */
  1107. put_bits(&s->pb, 1, 0); /* no lang code */
  1108. put_bits(&s->pb, 1, opt->audio_production_info);
  1109. if (opt->audio_production_info) {
  1110. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1111. put_bits(&s->pb, 2, opt->room_type);
  1112. }
  1113. put_bits(&s->pb, 1, opt->copyright);
  1114. put_bits(&s->pb, 1, opt->original);
  1115. if (s->bitstream_id == 6) {
  1116. /* alternate bit stream syntax */
  1117. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1118. if (opt->extended_bsi_1) {
  1119. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1120. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1121. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1122. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1123. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1124. }
  1125. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1126. if (opt->extended_bsi_2) {
  1127. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1128. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1129. put_bits(&s->pb, 1, opt->ad_converter_type);
  1130. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1131. }
  1132. } else {
  1133. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1134. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1135. }
  1136. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1137. }
  1138. /**
  1139. * Write one audio block to the output bitstream.
  1140. */
  1141. static void output_audio_block(AC3EncodeContext *s, int blk)
  1142. {
  1143. int ch, i, baie, bnd, got_cpl;
  1144. int av_uninit(ch0);
  1145. AC3Block *block = &s->blocks[blk];
  1146. /* block switching */
  1147. if (!s->eac3) {
  1148. for (ch = 0; ch < s->fbw_channels; ch++)
  1149. put_bits(&s->pb, 1, 0);
  1150. }
  1151. /* dither flags */
  1152. if (!s->eac3) {
  1153. for (ch = 0; ch < s->fbw_channels; ch++)
  1154. put_bits(&s->pb, 1, 1);
  1155. }
  1156. /* dynamic range codes */
  1157. put_bits(&s->pb, 1, 0);
  1158. /* spectral extension */
  1159. if (s->eac3)
  1160. put_bits(&s->pb, 1, 0);
  1161. /* channel coupling */
  1162. if (!s->eac3)
  1163. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1164. if (block->new_cpl_strategy) {
  1165. if (!s->eac3)
  1166. put_bits(&s->pb, 1, block->cpl_in_use);
  1167. if (block->cpl_in_use) {
  1168. int start_sub, end_sub;
  1169. if (s->eac3)
  1170. put_bits(&s->pb, 1, 0); /* enhanced coupling */
  1171. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
  1172. for (ch = 1; ch <= s->fbw_channels; ch++)
  1173. put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
  1174. }
  1175. if (s->channel_mode == AC3_CHMODE_STEREO)
  1176. put_bits(&s->pb, 1, 0); /* phase flags in use */
  1177. start_sub = (s->start_freq[CPL_CH] - 37) / 12;
  1178. end_sub = (s->cpl_end_freq - 37) / 12;
  1179. put_bits(&s->pb, 4, start_sub);
  1180. put_bits(&s->pb, 4, end_sub - 3);
  1181. /* coupling band structure */
  1182. if (s->eac3) {
  1183. put_bits(&s->pb, 1, 0); /* use default */
  1184. } else {
  1185. for (bnd = start_sub+1; bnd < end_sub; bnd++)
  1186. put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
  1187. }
  1188. }
  1189. }
  1190. /* coupling coordinates */
  1191. if (block->cpl_in_use) {
  1192. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1193. if (block->channel_in_cpl[ch]) {
  1194. if (!s->eac3 || block->new_cpl_coords != 2)
  1195. put_bits(&s->pb, 1, block->new_cpl_coords);
  1196. if (block->new_cpl_coords) {
  1197. put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
  1198. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  1199. put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
  1200. put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. }
  1206. /* stereo rematrixing */
  1207. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1208. if (!s->eac3 || blk > 0)
  1209. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1210. if (block->new_rematrixing_strategy) {
  1211. /* rematrixing flags */
  1212. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
  1213. put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
  1214. }
  1215. }
  1216. /* exponent strategy */
  1217. if (!s->eac3) {
  1218. for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
  1219. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1220. if (s->lfe_on)
  1221. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1222. }
  1223. /* bandwidth */
  1224. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1225. if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
  1226. put_bits(&s->pb, 6, s->bandwidth_code);
  1227. }
  1228. /* exponents */
  1229. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1230. int nb_groups;
  1231. int cpl = (ch == CPL_CH);
  1232. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1233. continue;
  1234. /* DC exponent */
  1235. put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
  1236. /* exponent groups */
  1237. nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
  1238. for (i = 1; i <= nb_groups; i++)
  1239. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1240. /* gain range info */
  1241. if (ch != s->lfe_channel && !cpl)
  1242. put_bits(&s->pb, 2, 0);
  1243. }
  1244. /* bit allocation info */
  1245. if (!s->eac3) {
  1246. baie = (blk == 0);
  1247. put_bits(&s->pb, 1, baie);
  1248. if (baie) {
  1249. put_bits(&s->pb, 2, s->slow_decay_code);
  1250. put_bits(&s->pb, 2, s->fast_decay_code);
  1251. put_bits(&s->pb, 2, s->slow_gain_code);
  1252. put_bits(&s->pb, 2, s->db_per_bit_code);
  1253. put_bits(&s->pb, 3, s->floor_code);
  1254. }
  1255. }
  1256. /* snr offset */
  1257. if (!s->eac3) {
  1258. put_bits(&s->pb, 1, block->new_snr_offsets);
  1259. if (block->new_snr_offsets) {
  1260. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1261. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1262. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1263. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1264. }
  1265. }
  1266. } else {
  1267. put_bits(&s->pb, 1, 0); /* no converter snr offset */
  1268. }
  1269. /* coupling leak */
  1270. if (block->cpl_in_use) {
  1271. if (!s->eac3 || block->new_cpl_leak != 2)
  1272. put_bits(&s->pb, 1, block->new_cpl_leak);
  1273. if (block->new_cpl_leak) {
  1274. put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
  1275. put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
  1276. }
  1277. }
  1278. if (!s->eac3) {
  1279. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1280. put_bits(&s->pb, 1, 0); /* no data to skip */
  1281. }
  1282. /* mantissas */
  1283. got_cpl = !block->cpl_in_use;
  1284. for (ch = 1; ch <= s->channels; ch++) {
  1285. int b, q;
  1286. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1287. ch0 = ch - 1;
  1288. ch = CPL_CH;
  1289. got_cpl = 1;
  1290. }
  1291. for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
  1292. q = block->qmant[ch][i];
  1293. b = s->ref_bap[ch][blk][i];
  1294. switch (b) {
  1295. case 0: break;
  1296. case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
  1297. case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
  1298. case 3: put_sbits(&s->pb, 3, q); break;
  1299. case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
  1300. case 14: put_sbits(&s->pb, 14, q); break;
  1301. case 15: put_sbits(&s->pb, 16, q); break;
  1302. default: put_sbits(&s->pb, b-1, q); break;
  1303. }
  1304. }
  1305. if (ch == CPL_CH)
  1306. ch = ch0;
  1307. }
  1308. }
  1309. /** CRC-16 Polynomial */
  1310. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1311. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1312. {
  1313. unsigned int c;
  1314. c = 0;
  1315. while (a) {
  1316. if (a & 1)
  1317. c ^= b;
  1318. a = a >> 1;
  1319. b = b << 1;
  1320. if (b & (1 << 16))
  1321. b ^= poly;
  1322. }
  1323. return c;
  1324. }
  1325. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1326. {
  1327. unsigned int r;
  1328. r = 1;
  1329. while (n) {
  1330. if (n & 1)
  1331. r = mul_poly(r, a, poly);
  1332. a = mul_poly(a, a, poly);
  1333. n >>= 1;
  1334. }
  1335. return r;
  1336. }
  1337. /**
  1338. * Fill the end of the frame with 0's and compute the two CRCs.
  1339. */
  1340. static void output_frame_end(AC3EncodeContext *s)
  1341. {
  1342. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1343. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1344. uint8_t *frame;
  1345. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1346. /* pad the remainder of the frame with zeros */
  1347. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1348. flush_put_bits(&s->pb);
  1349. frame = s->pb.buf;
  1350. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1351. av_assert2(pad_bytes >= 0);
  1352. if (pad_bytes > 0)
  1353. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1354. if (s->eac3) {
  1355. /* compute crc2 */
  1356. crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
  1357. } else {
  1358. /* compute crc1 */
  1359. /* this is not so easy because it is at the beginning of the data... */
  1360. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1361. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1362. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1363. AV_WB16(frame + 2, crc1);
  1364. /* compute crc2 */
  1365. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1366. s->frame_size - frame_size_58 - 3);
  1367. }
  1368. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1369. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1370. if (crc2 == 0x770B) {
  1371. frame[s->frame_size - 3] ^= 0x1;
  1372. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1373. }
  1374. crc2 = av_bswap16(crc2);
  1375. AV_WB16(frame + s->frame_size - 2, crc2);
  1376. }
  1377. /**
  1378. * Write the frame to the output bitstream.
  1379. */
  1380. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1381. {
  1382. int blk;
  1383. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1384. s->output_frame_header(s);
  1385. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1386. output_audio_block(s, blk);
  1387. output_frame_end(s);
  1388. }
  1389. static void dprint_options(AVCodecContext *avctx)
  1390. {
  1391. #ifdef DEBUG
  1392. AC3EncodeContext *s = avctx->priv_data;
  1393. AC3EncOptions *opt = &s->options;
  1394. char strbuf[32];
  1395. switch (s->bitstream_id) {
  1396. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1397. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1398. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1399. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
  1400. case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
  1401. default: snprintf(strbuf, 32, "ERROR");
  1402. }
  1403. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1404. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1405. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1406. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1407. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1408. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1409. if (s->cutoff)
  1410. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1411. av_dlog(avctx, "per_frame_metadata: %s\n",
  1412. opt->allow_per_frame_metadata?"on":"off");
  1413. if (s->has_center)
  1414. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1415. s->center_mix_level);
  1416. else
  1417. av_dlog(avctx, "center_mixlev: {not written}\n");
  1418. if (s->has_surround)
  1419. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1420. s->surround_mix_level);
  1421. else
  1422. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1423. if (opt->audio_production_info) {
  1424. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1425. switch (opt->room_type) {
  1426. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1427. case 1: av_strlcpy(strbuf, "large", 32); break;
  1428. case 2: av_strlcpy(strbuf, "small", 32); break;
  1429. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1430. }
  1431. av_dlog(avctx, "room_type: %s\n", strbuf);
  1432. } else {
  1433. av_dlog(avctx, "mixing_level: {not written}\n");
  1434. av_dlog(avctx, "room_type: {not written}\n");
  1435. }
  1436. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1437. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1438. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1439. switch (opt->dolby_surround_mode) {
  1440. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1441. case 1: av_strlcpy(strbuf, "on", 32); break;
  1442. case 2: av_strlcpy(strbuf, "off", 32); break;
  1443. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  1444. }
  1445. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1446. } else {
  1447. av_dlog(avctx, "dsur_mode: {not written}\n");
  1448. }
  1449. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1450. if (s->bitstream_id == 6) {
  1451. if (opt->extended_bsi_1) {
  1452. switch (opt->preferred_stereo_downmix) {
  1453. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1454. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  1455. case 2: av_strlcpy(strbuf, "loro", 32); break;
  1456. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1457. }
  1458. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1459. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1460. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1461. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1462. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1463. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1464. opt->loro_center_mix_level, s->loro_center_mix_level);
  1465. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1466. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1467. } else {
  1468. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1469. }
  1470. if (opt->extended_bsi_2) {
  1471. switch (opt->dolby_surround_ex_mode) {
  1472. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1473. case 1: av_strlcpy(strbuf, "on", 32); break;
  1474. case 2: av_strlcpy(strbuf, "off", 32); break;
  1475. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1476. }
  1477. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1478. switch (opt->dolby_headphone_mode) {
  1479. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1480. case 1: av_strlcpy(strbuf, "on", 32); break;
  1481. case 2: av_strlcpy(strbuf, "off", 32); break;
  1482. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1483. }
  1484. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1485. switch (opt->ad_converter_type) {
  1486. case 0: av_strlcpy(strbuf, "standard", 32); break;
  1487. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  1488. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1489. }
  1490. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1491. } else {
  1492. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1493. }
  1494. }
  1495. #endif
  1496. }
  1497. #define FLT_OPTION_THRESHOLD 0.01
  1498. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1499. {
  1500. int i;
  1501. for (i = 0; i < v_list_size; i++) {
  1502. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1503. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1504. break;
  1505. }
  1506. if (i == v_list_size)
  1507. return -1;
  1508. return i;
  1509. }
  1510. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1511. float *opt_param, const float *list,
  1512. int list_size, int default_value, int min_value,
  1513. int *ctx_param)
  1514. {
  1515. int mixlev = validate_float_option(*opt_param, list, list_size);
  1516. if (mixlev < min_value) {
  1517. mixlev = default_value;
  1518. if (*opt_param >= 0.0) {
  1519. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1520. "default value: %0.3f\n", opt_name, list[mixlev]);
  1521. }
  1522. }
  1523. *opt_param = list[mixlev];
  1524. *ctx_param = mixlev;
  1525. }
  1526. /**
  1527. * Validate metadata options as set by AVOption system.
  1528. * These values can optionally be changed per-frame.
  1529. */
  1530. static int validate_metadata(AVCodecContext *avctx)
  1531. {
  1532. AC3EncodeContext *s = avctx->priv_data;
  1533. AC3EncOptions *opt = &s->options;
  1534. /* validate mixing levels */
  1535. if (s->has_center) {
  1536. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1537. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1538. &s->center_mix_level);
  1539. }
  1540. if (s->has_surround) {
  1541. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1542. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1543. &s->surround_mix_level);
  1544. }
  1545. /* set audio production info flag */
  1546. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1547. if (opt->mixing_level < 0) {
  1548. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1549. "room_type is set\n");
  1550. return AVERROR(EINVAL);
  1551. }
  1552. if (opt->mixing_level < 80) {
  1553. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1554. "80dB and 111dB\n");
  1555. return AVERROR(EINVAL);
  1556. }
  1557. /* default room type */
  1558. if (opt->room_type < 0)
  1559. opt->room_type = 0;
  1560. opt->audio_production_info = 1;
  1561. } else {
  1562. opt->audio_production_info = 0;
  1563. }
  1564. /* set extended bsi 1 flag */
  1565. if ((s->has_center || s->has_surround) &&
  1566. (opt->preferred_stereo_downmix >= 0 ||
  1567. opt->ltrt_center_mix_level >= 0 ||
  1568. opt->ltrt_surround_mix_level >= 0 ||
  1569. opt->loro_center_mix_level >= 0 ||
  1570. opt->loro_surround_mix_level >= 0)) {
  1571. /* default preferred stereo downmix */
  1572. if (opt->preferred_stereo_downmix < 0)
  1573. opt->preferred_stereo_downmix = 0;
  1574. /* validate Lt/Rt center mix level */
  1575. validate_mix_level(avctx, "ltrt_center_mix_level",
  1576. &opt->ltrt_center_mix_level, extmixlev_options,
  1577. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1578. &s->ltrt_center_mix_level);
  1579. /* validate Lt/Rt surround mix level */
  1580. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1581. &opt->ltrt_surround_mix_level, extmixlev_options,
  1582. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1583. &s->ltrt_surround_mix_level);
  1584. /* validate Lo/Ro center mix level */
  1585. validate_mix_level(avctx, "loro_center_mix_level",
  1586. &opt->loro_center_mix_level, extmixlev_options,
  1587. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1588. &s->loro_center_mix_level);
  1589. /* validate Lo/Ro surround mix level */
  1590. validate_mix_level(avctx, "loro_surround_mix_level",
  1591. &opt->loro_surround_mix_level, extmixlev_options,
  1592. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1593. &s->loro_surround_mix_level);
  1594. opt->extended_bsi_1 = 1;
  1595. } else {
  1596. opt->extended_bsi_1 = 0;
  1597. }
  1598. /* set extended bsi 2 flag */
  1599. if (opt->dolby_surround_ex_mode >= 0 ||
  1600. opt->dolby_headphone_mode >= 0 ||
  1601. opt->ad_converter_type >= 0) {
  1602. /* default dolby surround ex mode */
  1603. if (opt->dolby_surround_ex_mode < 0)
  1604. opt->dolby_surround_ex_mode = 0;
  1605. /* default dolby headphone mode */
  1606. if (opt->dolby_headphone_mode < 0)
  1607. opt->dolby_headphone_mode = 0;
  1608. /* default A/D converter type */
  1609. if (opt->ad_converter_type < 0)
  1610. opt->ad_converter_type = 0;
  1611. opt->extended_bsi_2 = 1;
  1612. } else {
  1613. opt->extended_bsi_2 = 0;
  1614. }
  1615. /* set bitstream id for alternate bitstream syntax */
  1616. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1617. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1618. static int warn_once = 1;
  1619. if (warn_once) {
  1620. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1621. "not compatible with reduced samplerates. writing of "
  1622. "extended bitstream information will be disabled.\n");
  1623. warn_once = 0;
  1624. }
  1625. } else {
  1626. s->bitstream_id = 6;
  1627. }
  1628. }
  1629. return 0;
  1630. }
  1631. /**
  1632. * Encode a single AC-3 frame.
  1633. */
  1634. int ff_ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1635. int buf_size, void *data)
  1636. {
  1637. AC3EncodeContext *s = avctx->priv_data;
  1638. const SampleType *samples = data;
  1639. int ret;
  1640. if (!s->eac3 && s->options.allow_per_frame_metadata) {
  1641. ret = validate_metadata(avctx);
  1642. if (ret)
  1643. return ret;
  1644. }
  1645. if (s->bit_alloc.sr_code == 1 || s->eac3)
  1646. adjust_frame_size(s);
  1647. s->deinterleave_input_samples(s, samples);
  1648. s->apply_mdct(s);
  1649. s->scale_coefficients(s);
  1650. s->cpl_on = s->cpl_enabled;
  1651. compute_coupling_strategy(s);
  1652. if (s->cpl_on)
  1653. s->apply_channel_coupling(s);
  1654. s->compute_rematrixing_strategy(s);
  1655. apply_rematrixing(s);
  1656. process_exponents(s);
  1657. ret = compute_bit_allocation(s);
  1658. if (ret) {
  1659. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1660. return ret;
  1661. }
  1662. quantize_mantissas(s);
  1663. output_frame(s, frame);
  1664. return s->frame_size;
  1665. }
  1666. /**
  1667. * Finalize encoding and free any memory allocated by the encoder.
  1668. */
  1669. av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
  1670. {
  1671. int blk, ch;
  1672. AC3EncodeContext *s = avctx->priv_data;
  1673. av_freep(&s->windowed_samples);
  1674. for (ch = 0; ch < s->channels; ch++)
  1675. av_freep(&s->planar_samples[ch]);
  1676. av_freep(&s->planar_samples);
  1677. av_freep(&s->bap_buffer);
  1678. av_freep(&s->bap1_buffer);
  1679. av_freep(&s->mdct_coef_buffer);
  1680. av_freep(&s->fixed_coef_buffer);
  1681. av_freep(&s->exp_buffer);
  1682. av_freep(&s->grouped_exp_buffer);
  1683. av_freep(&s->psd_buffer);
  1684. av_freep(&s->band_psd_buffer);
  1685. av_freep(&s->mask_buffer);
  1686. av_freep(&s->qmant_buffer);
  1687. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1688. AC3Block *block = &s->blocks[blk];
  1689. av_freep(&block->mdct_coef);
  1690. av_freep(&block->fixed_coef);
  1691. av_freep(&block->exp);
  1692. av_freep(&block->grouped_exp);
  1693. av_freep(&block->psd);
  1694. av_freep(&block->band_psd);
  1695. av_freep(&block->mask);
  1696. av_freep(&block->qmant);
  1697. }
  1698. s->mdct_end(s->mdct);
  1699. av_freep(&s->mdct);
  1700. av_freep(&avctx->coded_frame);
  1701. return 0;
  1702. }
  1703. /**
  1704. * Set channel information during initialization.
  1705. */
  1706. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1707. int64_t *channel_layout)
  1708. {
  1709. int ch_layout;
  1710. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1711. return AVERROR(EINVAL);
  1712. if ((uint64_t)*channel_layout > 0x7FF)
  1713. return AVERROR(EINVAL);
  1714. ch_layout = *channel_layout;
  1715. if (!ch_layout)
  1716. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1717. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1718. s->channels = channels;
  1719. s->fbw_channels = channels - s->lfe_on;
  1720. s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
  1721. if (s->lfe_on)
  1722. ch_layout -= AV_CH_LOW_FREQUENCY;
  1723. switch (ch_layout) {
  1724. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1725. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1726. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1727. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1728. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1729. case AV_CH_LAYOUT_QUAD:
  1730. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1731. case AV_CH_LAYOUT_5POINT0:
  1732. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1733. default:
  1734. return AVERROR(EINVAL);
  1735. }
  1736. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1737. s->has_surround = s->channel_mode & 0x04;
  1738. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1739. *channel_layout = ch_layout;
  1740. if (s->lfe_on)
  1741. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1742. return 0;
  1743. }
  1744. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1745. {
  1746. int i, ret, max_sr;
  1747. /* validate channel layout */
  1748. if (!avctx->channel_layout) {
  1749. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1750. "encoder will guess the layout, but it "
  1751. "might be incorrect.\n");
  1752. }
  1753. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1754. if (ret) {
  1755. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1756. return ret;
  1757. }
  1758. /* validate sample rate */
  1759. /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
  1760. decoder that supports half sample rate so we can validate that
  1761. the generated files are correct. */
  1762. max_sr = s->eac3 ? 2 : 8;
  1763. for (i = 0; i <= max_sr; i++) {
  1764. if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
  1765. break;
  1766. }
  1767. if (i > max_sr) {
  1768. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1769. return AVERROR(EINVAL);
  1770. }
  1771. s->sample_rate = avctx->sample_rate;
  1772. s->bit_alloc.sr_shift = i / 3;
  1773. s->bit_alloc.sr_code = i % 3;
  1774. s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
  1775. /* validate bit rate */
  1776. if (s->eac3) {
  1777. int max_br, min_br, wpf, min_br_dist, min_br_code;
  1778. /* calculate min/max bitrate */
  1779. max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
  1780. min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
  1781. if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
  1782. av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
  1783. "for this sample rate\n", min_br, max_br);
  1784. return AVERROR(EINVAL);
  1785. }
  1786. /* calculate words-per-frame for the selected bitrate */
  1787. wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
  1788. av_assert1(wpf > 0 && wpf <= 2048);
  1789. /* find the closest AC-3 bitrate code to the selected bitrate.
  1790. this is needed for lookup tables for bandwidth and coupling
  1791. parameter selection */
  1792. min_br_code = -1;
  1793. min_br_dist = INT_MAX;
  1794. for (i = 0; i < 19; i++) {
  1795. int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
  1796. if (br_dist < min_br_dist) {
  1797. min_br_dist = br_dist;
  1798. min_br_code = i;
  1799. }
  1800. }
  1801. /* make sure the minimum frame size is below the average frame size */
  1802. s->frame_size_code = min_br_code << 1;
  1803. while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
  1804. wpf--;
  1805. s->frame_size_min = 2 * wpf;
  1806. } else {
  1807. for (i = 0; i < 19; i++) {
  1808. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1809. break;
  1810. }
  1811. if (i == 19) {
  1812. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1813. return AVERROR(EINVAL);
  1814. }
  1815. s->frame_size_code = i << 1;
  1816. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1817. }
  1818. s->bit_rate = avctx->bit_rate;
  1819. s->frame_size = s->frame_size_min;
  1820. /* validate cutoff */
  1821. if (avctx->cutoff < 0) {
  1822. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1823. return AVERROR(EINVAL);
  1824. }
  1825. s->cutoff = avctx->cutoff;
  1826. if (s->cutoff > (s->sample_rate >> 1))
  1827. s->cutoff = s->sample_rate >> 1;
  1828. /* validate audio service type / channels combination */
  1829. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1830. avctx->channels == 1) ||
  1831. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1832. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1833. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1834. && avctx->channels > 1)) {
  1835. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1836. "specified number of channels\n");
  1837. return AVERROR(EINVAL);
  1838. }
  1839. if (!s->eac3) {
  1840. ret = validate_metadata(avctx);
  1841. if (ret)
  1842. return ret;
  1843. }
  1844. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  1845. (s->channel_mode == AC3_CHMODE_STEREO);
  1846. s->cpl_enabled = s->options.channel_coupling &&
  1847. s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
  1848. return 0;
  1849. }
  1850. /**
  1851. * Set bandwidth for all channels.
  1852. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1853. * default value will be used.
  1854. */
  1855. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1856. {
  1857. int blk, ch;
  1858. int av_uninit(cpl_start);
  1859. if (s->cutoff) {
  1860. /* calculate bandwidth based on user-specified cutoff frequency */
  1861. int fbw_coeffs;
  1862. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1863. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1864. } else {
  1865. /* use default bandwidth setting */
  1866. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  1867. }
  1868. /* set number of coefficients for each channel */
  1869. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1870. s->start_freq[ch] = 0;
  1871. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1872. s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
  1873. }
  1874. /* LFE channel always has 7 coefs */
  1875. if (s->lfe_on) {
  1876. s->start_freq[s->lfe_channel] = 0;
  1877. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1878. s->blocks[blk].end_freq[ch] = 7;
  1879. }
  1880. /* initialize coupling strategy */
  1881. if (s->cpl_enabled) {
  1882. if (s->options.cpl_start >= 0) {
  1883. cpl_start = s->options.cpl_start;
  1884. } else {
  1885. cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
  1886. if (cpl_start < 0)
  1887. s->cpl_enabled = 0;
  1888. }
  1889. }
  1890. if (s->cpl_enabled) {
  1891. int i, cpl_start_band, cpl_end_band;
  1892. uint8_t *cpl_band_sizes = s->cpl_band_sizes;
  1893. cpl_end_band = s->bandwidth_code / 4 + 3;
  1894. cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
  1895. s->num_cpl_subbands = cpl_end_band - cpl_start_band;
  1896. s->num_cpl_bands = 1;
  1897. *cpl_band_sizes = 12;
  1898. for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
  1899. if (ff_eac3_default_cpl_band_struct[i]) {
  1900. *cpl_band_sizes += 12;
  1901. } else {
  1902. s->num_cpl_bands++;
  1903. cpl_band_sizes++;
  1904. *cpl_band_sizes = 12;
  1905. }
  1906. }
  1907. s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
  1908. s->cpl_end_freq = cpl_end_band * 12 + 37;
  1909. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1910. s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
  1911. }
  1912. }
  1913. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1914. {
  1915. int blk, ch;
  1916. AC3EncodeContext *s = avctx->priv_data;
  1917. int channels = s->channels + 1; /* includes coupling channel */
  1918. if (s->allocate_sample_buffers(s))
  1919. goto alloc_fail;
  1920. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
  1921. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1922. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
  1923. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1924. FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
  1925. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1926. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
  1927. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1928. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
  1929. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1930. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
  1931. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1932. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
  1933. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1934. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
  1935. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1936. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
  1937. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1938. if (s->cpl_enabled) {
  1939. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
  1940. 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
  1941. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
  1942. 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
  1943. }
  1944. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1945. AC3Block *block = &s->blocks[blk];
  1946. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
  1947. alloc_fail);
  1948. FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
  1949. alloc_fail);
  1950. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
  1951. alloc_fail);
  1952. FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
  1953. alloc_fail);
  1954. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
  1955. alloc_fail);
  1956. FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
  1957. alloc_fail);
  1958. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
  1959. alloc_fail);
  1960. if (s->cpl_enabled) {
  1961. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
  1962. alloc_fail);
  1963. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
  1964. alloc_fail);
  1965. }
  1966. for (ch = 0; ch < channels; ch++) {
  1967. /* arrangement: block, channel, coeff */
  1968. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
  1969. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  1970. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
  1971. block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
  1972. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  1973. if (s->cpl_enabled) {
  1974. block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
  1975. block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
  1976. }
  1977. /* arrangement: channel, block, coeff */
  1978. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1979. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1980. }
  1981. }
  1982. if (!s->fixed_point) {
  1983. FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
  1984. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1985. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1986. AC3Block *block = &s->blocks[blk];
  1987. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  1988. sizeof(*block->fixed_coef), alloc_fail);
  1989. for (ch = 0; ch < channels; ch++)
  1990. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1991. }
  1992. } else {
  1993. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1994. AC3Block *block = &s->blocks[blk];
  1995. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  1996. sizeof(*block->fixed_coef), alloc_fail);
  1997. for (ch = 0; ch < channels; ch++)
  1998. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1999. }
  2000. }
  2001. return 0;
  2002. alloc_fail:
  2003. return AVERROR(ENOMEM);
  2004. }
  2005. /**
  2006. * Initialize the encoder.
  2007. */
  2008. av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
  2009. {
  2010. AC3EncodeContext *s = avctx->priv_data;
  2011. int ret, frame_size_58;
  2012. s->avctx = avctx;
  2013. s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
  2014. avctx->frame_size = AC3_FRAME_SIZE;
  2015. ff_ac3_common_init();
  2016. ret = validate_options(avctx, s);
  2017. if (ret)
  2018. return ret;
  2019. s->bitstream_mode = avctx->audio_service_type;
  2020. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  2021. s->bitstream_mode = 0x7;
  2022. s->bits_written = 0;
  2023. s->samples_written = 0;
  2024. /* calculate crc_inv for both possible frame sizes */
  2025. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  2026. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2027. if (s->bit_alloc.sr_code == 1) {
  2028. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  2029. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2030. }
  2031. /* set function pointers */
  2032. if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
  2033. s->mdct_end = ff_ac3_fixed_mdct_end;
  2034. s->mdct_init = ff_ac3_fixed_mdct_init;
  2035. s->apply_window = ff_ac3_fixed_apply_window;
  2036. s->normalize_samples = ff_ac3_fixed_normalize_samples;
  2037. s->scale_coefficients = ff_ac3_fixed_scale_coefficients;
  2038. s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
  2039. s->deinterleave_input_samples = ff_ac3_fixed_deinterleave_input_samples;
  2040. s->apply_mdct = ff_ac3_fixed_apply_mdct;
  2041. s->apply_channel_coupling = ff_ac3_fixed_apply_channel_coupling;
  2042. s->compute_rematrixing_strategy = ff_ac3_fixed_compute_rematrixing_strategy;
  2043. } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
  2044. s->mdct_end = ff_ac3_float_mdct_end;
  2045. s->mdct_init = ff_ac3_float_mdct_init;
  2046. s->apply_window = ff_ac3_float_apply_window;
  2047. s->scale_coefficients = ff_ac3_float_scale_coefficients;
  2048. s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
  2049. s->deinterleave_input_samples = ff_ac3_float_deinterleave_input_samples;
  2050. s->apply_mdct = ff_ac3_float_apply_mdct;
  2051. s->apply_channel_coupling = ff_ac3_float_apply_channel_coupling;
  2052. s->compute_rematrixing_strategy = ff_ac3_float_compute_rematrixing_strategy;
  2053. }
  2054. if (CONFIG_EAC3_ENCODER && s->eac3)
  2055. s->output_frame_header = ff_eac3_output_frame_header;
  2056. else
  2057. s->output_frame_header = ac3_output_frame_header;
  2058. set_bandwidth(s);
  2059. exponent_init(s);
  2060. bit_alloc_init(s);
  2061. FF_ALLOCZ_OR_GOTO(avctx, s->mdct, sizeof(AC3MDCTContext), init_fail);
  2062. ret = s->mdct_init(avctx, s->mdct, 9);
  2063. if (ret)
  2064. goto init_fail;
  2065. ret = allocate_buffers(avctx);
  2066. if (ret)
  2067. goto init_fail;
  2068. avctx->coded_frame= avcodec_alloc_frame();
  2069. dsputil_init(&s->dsp, avctx);
  2070. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  2071. dprint_options(avctx);
  2072. return 0;
  2073. init_fail:
  2074. ff_ac3_encode_close(avctx);
  2075. return ret;
  2076. }