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.

1767 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 coarse_snr_offset, int fine_snr_offset)
  789. {
  790. int blk, ch;
  791. int snr_offset, mantissa_bits;
  792. snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 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. #define SNR_INC1 4
  809. /**
  810. * Perform bit allocation search.
  811. * Finds the SNR offset value that maximizes quality and fits in the specified
  812. * frame size. Output is the SNR offset and a set of bit allocation pointers
  813. * used to quantize the mantissas.
  814. */
  815. static int compute_bit_allocation(AC3EncodeContext *s,
  816. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  817. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  818. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS])
  819. {
  820. int ch;
  821. int bits_left;
  822. int coarse_snr_offset, fine_snr_offset;
  823. uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  824. int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  825. int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
  826. /* count frame bits other than exponents and mantissas */
  827. count_frame_bits(s, exp_strategy);
  828. /* calculate psd and masking curve before doing bit allocation */
  829. bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
  830. /* now the big work begins : do the bit allocation. Modify the snr
  831. offset until we can pack everything in the requested frame size */
  832. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  833. coarse_snr_offset = s->coarse_snr_offset;
  834. while (coarse_snr_offset >= 0 &&
  835. bit_alloc(s, mask, psd, bap, coarse_snr_offset, 0) > bits_left)
  836. coarse_snr_offset -= SNR_INC1;
  837. if (coarse_snr_offset < 0) {
  838. return AVERROR(EINVAL);
  839. }
  840. while (coarse_snr_offset + SNR_INC1 <= 63 &&
  841. bit_alloc(s, mask, psd, bap1,
  842. coarse_snr_offset + SNR_INC1, 0) <= bits_left) {
  843. coarse_snr_offset += SNR_INC1;
  844. memcpy(bap, bap1, sizeof(bap1));
  845. }
  846. while (coarse_snr_offset + 1 <= 63 &&
  847. bit_alloc(s, mask, psd, bap1, coarse_snr_offset + 1, 0) <= bits_left) {
  848. coarse_snr_offset++;
  849. memcpy(bap, bap1, sizeof(bap1));
  850. }
  851. fine_snr_offset = 0;
  852. while (fine_snr_offset + SNR_INC1 <= 15 &&
  853. bit_alloc(s, mask, psd, bap1,
  854. coarse_snr_offset, fine_snr_offset + SNR_INC1) <= bits_left) {
  855. fine_snr_offset += SNR_INC1;
  856. memcpy(bap, bap1, sizeof(bap1));
  857. }
  858. while (fine_snr_offset + 1 <= 15 &&
  859. bit_alloc(s, mask, psd, bap1,
  860. coarse_snr_offset, fine_snr_offset + 1) <= bits_left) {
  861. fine_snr_offset++;
  862. memcpy(bap, bap1, sizeof(bap1));
  863. }
  864. s->coarse_snr_offset = coarse_snr_offset;
  865. for (ch = 0; ch < s->channels; ch++)
  866. s->fine_snr_offset[ch] = fine_snr_offset;
  867. return 0;
  868. }
  869. /**
  870. * Symmetric quantization on 'levels' levels.
  871. */
  872. static inline int sym_quant(int c, int e, int levels)
  873. {
  874. int v;
  875. if (c >= 0) {
  876. v = (levels * (c << e)) >> 24;
  877. v = (v + 1) >> 1;
  878. v = (levels >> 1) + v;
  879. } else {
  880. v = (levels * ((-c) << e)) >> 24;
  881. v = (v + 1) >> 1;
  882. v = (levels >> 1) - v;
  883. }
  884. assert (v >= 0 && v < levels);
  885. return v;
  886. }
  887. /**
  888. * Asymmetric quantization on 2^qbits levels.
  889. */
  890. static inline int asym_quant(int c, int e, int qbits)
  891. {
  892. int lshift, m, v;
  893. lshift = e + qbits - 24;
  894. if (lshift >= 0)
  895. v = c << lshift;
  896. else
  897. v = c >> (-lshift);
  898. /* rounding */
  899. v = (v + 1) >> 1;
  900. m = (1 << (qbits-1));
  901. if (v >= m)
  902. v = m - 1;
  903. assert(v >= -m);
  904. return v & ((1 << qbits)-1);
  905. }
  906. /**
  907. * Quantize a set of mantissas for a single channel in a single block.
  908. */
  909. static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
  910. int32_t *mdct_coef, int8_t exp_shift,
  911. uint8_t *encoded_exp, uint8_t *bap,
  912. uint16_t *qmant, int n)
  913. {
  914. int i;
  915. for (i = 0; i < n; i++) {
  916. int v;
  917. int c = mdct_coef[i];
  918. int e = encoded_exp[i] - exp_shift;
  919. int b = bap[i];
  920. switch (b) {
  921. case 0:
  922. v = 0;
  923. break;
  924. case 1:
  925. v = sym_quant(c, e, 3);
  926. switch (s->mant1_cnt) {
  927. case 0:
  928. s->qmant1_ptr = &qmant[i];
  929. v = 9 * v;
  930. s->mant1_cnt = 1;
  931. break;
  932. case 1:
  933. *s->qmant1_ptr += 3 * v;
  934. s->mant1_cnt = 2;
  935. v = 128;
  936. break;
  937. default:
  938. *s->qmant1_ptr += v;
  939. s->mant1_cnt = 0;
  940. v = 128;
  941. break;
  942. }
  943. break;
  944. case 2:
  945. v = sym_quant(c, e, 5);
  946. switch (s->mant2_cnt) {
  947. case 0:
  948. s->qmant2_ptr = &qmant[i];
  949. v = 25 * v;
  950. s->mant2_cnt = 1;
  951. break;
  952. case 1:
  953. *s->qmant2_ptr += 5 * v;
  954. s->mant2_cnt = 2;
  955. v = 128;
  956. break;
  957. default:
  958. *s->qmant2_ptr += v;
  959. s->mant2_cnt = 0;
  960. v = 128;
  961. break;
  962. }
  963. break;
  964. case 3:
  965. v = sym_quant(c, e, 7);
  966. break;
  967. case 4:
  968. v = sym_quant(c, e, 11);
  969. switch (s->mant4_cnt) {
  970. case 0:
  971. s->qmant4_ptr = &qmant[i];
  972. v = 11 * v;
  973. s->mant4_cnt = 1;
  974. break;
  975. default:
  976. *s->qmant4_ptr += v;
  977. s->mant4_cnt = 0;
  978. v = 128;
  979. break;
  980. }
  981. break;
  982. case 5:
  983. v = sym_quant(c, e, 15);
  984. break;
  985. case 14:
  986. v = asym_quant(c, e, 14);
  987. break;
  988. case 15:
  989. v = asym_quant(c, e, 16);
  990. break;
  991. default:
  992. v = asym_quant(c, e, b - 1);
  993. break;
  994. }
  995. qmant[i] = v;
  996. }
  997. }
  998. /**
  999. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1000. */
  1001. static void quantize_mantissas(AC3EncodeContext *s,
  1002. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1003. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  1004. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1005. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1006. uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  1007. {
  1008. int blk, ch;
  1009. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1010. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  1011. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  1012. for (ch = 0; ch < s->channels; ch++) {
  1013. quantize_mantissas_blk_ch(s, mdct_coef[blk][ch], exp_shift[blk][ch],
  1014. encoded_exp[blk][ch], bap[blk][ch],
  1015. qmant[blk][ch], s->nb_coefs[ch]);
  1016. }
  1017. }
  1018. }
  1019. /**
  1020. * Write the AC-3 frame header to the output bitstream.
  1021. */
  1022. static void output_frame_header(AC3EncodeContext *s)
  1023. {
  1024. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1025. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1026. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1027. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1028. put_bits(&s->pb, 5, s->bitstream_id);
  1029. put_bits(&s->pb, 3, s->bitstream_mode);
  1030. put_bits(&s->pb, 3, s->channel_mode);
  1031. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1032. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  1033. if (s->channel_mode & 0x04)
  1034. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  1035. if (s->channel_mode == AC3_CHMODE_STEREO)
  1036. put_bits(&s->pb, 2, 0); /* surround not indicated */
  1037. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1038. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  1039. put_bits(&s->pb, 1, 0); /* no compression control word */
  1040. put_bits(&s->pb, 1, 0); /* no lang code */
  1041. put_bits(&s->pb, 1, 0); /* no audio production info */
  1042. put_bits(&s->pb, 1, 0); /* no copyright */
  1043. put_bits(&s->pb, 1, 1); /* original bitstream */
  1044. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1045. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1046. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1047. }
  1048. /**
  1049. * Write one audio block to the output bitstream.
  1050. */
  1051. static void output_audio_block(AC3EncodeContext *s,
  1052. uint8_t exp_strategy[AC3_MAX_CHANNELS],
  1053. uint8_t num_exp_groups[AC3_MAX_CHANNELS],
  1054. uint8_t grouped_exp[AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS],
  1055. uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1056. uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1057. int block_num)
  1058. {
  1059. int ch, i, baie, rbnd;
  1060. for (ch = 0; ch < s->fbw_channels; ch++)
  1061. put_bits(&s->pb, 1, 0); /* no block switching */
  1062. for (ch = 0; ch < s->fbw_channels; ch++)
  1063. put_bits(&s->pb, 1, 1); /* no dither */
  1064. put_bits(&s->pb, 1, 0); /* no dynamic range */
  1065. if (!block_num) {
  1066. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1067. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1068. } else {
  1069. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1070. }
  1071. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1072. if (!block_num) {
  1073. /* first block must define rematrixing (rematstr) */
  1074. put_bits(&s->pb, 1, 1);
  1075. /* dummy rematrixing rematflg(1:4)=0 */
  1076. for (rbnd = 0; rbnd < 4; rbnd++)
  1077. put_bits(&s->pb, 1, 0);
  1078. } else {
  1079. /* no matrixing (but should be used in the future) */
  1080. put_bits(&s->pb, 1, 0);
  1081. }
  1082. }
  1083. /* exponent strategy */
  1084. for (ch = 0; ch < s->fbw_channels; ch++)
  1085. put_bits(&s->pb, 2, exp_strategy[ch]);
  1086. if (s->lfe_on)
  1087. put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
  1088. /* bandwidth */
  1089. for (ch = 0; ch < s->fbw_channels; ch++) {
  1090. if (exp_strategy[ch] != EXP_REUSE)
  1091. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1092. }
  1093. /* exponents */
  1094. for (ch = 0; ch < s->channels; ch++) {
  1095. if (exp_strategy[ch] == EXP_REUSE)
  1096. continue;
  1097. /* first exponent */
  1098. put_bits(&s->pb, 4, grouped_exp[ch][0]);
  1099. /* next ones are delta-encoded and grouped */
  1100. for (i = 1; i <= num_exp_groups[ch]; i++)
  1101. put_bits(&s->pb, 7, grouped_exp[ch][i]);
  1102. if (ch != s->lfe_channel)
  1103. put_bits(&s->pb, 2, 0); /* no gain range info */
  1104. }
  1105. /* bit allocation info */
  1106. baie = (block_num == 0);
  1107. put_bits(&s->pb, 1, baie);
  1108. if (baie) {
  1109. put_bits(&s->pb, 2, s->slow_decay_code);
  1110. put_bits(&s->pb, 2, s->fast_decay_code);
  1111. put_bits(&s->pb, 2, s->slow_gain_code);
  1112. put_bits(&s->pb, 2, s->db_per_bit_code);
  1113. put_bits(&s->pb, 3, s->floor_code);
  1114. }
  1115. /* snr offset */
  1116. put_bits(&s->pb, 1, baie);
  1117. if (baie) {
  1118. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1119. for (ch = 0; ch < s->channels; ch++) {
  1120. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1121. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1122. }
  1123. }
  1124. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1125. put_bits(&s->pb, 1, 0); /* no data to skip */
  1126. /* mantissa encoding */
  1127. for (ch = 0; ch < s->channels; ch++) {
  1128. int b, q;
  1129. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1130. q = qmant[ch][i];
  1131. b = bap[ch][i];
  1132. switch (b) {
  1133. case 0: break;
  1134. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1135. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1136. case 3: put_bits(&s->pb, 3, q); break;
  1137. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1138. case 14: put_bits(&s->pb, 14, q); break;
  1139. case 15: put_bits(&s->pb, 16, q); break;
  1140. default: put_bits(&s->pb, b-1, q); break;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. /** CRC-16 Polynomial */
  1146. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1147. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1148. {
  1149. unsigned int c;
  1150. c = 0;
  1151. while (a) {
  1152. if (a & 1)
  1153. c ^= b;
  1154. a = a >> 1;
  1155. b = b << 1;
  1156. if (b & (1 << 16))
  1157. b ^= poly;
  1158. }
  1159. return c;
  1160. }
  1161. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1162. {
  1163. unsigned int r;
  1164. r = 1;
  1165. while (n) {
  1166. if (n & 1)
  1167. r = mul_poly(r, a, poly);
  1168. a = mul_poly(a, a, poly);
  1169. n >>= 1;
  1170. }
  1171. return r;
  1172. }
  1173. /**
  1174. * Fill the end of the frame with 0's and compute the two CRCs.
  1175. */
  1176. static void output_frame_end(AC3EncodeContext *s)
  1177. {
  1178. int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
  1179. uint8_t *frame;
  1180. frame_size = s->frame_size; /* frame size in words */
  1181. /* align to 8 bits */
  1182. flush_put_bits(&s->pb);
  1183. /* add zero bytes to reach the frame size */
  1184. frame = s->pb.buf;
  1185. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1186. assert(pad_bytes >= 0);
  1187. if (pad_bytes > 0)
  1188. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1189. /* Now we must compute both crcs : this is not so easy for crc1
  1190. because it is at the beginning of the data... */
  1191. frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
  1192. crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
  1193. frame + 4, frame_size_58 - 4));
  1194. /* XXX: could precompute crc_inv */
  1195. crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1196. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1197. AV_WB16(frame + 2, crc1);
  1198. crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
  1199. frame + frame_size_58,
  1200. frame_size - frame_size_58 - 2));
  1201. AV_WB16(frame + frame_size - 2, crc2);
  1202. }
  1203. /**
  1204. * Write the frame to the output bitstream.
  1205. */
  1206. static void output_frame(AC3EncodeContext *s,
  1207. unsigned char *frame,
  1208. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  1209. uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
  1210. uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS],
  1211. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
  1212. uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
  1213. {
  1214. int blk;
  1215. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1216. output_frame_header(s);
  1217. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1218. output_audio_block(s, exp_strategy[blk], num_exp_groups[blk],
  1219. grouped_exp[blk], bap[blk], qmant[blk], blk);
  1220. }
  1221. output_frame_end(s);
  1222. }
  1223. /**
  1224. * Encode a single AC-3 frame.
  1225. */
  1226. static int ac3_encode_frame(AVCodecContext *avctx,
  1227. unsigned char *frame, int buf_size, void *data)
  1228. {
  1229. AC3EncodeContext *s = avctx->priv_data;
  1230. const int16_t *samples = data;
  1231. int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
  1232. int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1233. uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1234. uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
  1235. uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1236. uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
  1237. uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
  1238. uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1239. int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
  1240. uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
  1241. int ret;
  1242. if (s->bit_alloc.sr_code == 1)
  1243. adjust_frame_size(s);
  1244. deinterleave_input_samples(s, samples, planar_samples);
  1245. apply_mdct(s, planar_samples, exp_shift, mdct_coef);
  1246. process_exponents(s, mdct_coef, exp_shift, exp, exp_strategy, encoded_exp,
  1247. num_exp_groups, grouped_exp);
  1248. ret = compute_bit_allocation(s, bap, encoded_exp, exp_strategy);
  1249. if (ret) {
  1250. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1251. return ret;
  1252. }
  1253. quantize_mantissas(s, mdct_coef, exp_shift, encoded_exp, bap, qmant);
  1254. output_frame(s, frame, exp_strategy, num_exp_groups, grouped_exp, bap, qmant);
  1255. return s->frame_size;
  1256. }
  1257. /**
  1258. * Finalize encoding and free any memory allocated by the encoder.
  1259. */
  1260. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1261. {
  1262. av_freep(&avctx->coded_frame);
  1263. return 0;
  1264. }
  1265. /**
  1266. * Set channel information during initialization.
  1267. */
  1268. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1269. int64_t *channel_layout)
  1270. {
  1271. int ch_layout;
  1272. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1273. return AVERROR(EINVAL);
  1274. if ((uint64_t)*channel_layout > 0x7FF)
  1275. return AVERROR(EINVAL);
  1276. ch_layout = *channel_layout;
  1277. if (!ch_layout)
  1278. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1279. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1280. return AVERROR(EINVAL);
  1281. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1282. s->channels = channels;
  1283. s->fbw_channels = channels - s->lfe_on;
  1284. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1285. if (s->lfe_on)
  1286. ch_layout -= AV_CH_LOW_FREQUENCY;
  1287. switch (ch_layout) {
  1288. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1289. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1290. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1291. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1292. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1293. case AV_CH_LAYOUT_QUAD:
  1294. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1295. case AV_CH_LAYOUT_5POINT0:
  1296. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1297. default:
  1298. return AVERROR(EINVAL);
  1299. }
  1300. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1301. *channel_layout = ch_layout;
  1302. if (s->lfe_on)
  1303. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1304. return 0;
  1305. }
  1306. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1307. {
  1308. int i, ret;
  1309. /* validate channel layout */
  1310. if (!avctx->channel_layout) {
  1311. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1312. "encoder will guess the layout, but it "
  1313. "might be incorrect.\n");
  1314. }
  1315. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1316. if (ret) {
  1317. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1318. return ret;
  1319. }
  1320. /* validate sample rate */
  1321. for (i = 0; i < 9; i++) {
  1322. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1323. break;
  1324. }
  1325. if (i == 9) {
  1326. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1327. return AVERROR(EINVAL);
  1328. }
  1329. s->sample_rate = avctx->sample_rate;
  1330. s->bit_alloc.sr_shift = i % 3;
  1331. s->bit_alloc.sr_code = i / 3;
  1332. /* validate bit rate */
  1333. for (i = 0; i < 19; i++) {
  1334. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1335. break;
  1336. }
  1337. if (i == 19) {
  1338. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1339. return AVERROR(EINVAL);
  1340. }
  1341. s->bit_rate = avctx->bit_rate;
  1342. s->frame_size_code = i << 1;
  1343. return 0;
  1344. }
  1345. /**
  1346. * Set bandwidth for all channels.
  1347. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1348. * default value will be used.
  1349. */
  1350. static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
  1351. {
  1352. int ch, bw_code;
  1353. if (cutoff) {
  1354. /* calculate bandwidth based on user-specified cutoff frequency */
  1355. int fbw_coeffs;
  1356. cutoff = av_clip(cutoff, 1, s->sample_rate >> 1);
  1357. fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1358. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1359. } else {
  1360. /* use default bandwidth setting */
  1361. /* XXX: should compute the bandwidth according to the frame
  1362. size, so that we avoid annoying high frequency artifacts */
  1363. bw_code = 50;
  1364. }
  1365. /* set number of coefficients for each channel */
  1366. for (ch = 0; ch < s->fbw_channels; ch++) {
  1367. s->bandwidth_code[ch] = bw_code;
  1368. s->nb_coefs[ch] = bw_code * 3 + 73;
  1369. }
  1370. if (s->lfe_on)
  1371. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1372. }
  1373. /**
  1374. * Initialize the encoder.
  1375. */
  1376. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1377. {
  1378. AC3EncodeContext *s = avctx->priv_data;
  1379. int ret;
  1380. avctx->frame_size = AC3_FRAME_SIZE;
  1381. ac3_common_init();
  1382. ret = validate_options(avctx, s);
  1383. if (ret)
  1384. return ret;
  1385. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1386. s->bitstream_mode = 0; /* complete main audio service */
  1387. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1388. s->bits_written = 0;
  1389. s->samples_written = 0;
  1390. s->frame_size = s->frame_size_min;
  1391. set_bandwidth(s, avctx->cutoff);
  1392. bit_alloc_init(s);
  1393. mdct_init(9);
  1394. avctx->coded_frame= avcodec_alloc_frame();
  1395. avctx->coded_frame->key_frame= 1;
  1396. return 0;
  1397. }
  1398. #ifdef TEST
  1399. /*************************************************************************/
  1400. /* TEST */
  1401. #include "libavutil/lfg.h"
  1402. #define FN (MDCT_SAMPLES/4)
  1403. static void fft_test(AVLFG *lfg)
  1404. {
  1405. IComplex in[FN], in1[FN];
  1406. int k, n, i;
  1407. float sum_re, sum_im, a;
  1408. for (i = 0; i < FN; i++) {
  1409. in[i].re = av_lfg_get(lfg) % 65535 - 32767;
  1410. in[i].im = av_lfg_get(lfg) % 65535 - 32767;
  1411. in1[i] = in[i];
  1412. }
  1413. fft(in, 7);
  1414. /* do it by hand */
  1415. for (k = 0; k < FN; k++) {
  1416. sum_re = 0;
  1417. sum_im = 0;
  1418. for (n = 0; n < FN; n++) {
  1419. a = -2 * M_PI * (n * k) / FN;
  1420. sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
  1421. sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
  1422. }
  1423. av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
  1424. k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
  1425. }
  1426. }
  1427. static void mdct_test(AVLFG *lfg)
  1428. {
  1429. int16_t input[MDCT_SAMPLES];
  1430. int32_t output[AC3_MAX_COEFS];
  1431. float input1[MDCT_SAMPLES];
  1432. float output1[AC3_MAX_COEFS];
  1433. float s, a, err, e, emax;
  1434. int i, k, n;
  1435. for (i = 0; i < MDCT_SAMPLES; i++) {
  1436. input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
  1437. input1[i] = input[i];
  1438. }
  1439. mdct512(output, input);
  1440. /* do it by hand */
  1441. for (k = 0; k < AC3_MAX_COEFS; k++) {
  1442. s = 0;
  1443. for (n = 0; n < MDCT_SAMPLES; n++) {
  1444. a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
  1445. s += input1[n] * cos(a);
  1446. }
  1447. output1[k] = -2 * s / MDCT_SAMPLES;
  1448. }
  1449. err = 0;
  1450. emax = 0;
  1451. for (i = 0; i < AC3_MAX_COEFS; i++) {
  1452. av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
  1453. e = output[i] - output1[i];
  1454. if (e > emax)
  1455. emax = e;
  1456. err += e * e;
  1457. }
  1458. av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
  1459. }
  1460. int main(void)
  1461. {
  1462. AVLFG lfg;
  1463. av_log_set_level(AV_LOG_DEBUG);
  1464. mdct_init(9);
  1465. fft_test(&lfg);
  1466. mdct_test(&lfg);
  1467. return 0;
  1468. }
  1469. #endif /* TEST */
  1470. AVCodec ac3_encoder = {
  1471. "ac3",
  1472. AVMEDIA_TYPE_AUDIO,
  1473. CODEC_ID_AC3,
  1474. sizeof(AC3EncodeContext),
  1475. ac3_encode_init,
  1476. ac3_encode_frame,
  1477. ac3_encode_close,
  1478. NULL,
  1479. .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
  1480. .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
  1481. .channel_layouts = (const int64_t[]){
  1482. AV_CH_LAYOUT_MONO,
  1483. AV_CH_LAYOUT_STEREO,
  1484. AV_CH_LAYOUT_2_1,
  1485. AV_CH_LAYOUT_SURROUND,
  1486. AV_CH_LAYOUT_2_2,
  1487. AV_CH_LAYOUT_QUAD,
  1488. AV_CH_LAYOUT_4POINT0,
  1489. AV_CH_LAYOUT_5POINT0,
  1490. AV_CH_LAYOUT_5POINT0_BACK,
  1491. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  1492. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  1493. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  1494. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  1495. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  1496. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  1497. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  1498. AV_CH_LAYOUT_5POINT1,
  1499. AV_CH_LAYOUT_5POINT1_BACK,
  1500. 0 },
  1501. };