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.

1624 lines
51KB

  1. /*
  2. * The simplest AC-3 encoder
  3. * Copyright (c) 2000 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * The simplest AC-3 encoder.
  24. */
  25. //#define DEBUG
  26. #include "libavcore/audioconvert.h"
  27. #include "libavutil/crc.h"
  28. #include "avcodec.h"
  29. #include "put_bits.h"
  30. #include "ac3.h"
  31. #include "audioconvert.h"
  32. #define MDCT_NBITS 9
  33. #define MDCT_SAMPLES (1 << MDCT_NBITS)
  34. /** Scale a float value by 2^bits and convert to an integer. */
  35. #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
  36. /** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
  37. #define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
  38. /**
  39. * Compex number.
  40. * Used in fixed-point MDCT calculation.
  41. */
  42. typedef struct IComplex {
  43. int16_t re,im;
  44. } IComplex;
  45. /**
  46. * AC-3 encoder private context.
  47. */
  48. typedef struct AC3EncodeContext {
  49. PutBitContext pb; ///< bitstream writer context
  50. int bitstream_id; ///< bitstream id (bsid)
  51. int bitstream_mode; ///< bitstream mode (bsmod)
  52. int bit_rate; ///< target bit rate, in bits-per-second
  53. int sample_rate; ///< sampling frequency, in Hz
  54. int frame_size_min; ///< minimum frame size in case rounding is necessary
  55. int frame_size; ///< current frame size in bytes
  56. int frame_size_code; ///< frame size code (frmsizecod)
  57. int bits_written; ///< bit count (used to avg. bitrate)
  58. int samples_written; ///< sample count (used to avg. bitrate)
  59. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  60. int channels; ///< total number of channels (nchans)
  61. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  62. int lfe_channel; ///< channel index of the LFE channel
  63. int channel_mode; ///< channel mode (acmod)
  64. const uint8_t *channel_map; ///< channel map used to reorder channels
  65. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  66. int nb_coefs[AC3_MAX_CHANNELS];
  67. /* bitrate allocation control */
  68. int slow_gain_code; ///< slow gain code (sgaincod)
  69. int slow_decay_code; ///< slow decay code (sdcycod)
  70. int fast_decay_code; ///< fast decay code (fdcycod)
  71. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  72. int floor_code; ///< floor code (floorcod)
  73. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  74. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  75. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  76. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  77. /* mantissa encoding */
  78. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  79. int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
  80. } AC3EncodeContext;
  81. /** MDCT and FFT tables */
  82. static int16_t costab[64];
  83. static int16_t sintab[64];
  84. static int16_t xcos1[128];
  85. static int16_t xsin1[128];
  86. /**
  87. * Deinterleave input samples.
  88. * Channels are reordered from FFmpeg's default order to AC-3 order.
  89. */
  90. static void deinterleave_input_samples(AC3EncodeContext *s,
  91. const int16_t *samples,
  92. int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE])
  93. {
  94. int ch, i;
  95. /* deinterleave and remap input samples */
  96. for (ch = 0; ch < s->channels; ch++) {
  97. const int16_t *sptr;
  98. int sinc;
  99. /* copy last 256 samples of previous frame to the start of the current frame */
  100. memcpy(&planar_samples[ch][0], s->last_samples[ch],
  101. AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
  102. /* deinterleave */
  103. sinc = s->channels;
  104. sptr = samples + s->channel_map[ch];
  105. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  106. planar_samples[ch][i] = *sptr;
  107. sptr += sinc;
  108. }
  109. /* save last 256 samples for next frame */
  110. memcpy(s->last_samples[ch], &planar_samples[ch][6* AC3_BLOCK_SIZE],
  111. AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
  112. }
  113. }
  114. /**
  115. * Initialize FFT tables.
  116. * @param ln log2(FFT size)
  117. */
  118. static av_cold void fft_init(int ln)
  119. {
  120. int i, n, n2;
  121. float alpha;
  122. n = 1 << ln;
  123. n2 = n >> 1;
  124. for (i = 0; i < n2; i++) {
  125. alpha = 2.0 * M_PI * i / n;
  126. costab[i] = FIX15(cos(alpha));
  127. sintab[i] = FIX15(sin(alpha));
  128. }
  129. }
  130. /**
  131. * Initialize MDCT tables.
  132. * @param nbits log2(MDCT size)
  133. */
  134. static av_cold void mdct_init(int nbits)
  135. {
  136. int i, n, n4;
  137. n = 1 << nbits;
  138. n4 = n >> 2;
  139. fft_init(nbits - 2);
  140. for (i = 0; i < n4; i++) {
  141. float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
  142. xcos1[i] = FIX15(-cos(alpha));
  143. xsin1[i] = FIX15(-sin(alpha));
  144. }
  145. }
  146. /** Butterfly op */
  147. #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
  148. { \
  149. int ax, ay, bx, by; \
  150. bx = pre1; \
  151. by = pim1; \
  152. ax = qre1; \
  153. ay = qim1; \
  154. pre = (bx + ax) >> 1; \
  155. pim = (by + ay) >> 1; \
  156. qre = (bx - ax) >> 1; \
  157. qim = (by - ay) >> 1; \
  158. }
  159. /** Complex multiply */
  160. #define CMUL(pre, pim, are, aim, bre, bim) \
  161. { \
  162. pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15; \
  163. pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15; \
  164. }
  165. /**
  166. * Calculate a 2^n point complex FFT on 2^ln points.
  167. * @param z complex input/output samples
  168. * @param ln log2(FFT size)
  169. */
  170. static void fft(IComplex *z, int ln)
  171. {
  172. int j, l, np, np2;
  173. int nblocks, nloops;
  174. register IComplex *p,*q;
  175. int tmp_re, tmp_im;
  176. np = 1 << ln;
  177. /* reverse */
  178. for (j = 0; j < np; j++) {
  179. int k = av_reverse[j] >> (8 - ln);
  180. if (k < j)
  181. FFSWAP(IComplex, z[k], z[j]);
  182. }
  183. /* pass 0 */
  184. p = &z[0];
  185. j = np >> 1;
  186. do {
  187. BF(p[0].re, p[0].im, p[1].re, p[1].im,
  188. p[0].re, p[0].im, p[1].re, p[1].im);
  189. p += 2;
  190. } while (--j);
  191. /* pass 1 */
  192. p = &z[0];
  193. j = np >> 2;
  194. do {
  195. BF(p[0].re, p[0].im, p[2].re, p[2].im,
  196. p[0].re, p[0].im, p[2].re, p[2].im);
  197. BF(p[1].re, p[1].im, p[3].re, p[3].im,
  198. p[1].re, p[1].im, p[3].im, -p[3].re);
  199. p+=4;
  200. } while (--j);
  201. /* pass 2 .. ln-1 */
  202. nblocks = np >> 3;
  203. nloops = 1 << 2;
  204. np2 = np >> 1;
  205. do {
  206. p = z;
  207. q = z + nloops;
  208. for (j = 0; j < nblocks; j++) {
  209. BF(p->re, p->im, q->re, q->im,
  210. p->re, p->im, q->re, q->im);
  211. p++;
  212. q++;
  213. for(l = nblocks; l < np2; l += nblocks) {
  214. CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
  215. BF(p->re, p->im, q->re, q->im,
  216. p->re, p->im, tmp_re, tmp_im);
  217. p++;
  218. q++;
  219. }
  220. p += nloops;
  221. q += nloops;
  222. }
  223. nblocks = nblocks >> 1;
  224. nloops = nloops << 1;
  225. } while (nblocks);
  226. }
  227. /**
  228. * Calculate a 512-point MDCT
  229. * @param out 256 output frequency coefficients
  230. * @param in 512 windowed input audio samples
  231. */
  232. static void mdct512(int32_t *out, int16_t *in)
  233. {
  234. int i, re, im, re1, im1;
  235. int16_t rot[MDCT_SAMPLES];
  236. IComplex x[MDCT_SAMPLES/4];
  237. /* shift to simplify computations */
  238. for (i = 0; i < MDCT_SAMPLES/4; i++)
  239. rot[i] = -in[i + 3*MDCT_SAMPLES/4];
  240. for (;i < MDCT_SAMPLES; i++)
  241. rot[i] = in[i - MDCT_SAMPLES/4];
  242. /* pre rotation */
  243. for (i = 0; i < MDCT_SAMPLES/4; i++) {
  244. re = ((int)rot[ 2*i] - (int)rot[MDCT_SAMPLES -1-2*i]) >> 1;
  245. im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
  246. CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
  247. }
  248. fft(x, MDCT_NBITS - 2);
  249. /* post rotation */
  250. for (i = 0; i < MDCT_SAMPLES/4; i++) {
  251. re = x[i].re;
  252. im = x[i].im;
  253. CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
  254. out[ 2*i] = im1;
  255. out[MDCT_SAMPLES/2-1-2*i] = re1;
  256. }
  257. }
  258. /**
  259. * Apply KBD window to input samples prior to MDCT.
  260. */
  261. static void apply_window(int16_t *output, const int16_t *input,
  262. const int16_t *window, int n)
  263. {
  264. int i;
  265. int n2 = n >> 1;
  266. for (i = 0; i < n2; i++) {
  267. output[i] = MUL16(input[i], window[i]) >> 15;
  268. output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
  269. }
  270. }
  271. /**
  272. * Calculate the log2() of the maximum absolute value in an array.
  273. * @param tab input array
  274. * @param n number of values in the array
  275. * @return log2(max(abs(tab[])))
  276. */
  277. static int log2_tab(int16_t *tab, int n)
  278. {
  279. int i, v;
  280. v = 0;
  281. for (i = 0; i < n; i++)
  282. v |= abs(tab[i]);
  283. return av_log2(v);
  284. }
  285. /**
  286. * Left-shift each value in an array by a specified amount.
  287. * @param tab input array
  288. * @param n number of values in the array
  289. * @param lshift left shift amount. a negative value means right shift.
  290. */
  291. static void lshift_tab(int16_t *tab, int n, int lshift)
  292. {
  293. int i;
  294. if (lshift > 0) {
  295. for(i = 0; i < n; i++)
  296. tab[i] <<= lshift;
  297. } else if (lshift < 0) {
  298. lshift = -lshift;
  299. for (i = 0; i < n; i++)
  300. tab[i] >>= lshift;
  301. }
  302. }
  303. /**
  304. * Normalize the input samples to use the maximum available precision.
  305. * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
  306. * match the 24-bit internal precision for MDCT coefficients.
  307. *
  308. * @return exponent shift
  309. */
  310. static int normalize_samples(AC3EncodeContext *s,
  311. int16_t windowed_samples[AC3_WINDOW_SIZE])
  312. {
  313. int v = 14 - log2_tab(windowed_samples, AC3_WINDOW_SIZE);
  314. v = FFMAX(0, v);
  315. lshift_tab(windowed_samples, AC3_WINDOW_SIZE, v);
  316. return v - 9;
  317. }
  318. /**
  319. * Apply the MDCT to input samples to generate frequency coefficients.
  320. * This applies the KBD window and normalizes the input to reduce precision
  321. * loss due to fixed-point calculations.
  322. */
  323. static void apply_mdct(AC3EncodeContext *s,
  324. int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE],
  325. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  326. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  327. {
  328. int blk, ch;
  329. int16_t windowed_samples[AC3_WINDOW_SIZE];
  330. for (ch = 0; ch < s->channels; ch++) {
  331. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  332. const int16_t *input_samples = &planar_samples[ch][blk * AC3_BLOCK_SIZE];
  333. apply_window(windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
  334. exp_shift[blk][ch] = normalize_samples(s, windowed_samples);
  335. mdct512(mdct_coef[blk][ch], windowed_samples);
  336. }
  337. }
  338. }
  339. /**
  340. * Extract exponents from the MDCT coefficients.
  341. * This takes into account the normalization that was done to the input samples
  342. * by adjusting the exponents by the exponent shift values.
  343. */
  344. static void extract_exponents(AC3EncodeContext *s,
  345. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  346. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  347. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  348. {
  349. int blk, ch, i;
  350. /* extract exponents */
  351. for (ch = 0; ch < s->channels; ch++) {
  352. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  353. /* compute "exponents". We take into account the normalization there */
  354. for (i = 0; i < AC3_MAX_COEFS; i++) {
  355. int e;
  356. int v = abs(mdct_coef[blk][ch][i]);
  357. if (v == 0)
  358. e = 24;
  359. else {
  360. e = 23 - av_log2(v) + exp_shift[blk][ch];
  361. if (e >= 24) {
  362. e = 24;
  363. mdct_coef[blk][ch][i] = 0;
  364. }
  365. }
  366. exp[blk][ch][i] = e;
  367. }
  368. }
  369. }
  370. }
  371. /**
  372. * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
  373. */
  374. static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
  375. {
  376. int sum, i;
  377. sum = 0;
  378. for (i = 0; i < n; i++)
  379. sum += abs(exp1[i] - exp2[i]);
  380. return sum;
  381. }
  382. /**
  383. * Exponent Difference Threshold.
  384. * New exponents are sent if their SAD exceed this number.
  385. */
  386. #define EXP_DIFF_THRESHOLD 1000
  387. /**
  388. * Calculate exponent strategies for all blocks in a single channel.
  389. */
  390. static void compute_exp_strategy_ch(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  391. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  392. int ch, int is_lfe)
  393. {
  394. int blk, blk1;
  395. int exp_diff;
  396. /* estimate if the exponent variation & decide if they should be
  397. reused in the next frame */
  398. exp_strategy[0][ch] = EXP_NEW;
  399. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  400. exp_diff = calc_exp_diff(exp[blk][ch], exp[blk-1][ch], AC3_MAX_COEFS);
  401. if (exp_diff > EXP_DIFF_THRESHOLD)
  402. exp_strategy[blk][ch] = EXP_NEW;
  403. else
  404. exp_strategy[blk][ch] = EXP_REUSE;
  405. }
  406. if (is_lfe)
  407. return;
  408. /* now select the encoding strategy type : if exponents are often
  409. recoded, we use a coarse encoding */
  410. blk = 0;
  411. while (blk < AC3_MAX_BLOCKS) {
  412. blk1 = blk + 1;
  413. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE)
  414. blk1++;
  415. switch (blk1 - blk) {
  416. case 1: exp_strategy[blk][ch] = EXP_D45; break;
  417. case 2:
  418. case 3: exp_strategy[blk][ch] = EXP_D25; break;
  419. default: exp_strategy[blk][ch] = EXP_D15; break;
  420. }
  421. blk = blk1;
  422. }
  423. }
  424. /**
  425. * Calculate exponent strategies for all channels.
  426. */
  427. static void compute_exp_strategy(AC3EncodeContext *s,
  428. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  429. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  430. {
  431. int ch;
  432. for (ch = 0; ch < s->channels; ch++) {
  433. compute_exp_strategy_ch(exp_strategy, exp, ch, ch == s->lfe_channel);
  434. }
  435. }
  436. /**
  437. * Set each encoded exponent in a block to the minimum of itself and the
  438. * exponent in the same frequency bin of a following block.
  439. * exp[i] = min(exp[i], exp1[i]
  440. */
  441. static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
  442. {
  443. int i;
  444. for (i = 0; i < n; i++) {
  445. if (exp1[i] < exp[i])
  446. exp[i] = exp1[i];
  447. }
  448. }
  449. /**
  450. * Update the exponents so that they are the ones the decoder will decode.
  451. * @return the number of bits used to encode the exponents.
  452. */
  453. static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
  454. uint8_t exp[AC3_MAX_COEFS],
  455. int nb_exps, int exp_strategy)
  456. {
  457. int group_size, nb_groups, i, j, k, exp_min;
  458. uint8_t exp1[AC3_MAX_COEFS];
  459. group_size = exp_strategy + (exp_strategy == EXP_D45);
  460. nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
  461. /* for each group, compute the minimum exponent */
  462. exp1[0] = exp[0]; /* DC exponent is handled separately */
  463. k = 1;
  464. for (i = 1; i <= nb_groups; i++) {
  465. exp_min = exp[k];
  466. assert(exp_min >= 0 && exp_min <= 24);
  467. for (j = 1; j < group_size; j++) {
  468. if (exp[k+j] < exp_min)
  469. exp_min = exp[k+j];
  470. }
  471. exp1[i] = exp_min;
  472. k += group_size;
  473. }
  474. /* constraint for DC exponent */
  475. if (exp1[0] > 15)
  476. exp1[0] = 15;
  477. /* decrease the delta between each groups to within 2 so that they can be
  478. differentially encoded */
  479. for (i = 1; i <= nb_groups; i++)
  480. exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
  481. for (i = nb_groups-1; i >= 0; i--)
  482. exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
  483. /* now we have the exponent values the decoder will see */
  484. encoded_exp[0] = exp1[0];
  485. k = 1;
  486. for (i = 1; i <= nb_groups; i++) {
  487. for (j = 0; j < group_size; j++)
  488. encoded_exp[k+j] = exp1[i];
  489. k += group_size;
  490. }
  491. return 4 + (nb_groups / 3) * 7;
  492. }
  493. /**
  494. * Encode exponents from original extracted form to what the decoder will see.
  495. * This copies and groups exponents based on exponent strategy and reduces
  496. * deltas between adjacent exponent groups so that they can be differentially
  497. * encoded.
  498. * @return bits needed to encode the exponents
  499. */
  500. static int encode_exponents(AC3EncodeContext *s,
  501. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  502. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  503. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  504. {
  505. int blk, blk1, blk2, ch;
  506. int frame_bits;
  507. frame_bits = 0;
  508. for (ch = 0; ch < s->channels; ch++) {
  509. /* for the EXP_REUSE case we select the min of the exponents */
  510. blk = 0;
  511. while (blk < AC3_MAX_BLOCKS) {
  512. blk1 = blk + 1;
  513. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE) {
  514. exponent_min(exp[blk][ch], exp[blk1][ch], s->nb_coefs[ch]);
  515. blk1++;
  516. }
  517. frame_bits += encode_exponents_blk_ch(encoded_exp[blk][ch],
  518. exp[blk][ch], s->nb_coefs[ch],
  519. exp_strategy[blk][ch]);
  520. /* copy encoded exponents for reuse case */
  521. for (blk2 = blk+1; blk2 < blk1; blk2++) {
  522. memcpy(encoded_exp[blk2][ch], encoded_exp[blk][ch],
  523. s->nb_coefs[ch] * sizeof(uint8_t));
  524. }
  525. blk = blk1;
  526. }
  527. }
  528. return frame_bits;
  529. }
  530. /**
  531. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  532. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  533. * and encode final exponents.
  534. * @return bits needed to encode the exponents
  535. */
  536. static int process_exponents(AC3EncodeContext *s,
  537. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  538. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  539. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  540. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  541. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  542. {
  543. extract_exponents(s, mdct_coef, exp_shift, exp);
  544. compute_exp_strategy(s, exp_strategy, exp);
  545. return encode_exponents(s, exp, exp_strategy, encoded_exp);
  546. }
  547. /**
  548. * Calculate the number of bits needed to encode a set of mantissas.
  549. */
  550. static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
  551. {
  552. int bits, mant, i;
  553. bits = 0;
  554. for (i = 0; i < nb_coefs; i++) {
  555. mant = m[i];
  556. switch (mant) {
  557. case 0:
  558. /* nothing */
  559. break;
  560. case 1:
  561. /* 3 mantissa in 5 bits */
  562. if (s->mant1_cnt == 0)
  563. bits += 5;
  564. if (++s->mant1_cnt == 3)
  565. s->mant1_cnt = 0;
  566. break;
  567. case 2:
  568. /* 3 mantissa in 7 bits */
  569. if (s->mant2_cnt == 0)
  570. bits += 7;
  571. if (++s->mant2_cnt == 3)
  572. s->mant2_cnt = 0;
  573. break;
  574. case 3:
  575. bits += 3;
  576. break;
  577. case 4:
  578. /* 2 mantissa in 7 bits */
  579. if (s->mant4_cnt == 0)
  580. bits += 7;
  581. if (++s->mant4_cnt == 2)
  582. s->mant4_cnt = 0;
  583. break;
  584. case 14:
  585. bits += 14;
  586. break;
  587. case 15:
  588. bits += 16;
  589. break;
  590. default:
  591. bits += mant - 1;
  592. break;
  593. }
  594. }
  595. return bits;
  596. }
  597. /**
  598. * Calculate masking curve based on the final exponents.
  599. * Also calculate the power spectral densities to use in future calculations.
  600. */
  601. static void bit_alloc_masking(AC3EncodeContext *s,
  602. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  603. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  604. int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  605. int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
  606. {
  607. int blk, ch;
  608. int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
  609. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  610. for (ch = 0; ch < s->channels; ch++) {
  611. if(exp_strategy[blk][ch] == EXP_REUSE) {
  612. memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*sizeof(psd[0][0][0]));
  613. memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
  614. } else {
  615. ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
  616. s->nb_coefs[ch],
  617. psd[blk][ch], band_psd[blk][ch]);
  618. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
  619. 0, s->nb_coefs[ch],
  620. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  621. ch == s->lfe_channel,
  622. DBA_NONE, 0, NULL, NULL, NULL,
  623. mask[blk][ch]);
  624. }
  625. }
  626. }
  627. }
  628. /**
  629. * Run the bit allocation with a given SNR offset.
  630. * This calculates the bit allocation pointers that will be used to determine
  631. * the quantization of each mantissa.
  632. * @return the number of remaining bits (positive or negative) if the given
  633. * SNR offset is used to quantize the mantissas.
  634. */
  635. static int bit_alloc(AC3EncodeContext *s,
  636. int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
  637. int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  638. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  639. int frame_bits, int coarse_snr_offset, int fine_snr_offset)
  640. {
  641. int blk, ch;
  642. int snr_offset;
  643. snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
  644. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  645. s->mant1_cnt = 0;
  646. s->mant2_cnt = 0;
  647. s->mant4_cnt = 0;
  648. for (ch = 0; ch < s->channels; ch++) {
  649. ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
  650. s->nb_coefs[ch], snr_offset,
  651. s->bit_alloc.floor, ff_ac3_bap_tab,
  652. bap[blk][ch]);
  653. frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
  654. }
  655. }
  656. return 8 * s->frame_size - frame_bits;
  657. }
  658. #define SNR_INC1 4
  659. /**
  660. * Perform bit allocation search.
  661. * Finds the SNR offset value that maximizes quality and fits in the specified
  662. * frame size. Output is the SNR offset and a set of bit allocation pointers
  663. * used to quantize the mantissas.
  664. */
  665. static int compute_bit_allocation(AC3EncodeContext *s,
  666. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  667. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  668. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  669. int frame_bits)
  670. {
  671. int blk, ch;
  672. int coarse_snr_offset, fine_snr_offset;
  673. uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  674. int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  675. int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
  676. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  677. /* init default parameters */
  678. s->slow_decay_code = 2;
  679. s->fast_decay_code = 1;
  680. s->slow_gain_code = 1;
  681. s->db_per_bit_code = 2;
  682. s->floor_code = 4;
  683. for (ch = 0; ch < s->channels; ch++)
  684. s->fast_gain_code[ch] = 4;
  685. /* compute real values */
  686. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  687. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  688. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  689. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  690. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  691. /* header size */
  692. frame_bits += 65;
  693. // if (s->channel_mode == 2)
  694. // frame_bits += 2;
  695. frame_bits += frame_bits_inc[s->channel_mode];
  696. /* audio blocks */
  697. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  698. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  699. if (s->channel_mode == AC3_CHMODE_STEREO) {
  700. frame_bits++; /* rematstr */
  701. if (!blk)
  702. frame_bits += 4;
  703. }
  704. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  705. if (s->lfe_on)
  706. frame_bits++; /* lfeexpstr */
  707. for (ch = 0; ch < s->fbw_channels; ch++) {
  708. if (exp_strategy[blk][ch] != EXP_REUSE)
  709. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  710. }
  711. frame_bits++; /* baie */
  712. frame_bits++; /* snr */
  713. frame_bits += 2; /* delta / skip */
  714. }
  715. frame_bits++; /* cplinu for block 0 */
  716. /* bit alloc info */
  717. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  718. /* csnroffset[6] */
  719. /* (fsnoffset[4] + fgaincod[4]) * c */
  720. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  721. /* auxdatae, crcrsv */
  722. frame_bits += 2;
  723. /* CRC */
  724. frame_bits += 16;
  725. /* calculate psd and masking curve before doing bit allocation */
  726. bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
  727. /* now the big work begins : do the bit allocation. Modify the snr
  728. offset until we can pack everything in the requested frame size */
  729. coarse_snr_offset = s->coarse_snr_offset;
  730. while (coarse_snr_offset >= 0 &&
  731. bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
  732. coarse_snr_offset -= SNR_INC1;
  733. if (coarse_snr_offset < 0) {
  734. av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  735. return -1;
  736. }
  737. while (coarse_snr_offset + SNR_INC1 <= 63 &&
  738. bit_alloc(s, mask, psd, bap1, frame_bits,
  739. coarse_snr_offset + SNR_INC1, 0) >= 0) {
  740. coarse_snr_offset += SNR_INC1;
  741. memcpy(bap, bap1, sizeof(bap1));
  742. }
  743. while (coarse_snr_offset + 1 <= 63 &&
  744. bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
  745. coarse_snr_offset++;
  746. memcpy(bap, bap1, sizeof(bap1));
  747. }
  748. fine_snr_offset = 0;
  749. while (fine_snr_offset + SNR_INC1 <= 15 &&
  750. bit_alloc(s, mask, psd, bap1, frame_bits,
  751. coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
  752. fine_snr_offset += SNR_INC1;
  753. memcpy(bap, bap1, sizeof(bap1));
  754. }
  755. while (fine_snr_offset + 1 <= 15 &&
  756. bit_alloc(s, mask, psd, bap1, frame_bits,
  757. coarse_snr_offset, fine_snr_offset + 1) >= 0) {
  758. fine_snr_offset++;
  759. memcpy(bap, bap1, sizeof(bap1));
  760. }
  761. s->coarse_snr_offset = coarse_snr_offset;
  762. for (ch = 0; ch < s->channels; ch++)
  763. s->fine_snr_offset[ch] = fine_snr_offset;
  764. return 0;
  765. }
  766. /**
  767. * Write the AC-3 frame header to the output bitstream.
  768. */
  769. static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
  770. {
  771. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  772. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  773. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  774. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  775. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  776. put_bits(&s->pb, 5, s->bitstream_id);
  777. put_bits(&s->pb, 3, s->bitstream_mode);
  778. put_bits(&s->pb, 3, s->channel_mode);
  779. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  780. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  781. if (s->channel_mode & 0x04)
  782. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  783. if (s->channel_mode == AC3_CHMODE_STEREO)
  784. put_bits(&s->pb, 2, 0); /* surround not indicated */
  785. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  786. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  787. put_bits(&s->pb, 1, 0); /* no compression control word */
  788. put_bits(&s->pb, 1, 0); /* no lang code */
  789. put_bits(&s->pb, 1, 0); /* no audio production info */
  790. put_bits(&s->pb, 1, 0); /* no copyright */
  791. put_bits(&s->pb, 1, 1); /* original bitstream */
  792. put_bits(&s->pb, 1, 0); /* no time code 1 */
  793. put_bits(&s->pb, 1, 0); /* no time code 2 */
  794. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  795. }
  796. /**
  797. * Symmetric quantization on 'levels' levels.
  798. */
  799. static inline int sym_quant(int c, int e, int levels)
  800. {
  801. int v;
  802. if (c >= 0) {
  803. v = (levels * (c << e)) >> 24;
  804. v = (v + 1) >> 1;
  805. v = (levels >> 1) + v;
  806. } else {
  807. v = (levels * ((-c) << e)) >> 24;
  808. v = (v + 1) >> 1;
  809. v = (levels >> 1) - v;
  810. }
  811. assert (v >= 0 && v < levels);
  812. return v;
  813. }
  814. /**
  815. * Asymmetric quantization on 2^qbits levels.
  816. */
  817. static inline int asym_quant(int c, int e, int qbits)
  818. {
  819. int lshift, m, v;
  820. lshift = e + qbits - 24;
  821. if (lshift >= 0)
  822. v = c << lshift;
  823. else
  824. v = c >> (-lshift);
  825. /* rounding */
  826. v = (v + 1) >> 1;
  827. m = (1 << (qbits-1));
  828. if (v >= m)
  829. v = m - 1;
  830. assert(v >= -m);
  831. return v & ((1 << qbits)-1);
  832. }
  833. /**
  834. * Write one audio block to the output bitstream.
  835. */
  836. static void output_audio_block(AC3EncodeContext *s,
  837. uint8_t exp_strategy[AC3_MAX_CHANNELS],
  838. uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  839. uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  840. int32_t mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  841. int8_t exp_shift[AC3_MAX_CHANNELS],
  842. int block_num)
  843. {
  844. int ch, nb_groups, group_size, i, baie, rbnd;
  845. uint8_t *p;
  846. uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  847. int exp0, exp1;
  848. int mant1_cnt, mant2_cnt, mant4_cnt;
  849. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
  850. int delta0, delta1, delta2;
  851. for (ch = 0; ch < s->fbw_channels; ch++)
  852. put_bits(&s->pb, 1, 0); /* no block switching */
  853. for (ch = 0; ch < s->fbw_channels; ch++)
  854. put_bits(&s->pb, 1, 1); /* no dither */
  855. put_bits(&s->pb, 1, 0); /* no dynamic range */
  856. if (!block_num) {
  857. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  858. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  859. } else {
  860. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  861. }
  862. if (s->channel_mode == AC3_CHMODE_STEREO) {
  863. if (!block_num) {
  864. /* first block must define rematrixing (rematstr) */
  865. put_bits(&s->pb, 1, 1);
  866. /* dummy rematrixing rematflg(1:4)=0 */
  867. for (rbnd = 0; rbnd < 4; rbnd++)
  868. put_bits(&s->pb, 1, 0);
  869. } else {
  870. /* no matrixing (but should be used in the future) */
  871. put_bits(&s->pb, 1, 0);
  872. }
  873. }
  874. /* exponent strategy */
  875. for (ch = 0; ch < s->fbw_channels; ch++)
  876. put_bits(&s->pb, 2, exp_strategy[ch]);
  877. if (s->lfe_on)
  878. put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
  879. /* bandwidth */
  880. for (ch = 0; ch < s->fbw_channels; ch++) {
  881. if (exp_strategy[ch] != EXP_REUSE)
  882. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  883. }
  884. /* exponents */
  885. for (ch = 0; ch < s->channels; ch++) {
  886. if (exp_strategy[ch] == EXP_REUSE)
  887. continue;
  888. group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
  889. nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
  890. p = encoded_exp[ch];
  891. /* first exponent */
  892. exp1 = *p++;
  893. put_bits(&s->pb, 4, exp1);
  894. /* next ones are delta encoded */
  895. for (i = 0; i < nb_groups; i++) {
  896. /* merge three delta in one code */
  897. exp0 = exp1;
  898. exp1 = p[0];
  899. p += group_size;
  900. delta0 = exp1 - exp0 + 2;
  901. exp0 = exp1;
  902. exp1 = p[0];
  903. p += group_size;
  904. delta1 = exp1 - exp0 + 2;
  905. exp0 = exp1;
  906. exp1 = p[0];
  907. p += group_size;
  908. delta2 = exp1 - exp0 + 2;
  909. put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
  910. }
  911. if (ch != s->lfe_channel)
  912. put_bits(&s->pb, 2, 0); /* no gain range info */
  913. }
  914. /* bit allocation info */
  915. baie = (block_num == 0);
  916. put_bits(&s->pb, 1, baie);
  917. if (baie) {
  918. put_bits(&s->pb, 2, s->slow_decay_code);
  919. put_bits(&s->pb, 2, s->fast_decay_code);
  920. put_bits(&s->pb, 2, s->slow_gain_code);
  921. put_bits(&s->pb, 2, s->db_per_bit_code);
  922. put_bits(&s->pb, 3, s->floor_code);
  923. }
  924. /* snr offset */
  925. put_bits(&s->pb, 1, baie);
  926. if (baie) {
  927. put_bits(&s->pb, 6, s->coarse_snr_offset);
  928. for (ch = 0; ch < s->channels; ch++) {
  929. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  930. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  931. }
  932. }
  933. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  934. put_bits(&s->pb, 1, 0); /* no data to skip */
  935. /* mantissa encoding : we use two passes to handle the grouping. A
  936. one pass method may be faster, but it would necessitate to
  937. modify the output stream. */
  938. /* first pass: quantize */
  939. mant1_cnt = mant2_cnt = mant4_cnt = 0;
  940. qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
  941. for (ch = 0; ch < s->channels; ch++) {
  942. int b, c, e, v;
  943. for (i = 0; i < s->nb_coefs[ch]; i++) {
  944. c = mdct_coef[ch][i];
  945. e = encoded_exp[ch][i] - exp_shift[ch];
  946. b = bap[ch][i];
  947. switch (b) {
  948. case 0:
  949. v = 0;
  950. break;
  951. case 1:
  952. v = sym_quant(c, e, 3);
  953. switch (mant1_cnt) {
  954. case 0:
  955. qmant1_ptr = &qmant[ch][i];
  956. v = 9 * v;
  957. mant1_cnt = 1;
  958. break;
  959. case 1:
  960. *qmant1_ptr += 3 * v;
  961. mant1_cnt = 2;
  962. v = 128;
  963. break;
  964. default:
  965. *qmant1_ptr += v;
  966. mant1_cnt = 0;
  967. v = 128;
  968. break;
  969. }
  970. break;
  971. case 2:
  972. v = sym_quant(c, e, 5);
  973. switch (mant2_cnt) {
  974. case 0:
  975. qmant2_ptr = &qmant[ch][i];
  976. v = 25 * v;
  977. mant2_cnt = 1;
  978. break;
  979. case 1:
  980. *qmant2_ptr += 5 * v;
  981. mant2_cnt = 2;
  982. v = 128;
  983. break;
  984. default:
  985. *qmant2_ptr += v;
  986. mant2_cnt = 0;
  987. v = 128;
  988. break;
  989. }
  990. break;
  991. case 3:
  992. v = sym_quant(c, e, 7);
  993. break;
  994. case 4:
  995. v = sym_quant(c, e, 11);
  996. switch (mant4_cnt) {
  997. case 0:
  998. qmant4_ptr = &qmant[ch][i];
  999. v = 11 * v;
  1000. mant4_cnt = 1;
  1001. break;
  1002. default:
  1003. *qmant4_ptr += v;
  1004. mant4_cnt = 0;
  1005. v = 128;
  1006. break;
  1007. }
  1008. break;
  1009. case 5:
  1010. v = sym_quant(c, e, 15);
  1011. break;
  1012. case 14:
  1013. v = asym_quant(c, e, 14);
  1014. break;
  1015. case 15:
  1016. v = asym_quant(c, e, 16);
  1017. break;
  1018. default:
  1019. v = asym_quant(c, e, b - 1);
  1020. break;
  1021. }
  1022. qmant[ch][i] = v;
  1023. }
  1024. }
  1025. /* second pass : output the values */
  1026. for (ch = 0; ch < s->channels; ch++) {
  1027. int b, q;
  1028. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1029. q = qmant[ch][i];
  1030. b = bap[ch][i];
  1031. switch (b) {
  1032. case 0: break;
  1033. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1034. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1035. case 3: put_bits(&s->pb, 3, q); break;
  1036. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1037. case 14: put_bits(&s->pb, 14, q); break;
  1038. case 15: put_bits(&s->pb, 16, q); break;
  1039. default: put_bits(&s->pb, b-1, q); break;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. /** CRC-16 Polynomial */
  1045. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1046. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1047. {
  1048. unsigned int c;
  1049. c = 0;
  1050. while (a) {
  1051. if (a & 1)
  1052. c ^= b;
  1053. a = a >> 1;
  1054. b = b << 1;
  1055. if (b & (1 << 16))
  1056. b ^= poly;
  1057. }
  1058. return c;
  1059. }
  1060. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1061. {
  1062. unsigned int r;
  1063. r = 1;
  1064. while (n) {
  1065. if (n & 1)
  1066. r = mul_poly(r, a, poly);
  1067. a = mul_poly(a, a, poly);
  1068. n >>= 1;
  1069. }
  1070. return r;
  1071. }
  1072. /**
  1073. * Fill the end of the frame with 0's and compute the two CRCs.
  1074. */
  1075. static void output_frame_end(AC3EncodeContext *s)
  1076. {
  1077. int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
  1078. uint8_t *frame;
  1079. frame_size = s->frame_size; /* frame size in words */
  1080. /* align to 8 bits */
  1081. flush_put_bits(&s->pb);
  1082. /* add zero bytes to reach the frame size */
  1083. frame = s->pb.buf;
  1084. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1085. assert(pad_bytes >= 0);
  1086. if (pad_bytes > 0)
  1087. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1088. /* Now we must compute both crcs : this is not so easy for crc1
  1089. because it is at the beginning of the data... */
  1090. frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
  1091. crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
  1092. frame + 4, frame_size_58 - 4));
  1093. /* XXX: could precompute crc_inv */
  1094. crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1095. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1096. AV_WB16(frame + 2, crc1);
  1097. crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
  1098. frame + frame_size_58,
  1099. frame_size - frame_size_58 - 2));
  1100. AV_WB16(frame + frame_size - 2, crc2);
  1101. }
  1102. /**
  1103. * Encode a single AC-3 frame.
  1104. */
  1105. static int ac3_encode_frame(AVCodecContext *avctx,
  1106. unsigned char *frame, int buf_size, void *data)
  1107. {
  1108. AC3EncodeContext *s = avctx->priv_data;
  1109. const int16_t *samples = data;
  1110. int blk;
  1111. int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
  1112. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1113. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1114. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
  1115. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1116. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1117. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
  1118. int frame_bits;
  1119. deinterleave_input_samples(s, samples, planar_samples);
  1120. apply_mdct(s, planar_samples, exp_shift, mdct_coef);
  1121. frame_bits = process_exponents(s, mdct_coef, exp_shift, exp, exp_strategy, encoded_exp);
  1122. /* adjust for fractional frame sizes */
  1123. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  1124. s->bits_written -= s->bit_rate;
  1125. s->samples_written -= s->sample_rate;
  1126. }
  1127. s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  1128. s->bits_written += s->frame_size * 8;
  1129. s->samples_written += AC3_FRAME_SIZE;
  1130. compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
  1131. /* everything is known... let's output the frame */
  1132. output_frame_header(s, frame);
  1133. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1134. output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
  1135. bap[blk], mdct_coef[blk], exp_shift[blk], blk);
  1136. }
  1137. output_frame_end(s);
  1138. return s->frame_size;
  1139. }
  1140. /**
  1141. * Finalize encoding and free any memory allocated by the encoder.
  1142. */
  1143. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1144. {
  1145. av_freep(&avctx->coded_frame);
  1146. return 0;
  1147. }
  1148. /**
  1149. * Set channel information during initialization.
  1150. */
  1151. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1152. int64_t *channel_layout)
  1153. {
  1154. int ch_layout;
  1155. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1156. return AVERROR(EINVAL);
  1157. if ((uint64_t)*channel_layout > 0x7FF)
  1158. return AVERROR(EINVAL);
  1159. ch_layout = *channel_layout;
  1160. if (!ch_layout)
  1161. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1162. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1163. return AVERROR(EINVAL);
  1164. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1165. s->channels = channels;
  1166. s->fbw_channels = channels - s->lfe_on;
  1167. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1168. if (s->lfe_on)
  1169. ch_layout -= AV_CH_LOW_FREQUENCY;
  1170. switch (ch_layout) {
  1171. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1172. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1173. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1174. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1175. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1176. case AV_CH_LAYOUT_QUAD:
  1177. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1178. case AV_CH_LAYOUT_5POINT0:
  1179. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1180. default:
  1181. return AVERROR(EINVAL);
  1182. }
  1183. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1184. *channel_layout = ch_layout;
  1185. if (s->lfe_on)
  1186. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1187. return 0;
  1188. }
  1189. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1190. {
  1191. int i, ret;
  1192. /* validate channel layout */
  1193. if (!avctx->channel_layout) {
  1194. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1195. "encoder will guess the layout, but it "
  1196. "might be incorrect.\n");
  1197. }
  1198. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1199. if (ret) {
  1200. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1201. return ret;
  1202. }
  1203. /* validate sample rate */
  1204. for (i = 0; i < 9; i++) {
  1205. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1206. break;
  1207. }
  1208. if (i == 9) {
  1209. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1210. return AVERROR(EINVAL);
  1211. }
  1212. s->sample_rate = avctx->sample_rate;
  1213. s->bit_alloc.sr_shift = i % 3;
  1214. s->bit_alloc.sr_code = i / 3;
  1215. /* validate bit rate */
  1216. for (i = 0; i < 19; i++) {
  1217. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1218. break;
  1219. }
  1220. if (i == 19) {
  1221. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1222. return AVERROR(EINVAL);
  1223. }
  1224. s->bit_rate = avctx->bit_rate;
  1225. s->frame_size_code = i << 1;
  1226. return 0;
  1227. }
  1228. /**
  1229. * Set bandwidth for all channels.
  1230. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1231. * default value will be used.
  1232. */
  1233. static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
  1234. {
  1235. int ch, bw_code;
  1236. if (cutoff) {
  1237. /* calculate bandwidth based on user-specified cutoff frequency */
  1238. int fbw_coeffs;
  1239. cutoff = av_clip(cutoff, 1, s->sample_rate >> 1);
  1240. fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1241. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1242. } else {
  1243. /* use default bandwidth setting */
  1244. /* XXX: should compute the bandwidth according to the frame
  1245. size, so that we avoid annoying high frequency artifacts */
  1246. bw_code = 50;
  1247. }
  1248. /* set number of coefficients for each channel */
  1249. for (ch = 0; ch < s->fbw_channels; ch++) {
  1250. s->bandwidth_code[ch] = bw_code;
  1251. s->nb_coefs[ch] = bw_code * 3 + 73;
  1252. }
  1253. if (s->lfe_on)
  1254. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1255. }
  1256. /**
  1257. * Initialize the encoder.
  1258. */
  1259. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1260. {
  1261. AC3EncodeContext *s = avctx->priv_data;
  1262. int ret;
  1263. avctx->frame_size = AC3_FRAME_SIZE;
  1264. ac3_common_init();
  1265. ret = validate_options(avctx, s);
  1266. if (ret)
  1267. return ret;
  1268. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1269. s->bitstream_mode = 0; /* complete main audio service */
  1270. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1271. s->bits_written = 0;
  1272. s->samples_written = 0;
  1273. s->frame_size = s->frame_size_min;
  1274. set_bandwidth(s, avctx->cutoff);
  1275. /* initial snr offset */
  1276. s->coarse_snr_offset = 40;
  1277. mdct_init(9);
  1278. avctx->coded_frame= avcodec_alloc_frame();
  1279. avctx->coded_frame->key_frame= 1;
  1280. return 0;
  1281. }
  1282. #ifdef TEST
  1283. /*************************************************************************/
  1284. /* TEST */
  1285. #include "libavutil/lfg.h"
  1286. #define FN (MDCT_SAMPLES/4)
  1287. static void fft_test(AVLFG *lfg)
  1288. {
  1289. IComplex in[FN], in1[FN];
  1290. int k, n, i;
  1291. float sum_re, sum_im, a;
  1292. for (i = 0; i < FN; i++) {
  1293. in[i].re = av_lfg_get(lfg) % 65535 - 32767;
  1294. in[i].im = av_lfg_get(lfg) % 65535 - 32767;
  1295. in1[i] = in[i];
  1296. }
  1297. fft(in, 7);
  1298. /* do it by hand */
  1299. for (k = 0; k < FN; k++) {
  1300. sum_re = 0;
  1301. sum_im = 0;
  1302. for (n = 0; n < FN; n++) {
  1303. a = -2 * M_PI * (n * k) / FN;
  1304. sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
  1305. sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
  1306. }
  1307. av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
  1308. k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
  1309. }
  1310. }
  1311. static void mdct_test(AVLFG *lfg)
  1312. {
  1313. int16_t input[MDCT_SAMPLES];
  1314. int32_t output[AC3_MAX_COEFS];
  1315. float input1[MDCT_SAMPLES];
  1316. float output1[AC3_MAX_COEFS];
  1317. float s, a, err, e, emax;
  1318. int i, k, n;
  1319. for (i = 0; i < MDCT_SAMPLES; i++) {
  1320. input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
  1321. input1[i] = input[i];
  1322. }
  1323. mdct512(output, input);
  1324. /* do it by hand */
  1325. for (k = 0; k < AC3_MAX_COEFS; k++) {
  1326. s = 0;
  1327. for (n = 0; n < MDCT_SAMPLES; n++) {
  1328. a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
  1329. s += input1[n] * cos(a);
  1330. }
  1331. output1[k] = -2 * s / MDCT_SAMPLES;
  1332. }
  1333. err = 0;
  1334. emax = 0;
  1335. for (i = 0; i < AC3_MAX_COEFS; i++) {
  1336. av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
  1337. e = output[i] - output1[i];
  1338. if (e > emax)
  1339. emax = e;
  1340. err += e * e;
  1341. }
  1342. av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
  1343. }
  1344. int main(void)
  1345. {
  1346. AVLFG lfg;
  1347. av_log_set_level(AV_LOG_DEBUG);
  1348. mdct_init(9);
  1349. fft_test(&lfg);
  1350. mdct_test(&lfg);
  1351. return 0;
  1352. }
  1353. #endif /* TEST */
  1354. AVCodec ac3_encoder = {
  1355. "ac3",
  1356. AVMEDIA_TYPE_AUDIO,
  1357. CODEC_ID_AC3,
  1358. sizeof(AC3EncodeContext),
  1359. ac3_encode_init,
  1360. ac3_encode_frame,
  1361. ac3_encode_close,
  1362. NULL,
  1363. .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
  1364. .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
  1365. .channel_layouts = (const int64_t[]){
  1366. AV_CH_LAYOUT_MONO,
  1367. AV_CH_LAYOUT_STEREO,
  1368. AV_CH_LAYOUT_2_1,
  1369. AV_CH_LAYOUT_SURROUND,
  1370. AV_CH_LAYOUT_2_2,
  1371. AV_CH_LAYOUT_QUAD,
  1372. AV_CH_LAYOUT_4POINT0,
  1373. AV_CH_LAYOUT_5POINT0,
  1374. AV_CH_LAYOUT_5POINT0_BACK,
  1375. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  1376. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  1377. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  1378. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  1379. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  1380. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  1381. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  1382. AV_CH_LAYOUT_5POINT1,
  1383. AV_CH_LAYOUT_5POINT1_BACK,
  1384. 0 },
  1385. };