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.

1764 lines
55KB

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