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.

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