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.

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