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.

1501 lines
47KB

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