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.

1741 lines
51KB

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