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.

1712 lines
50KB

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