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.

2293 lines
77KB

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