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.

1081 lines
36KB

  1. /*
  2. * AC-3 Audio Decoder
  3. * This code is developed as part of Google Summer of Code 2006 Program.
  4. *
  5. * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
  6. * Copyright (c) 2007 Justin Ruggles
  7. *
  8. * Portions of this code are derived from liba52
  9. * http://liba52.sourceforge.net
  10. * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
  11. * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
  12. *
  13. * This file is part of FFmpeg.
  14. *
  15. * FFmpeg is free software; you can redistribute it and/or
  16. * modify it under the terms of the GNU General Public
  17. * License as published by the Free Software Foundation; either
  18. * version 2 of the License, or (at your option) any later version.
  19. *
  20. * FFmpeg is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. * General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public
  26. * License along with FFmpeg; if not, write to the Free Software
  27. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  28. */
  29. #include <stdio.h>
  30. #include <stddef.h>
  31. #include <math.h>
  32. #include <string.h>
  33. #include "avcodec.h"
  34. #include "ac3_parser.h"
  35. #include "bitstream.h"
  36. #include "dsputil.h"
  37. #include "random.h"
  38. /**
  39. * Table of bin locations for rematrixing bands
  40. * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
  41. */
  42. static const uint8_t rematrix_band_tbl[5] = { 13, 25, 37, 61, 253 };
  43. /* table for exponent to scale_factor mapping
  44. * scale_factor[i] = 2 ^ -(i + 15)
  45. */
  46. static float scale_factors[25];
  47. /** table for grouping exponents */
  48. static uint8_t exp_ungroup_tbl[128][3];
  49. static int16_t l3_quantizers_1[32];
  50. static int16_t l3_quantizers_2[32];
  51. static int16_t l3_quantizers_3[32];
  52. static int16_t l5_quantizers_1[128];
  53. static int16_t l5_quantizers_2[128];
  54. static int16_t l5_quantizers_3[128];
  55. static int16_t l7_quantizers[7];
  56. static int16_t l11_quantizers_1[128];
  57. static int16_t l11_quantizers_2[128];
  58. static int16_t l15_quantizers[15];
  59. static const uint8_t qntztab[16] = { 0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16 };
  60. /* Adjustmens in dB gain */
  61. #define LEVEL_MINUS_3DB 0.7071067811865476
  62. #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
  63. #define LEVEL_MINUS_6DB 0.5000000000000000
  64. #define LEVEL_PLUS_3DB 1.4142135623730951
  65. #define LEVEL_PLUS_6DB 2.0000000000000000
  66. #define LEVEL_ZERO 0.0000000000000000
  67. static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
  68. LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
  69. static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
  70. #define AC3_OUTPUT_LFEON 8
  71. typedef struct {
  72. int acmod;
  73. int cmixlev;
  74. int surmixlev;
  75. int dsurmod;
  76. int blksw[AC3_MAX_CHANNELS];
  77. int dithflag[AC3_MAX_CHANNELS];
  78. int cplinu;
  79. int chincpl[AC3_MAX_CHANNELS];
  80. int phsflginu;
  81. int cplcoe;
  82. uint32_t cplbndstrc;
  83. int rematstr;
  84. int nrematbnd;
  85. int rematflg[AC3_MAX_CHANNELS];
  86. int cplexpstr;
  87. int lfeexpstr;
  88. int chexpstr[5];
  89. int cplsnroffst;
  90. int cplfgain;
  91. int snroffst[5];
  92. int fgain[5];
  93. int lfesnroffst;
  94. int lfefgain;
  95. int cpldeltbae;
  96. int deltbae[5];
  97. int cpldeltnseg;
  98. uint8_t cpldeltoffst[8];
  99. uint8_t cpldeltlen[8];
  100. uint8_t cpldeltba[8];
  101. int deltnseg[5];
  102. uint8_t deltoffst[5][8];
  103. uint8_t deltlen[5][8];
  104. uint8_t deltba[5][8];
  105. /* Derived Attributes. */
  106. int sampling_rate;
  107. int bit_rate;
  108. int frame_size;
  109. int nchans; //number of total channels
  110. int nfchans; //number of full-bandwidth channels
  111. int lfeon; //lfe channel in use
  112. int output_mode; ///< output channel configuration
  113. int out_channels; ///< number of output channels
  114. float dynrng; //dynamic range gain
  115. float dynrng2; //dynamic range gain for 1+1 mode
  116. float cplco[5][18]; //coupling coordinates
  117. int ncplbnd; //number of coupling bands
  118. int ncplsubnd; //number of coupling sub bands
  119. int cplstrtmant; //coupling start mantissa
  120. int cplendmant; //coupling end mantissa
  121. int endmant[5]; //channel end mantissas
  122. AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
  123. int8_t dcplexps[256]; //decoded coupling exponents
  124. int8_t dexps[5][256]; //decoded fbw channel exponents
  125. int8_t dlfeexps[256]; //decoded lfe channel exponents
  126. uint8_t cplbap[256]; //coupling bit allocation pointers
  127. uint8_t bap[5][256]; //fbw channel bit allocation pointers
  128. uint8_t lfebap[256]; //lfe channel bit allocation pointers
  129. float transform_coeffs_cpl[256];
  130. DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); //transform coefficients
  131. /* For IMDCT. */
  132. MDCTContext imdct_512; //for 512 sample imdct transform
  133. MDCTContext imdct_256; //for 256 sample imdct transform
  134. DSPContext dsp; //for optimization
  135. DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][256]); //output after imdct transform and windowing
  136. DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][256]); //delay - added to the next block
  137. DECLARE_ALIGNED_16(float, tmp_imdct[256]); //temporary storage for imdct transform
  138. DECLARE_ALIGNED_16(float, tmp_output[512]); //temporary storage for output before windowing
  139. DECLARE_ALIGNED_16(float, window[256]); //window coefficients
  140. /* Miscellaneous. */
  141. GetBitContext gb;
  142. AVRandomState dith_state; //for dither generation
  143. } AC3DecodeContext;
  144. /*********** BEGIN INIT HELPER FUNCTIONS ***********/
  145. /**
  146. * Generate a Kaiser-Bessel Derived Window.
  147. */
  148. static void ac3_window_init(float *window)
  149. {
  150. int i, j;
  151. double sum = 0.0, bessel, tmp;
  152. double local_window[256];
  153. double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
  154. for (i = 0; i < 256; i++) {
  155. tmp = i * (256 - i) * alpha2;
  156. bessel = 1.0;
  157. for (j = 100; j > 0; j--) /* defaul to 100 iterations */
  158. bessel = bessel * tmp / (j * j) + 1;
  159. sum += bessel;
  160. local_window[i] = sum;
  161. }
  162. sum++;
  163. for (i = 0; i < 256; i++)
  164. window[i] = sqrt(local_window[i] / sum);
  165. }
  166. /*
  167. * Generate quantizer tables.
  168. */
  169. static void generate_quantizers_table(int16_t quantizers[], int level, int length)
  170. {
  171. int i;
  172. for (i = 0; i < length; i++)
  173. quantizers[i] = ((2 * i - level + 1) << 15) / level;
  174. }
  175. static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
  176. {
  177. int i, j;
  178. int16_t v;
  179. for (i = 0; i < length1; i++) {
  180. v = ((2 * i - level + 1) << 15) / level;
  181. for (j = 0; j < length2; j++)
  182. quantizers[i * length2 + j] = v;
  183. }
  184. for (i = length1 * length2; i < size; i++)
  185. quantizers[i] = 0;
  186. }
  187. static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
  188. {
  189. int i, j;
  190. int16_t v;
  191. for (i = 0; i < length1; i++) {
  192. v = ((2 * (i % level) - level + 1) << 15) / level;
  193. for (j = 0; j < length2; j++)
  194. quantizers[i * length2 + j] = v;
  195. }
  196. for (i = length1 * length2; i < size; i++)
  197. quantizers[i] = 0;
  198. }
  199. static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
  200. {
  201. int i, j;
  202. for (i = 0; i < length1; i++)
  203. for (j = 0; j < length2; j++)
  204. quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
  205. for (i = length1 * length2; i < size; i++)
  206. quantizers[i] = 0;
  207. }
  208. /*
  209. * Initialize tables at runtime.
  210. */
  211. static void ac3_tables_init(void)
  212. {
  213. int i;
  214. /* Quantizer ungrouping tables. */
  215. // for level-3 quantizers
  216. generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
  217. generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
  218. generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
  219. //for level-5 quantizers
  220. generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
  221. generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
  222. generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
  223. //for level-7 quantizers
  224. generate_quantizers_table(l7_quantizers, 7, 7);
  225. //for level-4 quantizers
  226. generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
  227. generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
  228. //for level-15 quantizers
  229. generate_quantizers_table(l15_quantizers, 15, 15);
  230. /* End Quantizer ungrouping tables. */
  231. //generate scale factors
  232. for (i = 0; i < 25; i++)
  233. scale_factors[i] = pow(2.0, -(i + 15));
  234. /* generate exponent tables
  235. reference: Section 7.1.3 Exponent Decoding */
  236. for(i=0; i<128; i++) {
  237. exp_ungroup_tbl[i][0] = i / 25;
  238. exp_ungroup_tbl[i][1] = (i % 25) / 5;
  239. exp_ungroup_tbl[i][2] = (i % 25) % 5;
  240. }
  241. }
  242. static int ac3_decode_init(AVCodecContext *avctx)
  243. {
  244. AC3DecodeContext *ctx = avctx->priv_data;
  245. ac3_common_init();
  246. ac3_tables_init();
  247. ff_mdct_init(&ctx->imdct_256, 8, 1);
  248. ff_mdct_init(&ctx->imdct_512, 9, 1);
  249. ac3_window_init(ctx->window);
  250. dsputil_init(&ctx->dsp, avctx);
  251. av_init_random(0, &ctx->dith_state);
  252. return 0;
  253. }
  254. /*********** END INIT FUNCTIONS ***********/
  255. /**
  256. * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
  257. * GetBitContext within AC3DecodeContext must point to
  258. * start of the synchronized ac3 bitstream.
  259. */
  260. static int ac3_parse_header(AC3DecodeContext *ctx)
  261. {
  262. AC3HeaderInfo hdr;
  263. GetBitContext *gb = &ctx->gb;
  264. int err, i;
  265. err = ff_ac3_parse_header(gb->buffer, &hdr);
  266. if(err)
  267. return err;
  268. /* get decoding parameters from header info */
  269. ctx->bit_alloc_params.fscod = hdr.fscod;
  270. ctx->acmod = hdr.acmod;
  271. ctx->cmixlev = hdr.cmixlev;
  272. ctx->surmixlev = hdr.surmixlev;
  273. ctx->dsurmod = hdr.dsurmod;
  274. ctx->lfeon = hdr.lfeon;
  275. ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
  276. ctx->sampling_rate = hdr.sample_rate;
  277. ctx->bit_rate = hdr.bit_rate;
  278. ctx->nchans = hdr.channels;
  279. ctx->nfchans = ctx->nchans - ctx->lfeon;
  280. ctx->frame_size = hdr.frame_size;
  281. /* set default output to all source channels */
  282. ctx->out_channels = ctx->nchans;
  283. ctx->output_mode = ctx->acmod;
  284. if(ctx->lfeon)
  285. ctx->output_mode |= AC3_OUTPUT_LFEON;
  286. /* skip over portion of header which has already been read */
  287. skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
  288. skip_bits(gb, 16); // skip crc1
  289. skip_bits(gb, 8); // skip fscod and frmsizecod
  290. skip_bits(gb, 11); // skip bsid, bsmod, and acmod
  291. if(ctx->acmod == AC3_ACMOD_STEREO) {
  292. skip_bits(gb, 2); // skip dsurmod
  293. } else {
  294. if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
  295. skip_bits(gb, 2); // skip cmixlev
  296. if(ctx->acmod & 4)
  297. skip_bits(gb, 2); // skip surmixlev
  298. }
  299. skip_bits1(gb); // skip lfeon
  300. /* read the rest of the bsi. read twice for dual mono mode. */
  301. i = !(ctx->acmod);
  302. do {
  303. skip_bits(gb, 5); //skip dialog normalization
  304. if (get_bits1(gb))
  305. skip_bits(gb, 8); //skip compression
  306. if (get_bits1(gb))
  307. skip_bits(gb, 8); //skip language code
  308. if (get_bits1(gb))
  309. skip_bits(gb, 7); //skip audio production information
  310. } while (i--);
  311. skip_bits(gb, 2); //skip copyright bit and original bitstream bit
  312. /* FIXME: read & use the xbsi1 downmix levels */
  313. if (get_bits1(gb))
  314. skip_bits(gb, 14); //skip timecode1
  315. if (get_bits1(gb))
  316. skip_bits(gb, 14); //skip timecode2
  317. if (get_bits1(gb)) {
  318. i = get_bits(gb, 6); //additional bsi length
  319. do {
  320. skip_bits(gb, 8);
  321. } while(i--);
  322. }
  323. return 0;
  324. }
  325. /**
  326. * Decodes the grouped exponents.
  327. * This function decodes the coded exponents according to exponent strategy
  328. * and stores them in the decoded exponents buffer.
  329. *
  330. * @param[in] gb GetBitContext which points to start of coded exponents
  331. * @param[in] expstr Exponent coding strategy
  332. * @param[in] ngrps Number of grouped exponents
  333. * @param[in] absexp Absolute exponent or DC exponent
  334. * @param[out] dexps Decoded exponents are stored in dexps
  335. */
  336. static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
  337. uint8_t absexp, int8_t *dexps)
  338. {
  339. int i, j, grp, grpsize;
  340. int dexp[256];
  341. int expacc, prevexp;
  342. /* unpack groups */
  343. grpsize = expstr + (expstr == EXP_D45);
  344. for(grp=0,i=0; grp<ngrps; grp++) {
  345. expacc = get_bits(gb, 7);
  346. dexp[i++] = exp_ungroup_tbl[expacc][0];
  347. dexp[i++] = exp_ungroup_tbl[expacc][1];
  348. dexp[i++] = exp_ungroup_tbl[expacc][2];
  349. }
  350. /* convert to absolute exps and expand groups */
  351. prevexp = absexp;
  352. for(i=0; i<ngrps*3; i++) {
  353. prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
  354. for(j=0; j<grpsize; j++) {
  355. dexps[(i*grpsize)+j] = prevexp;
  356. }
  357. }
  358. }
  359. /**
  360. * Generates transform coefficients for each coupled channel in the coupling
  361. * range using the coupling coefficients and coupling coordinates.
  362. * reference: Section 7.4.3 Coupling Coordinate Format
  363. */
  364. static void uncouple_channels(AC3DecodeContext *ctx)
  365. {
  366. int i, j, ch, bnd, subbnd;
  367. subbnd = -1;
  368. i = ctx->cplstrtmant;
  369. for(bnd=0; bnd<ctx->ncplbnd; bnd++) {
  370. do {
  371. subbnd++;
  372. for(j=0; j<12; j++) {
  373. for(ch=1; ch<=ctx->nfchans; ch++) {
  374. if(ctx->chincpl[ch-1])
  375. ctx->transform_coeffs[ch][i] = ctx->transform_coeffs_cpl[i] * ctx->cplco[ch-1][bnd];
  376. }
  377. i++;
  378. }
  379. } while((ctx->cplbndstrc >> subbnd) & 1);
  380. }
  381. }
  382. typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
  383. int16_t l3_quantizers[3];
  384. int16_t l5_quantizers[3];
  385. int16_t l11_quantizers[2];
  386. int l3ptr;
  387. int l5ptr;
  388. int l11ptr;
  389. } mant_groups;
  390. /* Get the transform coefficients for particular channel */
  391. static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
  392. {
  393. GetBitContext *gb = &ctx->gb;
  394. int i, gcode, tbap, dithflag, start, end;
  395. uint8_t *exps;
  396. uint8_t *bap;
  397. float *coeffs;
  398. if (ch_index >= 0) { /* fbw channels */
  399. dithflag = ctx->dithflag[ch_index];
  400. exps = ctx->dexps[ch_index];
  401. bap = ctx->bap[ch_index];
  402. coeffs = ctx->transform_coeffs[ch_index + 1];
  403. start = 0;
  404. end = ctx->endmant[ch_index];
  405. } else if (ch_index == -1) {
  406. dithflag = 0;
  407. exps = ctx->dlfeexps;
  408. bap = ctx->lfebap;
  409. coeffs = ctx->transform_coeffs[0];
  410. start = 0;
  411. end = 7;
  412. } else {
  413. dithflag = 0;
  414. exps = ctx->dcplexps;
  415. bap = ctx->cplbap;
  416. coeffs = ctx->transform_coeffs_cpl;
  417. start = ctx->cplstrtmant;
  418. end = ctx->cplendmant;
  419. }
  420. for (i = start; i < end; i++) {
  421. tbap = bap[i];
  422. switch (tbap) {
  423. case 0:
  424. if (!dithflag) {
  425. coeffs[i] = 0;
  426. continue;
  427. }
  428. else {
  429. coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[i]];
  430. coeffs[i] *= LEVEL_MINUS_3DB;
  431. continue;
  432. }
  433. case 1:
  434. if (m->l3ptr > 2) {
  435. gcode = get_bits(gb, 5);
  436. m->l3_quantizers[0] = l3_quantizers_1[gcode];
  437. m->l3_quantizers[1] = l3_quantizers_2[gcode];
  438. m->l3_quantizers[2] = l3_quantizers_3[gcode];
  439. m->l3ptr = 0;
  440. }
  441. coeffs[i] = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[i]];
  442. continue;
  443. case 2:
  444. if (m->l5ptr > 2) {
  445. gcode = get_bits(gb, 7);
  446. m->l5_quantizers[0] = l5_quantizers_1[gcode];
  447. m->l5_quantizers[1] = l5_quantizers_2[gcode];
  448. m->l5_quantizers[2] = l5_quantizers_3[gcode];
  449. m->l5ptr = 0;
  450. }
  451. coeffs[i] = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[i]];
  452. continue;
  453. case 3:
  454. coeffs[i] = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[i]];
  455. continue;
  456. case 4:
  457. if (m->l11ptr > 1) {
  458. gcode = get_bits(gb, 7);
  459. m->l11_quantizers[0] = l11_quantizers_1[gcode];
  460. m->l11_quantizers[1] = l11_quantizers_2[gcode];
  461. m->l11ptr = 0;
  462. }
  463. coeffs[i] = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[i]];
  464. continue;
  465. case 5:
  466. coeffs[i] = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[i]];
  467. continue;
  468. default:
  469. coeffs[i] = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[i]];
  470. continue;
  471. }
  472. }
  473. return 0;
  474. }
  475. /* Get the transform coefficients.
  476. * This function extracts the tranform coefficients form the ac3 bitstream.
  477. * This function is called after bit allocation is performed.
  478. */
  479. static int get_transform_coeffs(AC3DecodeContext * ctx)
  480. {
  481. int i, end;
  482. int got_cplchan = 0;
  483. mant_groups m;
  484. m.l3ptr = m.l5ptr = m.l11ptr = 3;
  485. for (i = 0; i < ctx->nfchans; i++) {
  486. /* transform coefficients for individual channel */
  487. if (get_transform_coeffs_ch(ctx, i, &m))
  488. return -1;
  489. /* tranform coefficients for coupling channels */
  490. if (ctx->chincpl[i]) {
  491. if (!got_cplchan) {
  492. if (get_transform_coeffs_ch(ctx, -2, &m)) {
  493. av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
  494. return -1;
  495. }
  496. uncouple_channels(ctx);
  497. got_cplchan = 1;
  498. }
  499. end = ctx->cplendmant;
  500. } else
  501. end = ctx->endmant[i];
  502. do
  503. ctx->transform_coeffs[i + 1][end] = 0;
  504. while(++end < 256);
  505. }
  506. if (ctx->lfeon) {
  507. if (get_transform_coeffs_ch(ctx, -1, &m))
  508. return -1;
  509. for (i = 7; i < 256; i++) {
  510. ctx->transform_coeffs[0][i] = 0;
  511. }
  512. }
  513. return 0;
  514. }
  515. /**
  516. * Performs stereo rematrixing.
  517. * reference: Section 7.5.4 Rematrixing : Decoding Technique
  518. */
  519. static void do_rematrixing(AC3DecodeContext *ctx)
  520. {
  521. int bnd, i;
  522. int end, bndend;
  523. float tmp0, tmp1;
  524. end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
  525. for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
  526. if(ctx->rematflg[bnd]) {
  527. bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
  528. for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
  529. tmp0 = ctx->transform_coeffs[1][i];
  530. tmp1 = ctx->transform_coeffs[2][i];
  531. ctx->transform_coeffs[1][i] = tmp0 + tmp1;
  532. ctx->transform_coeffs[2][i] = tmp0 - tmp1;
  533. }
  534. }
  535. }
  536. }
  537. /* This function performs the imdct on 256 sample transform
  538. * coefficients.
  539. */
  540. static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
  541. {
  542. int i, k;
  543. DECLARE_ALIGNED_16(float, x[128]);
  544. FFTComplex z[2][64];
  545. float *o_ptr = ctx->tmp_output;
  546. for(i=0; i<2; i++) {
  547. /* de-interleave coefficients */
  548. for(k=0; k<128; k++) {
  549. x[k] = ctx->transform_coeffs[chindex][2*k+i];
  550. }
  551. /* run standard IMDCT */
  552. ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
  553. /* reverse the post-rotation & reordering from standard IMDCT */
  554. for(k=0; k<32; k++) {
  555. z[i][32+k].re = -o_ptr[128+2*k];
  556. z[i][32+k].im = -o_ptr[2*k];
  557. z[i][31-k].re = o_ptr[2*k+1];
  558. z[i][31-k].im = o_ptr[128+2*k+1];
  559. }
  560. }
  561. /* apply AC-3 post-rotation & reordering */
  562. for(k=0; k<64; k++) {
  563. o_ptr[ 2*k ] = -z[0][ k].im;
  564. o_ptr[ 2*k+1] = z[0][63-k].re;
  565. o_ptr[128+2*k ] = -z[0][ k].re;
  566. o_ptr[128+2*k+1] = z[0][63-k].im;
  567. o_ptr[256+2*k ] = -z[1][ k].re;
  568. o_ptr[256+2*k+1] = z[1][63-k].im;
  569. o_ptr[384+2*k ] = z[1][ k].im;
  570. o_ptr[384+2*k+1] = -z[1][63-k].re;
  571. }
  572. }
  573. /* IMDCT Transform. */
  574. static inline void do_imdct(AC3DecodeContext *ctx)
  575. {
  576. int ch;
  577. if (ctx->output_mode & AC3_OUTPUT_LFEON) {
  578. ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
  579. ctx->transform_coeffs[0], ctx->tmp_imdct);
  580. ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
  581. ctx->window, ctx->delay[0], 384, 256, 1);
  582. ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
  583. ctx->window, 256);
  584. }
  585. for (ch=1; ch<=ctx->nfchans; ch++) {
  586. if (ctx->blksw[ch-1])
  587. do_imdct_256(ctx, ch);
  588. else
  589. ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
  590. ctx->transform_coeffs[ch],
  591. ctx->tmp_imdct);
  592. ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
  593. ctx->window, ctx->delay[ch], 384, 256, 1);
  594. ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
  595. ctx->window, 256);
  596. }
  597. }
  598. /* Parse the audio block from ac3 bitstream.
  599. * This function extract the audio block from the ac3 bitstream
  600. * and produces the output for the block. This function must
  601. * be called for each of the six audio block in the ac3 bitstream.
  602. */
  603. static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
  604. {
  605. int nfchans = ctx->nfchans;
  606. int acmod = ctx->acmod;
  607. int i, bnd, seg, grpsize, ch;
  608. GetBitContext *gb = &ctx->gb;
  609. int bit_alloc_flags = 0;
  610. int8_t *dexps;
  611. int mstrcplco, cplcoexp, cplcomant;
  612. int dynrng, chbwcod, ngrps, cplabsexp, skipl;
  613. for (i = 0; i < nfchans; i++) /*block switch flag */
  614. ctx->blksw[i] = get_bits1(gb);
  615. for (i = 0; i < nfchans; i++) /* dithering flag */
  616. ctx->dithflag[i] = get_bits1(gb);
  617. if (get_bits1(gb)) { /* dynamic range */
  618. dynrng = get_sbits(gb, 8);
  619. ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
  620. } else if(blk == 0) {
  621. ctx->dynrng = 1.0;
  622. }
  623. if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
  624. if(get_bits1(gb)) {
  625. dynrng = get_sbits(gb, 8);
  626. ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
  627. } else if(blk == 0) {
  628. ctx->dynrng2 = 1.0;
  629. }
  630. }
  631. if (get_bits1(gb)) { /* coupling strategy */
  632. ctx->cplinu = get_bits1(gb);
  633. ctx->cplbndstrc = 0;
  634. if (ctx->cplinu) { /* coupling in use */
  635. int cplbegf, cplendf;
  636. for (i = 0; i < nfchans; i++)
  637. ctx->chincpl[i] = get_bits1(gb);
  638. if (acmod == AC3_ACMOD_STEREO)
  639. ctx->phsflginu = get_bits1(gb); //phase flag in use
  640. cplbegf = get_bits(gb, 4);
  641. cplendf = get_bits(gb, 4);
  642. if (3 + cplendf - cplbegf < 0) {
  643. av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
  644. return -1;
  645. }
  646. ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
  647. ctx->cplstrtmant = cplbegf * 12 + 37;
  648. ctx->cplendmant = cplendf * 12 + 73;
  649. for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
  650. if (get_bits1(gb)) {
  651. ctx->cplbndstrc |= 1 << i;
  652. ctx->ncplbnd--;
  653. }
  654. } else {
  655. for (i = 0; i < nfchans; i++)
  656. ctx->chincpl[i] = 0;
  657. }
  658. }
  659. if (ctx->cplinu) {
  660. ctx->cplcoe = 0;
  661. for (i = 0; i < nfchans; i++)
  662. if (ctx->chincpl[i])
  663. if (get_bits1(gb)) { /* coupling co-ordinates */
  664. ctx->cplcoe |= 1 << i;
  665. mstrcplco = 3 * get_bits(gb, 2);
  666. for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
  667. cplcoexp = get_bits(gb, 4);
  668. cplcomant = get_bits(gb, 4);
  669. if (cplcoexp == 15)
  670. cplcomant <<= 14;
  671. else
  672. cplcomant = (cplcomant | 0x10) << 13;
  673. ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
  674. }
  675. }
  676. if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
  677. for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
  678. if (get_bits1(gb))
  679. ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
  680. }
  681. if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
  682. ctx->rematstr = get_bits1(gb);
  683. if (ctx->rematstr) {
  684. ctx->nrematbnd = 4;
  685. if(ctx->cplinu && ctx->cplstrtmant <= 61)
  686. ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
  687. for(bnd=0; bnd<ctx->nrematbnd; bnd++)
  688. ctx->rematflg[bnd] = get_bits1(gb);
  689. }
  690. }
  691. ctx->cplexpstr = EXP_REUSE;
  692. ctx->lfeexpstr = EXP_REUSE;
  693. if (ctx->cplinu) /* coupling exponent strategy */
  694. ctx->cplexpstr = get_bits(gb, 2);
  695. for (i = 0; i < nfchans; i++) /* channel exponent strategy */
  696. ctx->chexpstr[i] = get_bits(gb, 2);
  697. if (ctx->lfeon) /* lfe exponent strategy */
  698. ctx->lfeexpstr = get_bits1(gb);
  699. for (i = 0; i < nfchans; i++) /* channel bandwidth code */
  700. if (ctx->chexpstr[i] != EXP_REUSE) {
  701. if (ctx->chincpl[i])
  702. ctx->endmant[i] = ctx->cplstrtmant;
  703. else {
  704. chbwcod = get_bits(gb, 6);
  705. if (chbwcod > 60) {
  706. av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
  707. return -1;
  708. }
  709. ctx->endmant[i] = chbwcod * 3 + 73;
  710. }
  711. }
  712. if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
  713. bit_alloc_flags = 64;
  714. cplabsexp = get_bits(gb, 4) << 1;
  715. ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
  716. decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
  717. }
  718. for (i = 0; i < nfchans; i++) /* fbw channel exponents */
  719. if (ctx->chexpstr[i] != EXP_REUSE) {
  720. bit_alloc_flags |= 1 << i;
  721. grpsize = 3 << (ctx->chexpstr[i] - 1);
  722. ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
  723. dexps = ctx->dexps[i];
  724. dexps[0] = get_bits(gb, 4);
  725. decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
  726. skip_bits(gb, 2); /* skip gainrng */
  727. }
  728. if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
  729. bit_alloc_flags |= 32;
  730. ctx->dlfeexps[0] = get_bits(gb, 4);
  731. decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
  732. }
  733. if (get_bits1(gb)) { /* bit allocation information */
  734. bit_alloc_flags = 127;
  735. ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
  736. ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
  737. ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
  738. ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
  739. ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
  740. }
  741. if (get_bits1(gb)) { /* snroffset */
  742. int csnr;
  743. bit_alloc_flags = 127;
  744. csnr = (get_bits(gb, 6) - 15) << 4;
  745. if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
  746. ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
  747. ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
  748. }
  749. for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
  750. ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
  751. ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
  752. }
  753. if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
  754. ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
  755. ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
  756. }
  757. }
  758. if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
  759. bit_alloc_flags |= 64;
  760. ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
  761. ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
  762. }
  763. if (get_bits1(gb)) { /* delta bit allocation information */
  764. bit_alloc_flags = 127;
  765. if (ctx->cplinu) {
  766. ctx->cpldeltbae = get_bits(gb, 2);
  767. if (ctx->cpldeltbae == DBA_RESERVED) {
  768. av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
  769. return -1;
  770. }
  771. }
  772. for (i = 0; i < nfchans; i++) {
  773. ctx->deltbae[i] = get_bits(gb, 2);
  774. if (ctx->deltbae[i] == DBA_RESERVED) {
  775. av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
  776. return -1;
  777. }
  778. }
  779. if (ctx->cplinu)
  780. if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
  781. ctx->cpldeltnseg = get_bits(gb, 3);
  782. for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
  783. ctx->cpldeltoffst[seg] = get_bits(gb, 5);
  784. ctx->cpldeltlen[seg] = get_bits(gb, 4);
  785. ctx->cpldeltba[seg] = get_bits(gb, 3);
  786. }
  787. }
  788. for (i = 0; i < nfchans; i++)
  789. if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
  790. ctx->deltnseg[i] = get_bits(gb, 3);
  791. for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
  792. ctx->deltoffst[i][seg] = get_bits(gb, 5);
  793. ctx->deltlen[i][seg] = get_bits(gb, 4);
  794. ctx->deltba[i][seg] = get_bits(gb, 3);
  795. }
  796. }
  797. } else if(blk == 0) {
  798. if(ctx->cplinu)
  799. ctx->cpldeltbae = DBA_NONE;
  800. for(i=0; i<nfchans; i++) {
  801. ctx->deltbae[i] = DBA_NONE;
  802. }
  803. }
  804. if (bit_alloc_flags) {
  805. if (ctx->cplinu && (bit_alloc_flags & 64))
  806. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
  807. ctx->dcplexps, ctx->cplstrtmant,
  808. ctx->cplendmant, ctx->cplsnroffst,
  809. ctx->cplfgain, 0,
  810. ctx->cpldeltbae, ctx->cpldeltnseg,
  811. ctx->cpldeltoffst, ctx->cpldeltlen,
  812. ctx->cpldeltba);
  813. for (i = 0; i < nfchans; i++)
  814. if ((bit_alloc_flags >> i) & 1)
  815. ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
  816. ctx->bap[i], ctx->dexps[i], 0,
  817. ctx->endmant[i], ctx->snroffst[i],
  818. ctx->fgain[i], 0, ctx->deltbae[i],
  819. ctx->deltnseg[i], ctx->deltoffst[i],
  820. ctx->deltlen[i], ctx->deltba[i]);
  821. if (ctx->lfeon && (bit_alloc_flags & 32))
  822. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
  823. ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
  824. ctx->lfefgain, 1,
  825. DBA_NONE, 0, NULL, NULL, NULL);
  826. }
  827. if (get_bits1(gb)) { /* unused dummy data */
  828. skipl = get_bits(gb, 9);
  829. while(skipl--)
  830. skip_bits(gb, 8);
  831. }
  832. /* unpack the transform coefficients
  833. * * this also uncouples channels if coupling is in use.
  834. */
  835. if (get_transform_coeffs(ctx)) {
  836. av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
  837. return -1;
  838. }
  839. /* recover coefficients if rematrixing is in use */
  840. if(ctx->acmod == AC3_ACMOD_STEREO)
  841. do_rematrixing(ctx);
  842. /* apply scaling to coefficients (headroom, dynrng) */
  843. if(ctx->lfeon) {
  844. for(i=0; i<7; i++) {
  845. ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
  846. }
  847. }
  848. for(ch=1; ch<=ctx->nfchans; ch++) {
  849. float gain = 2.0f;
  850. if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
  851. gain *= ctx->dynrng2;
  852. } else {
  853. gain *= ctx->dynrng;
  854. }
  855. for(i=0; i<ctx->endmant[ch-1]; i++) {
  856. ctx->transform_coeffs[ch][i] *= gain;
  857. }
  858. }
  859. do_imdct(ctx);
  860. return 0;
  861. }
  862. static inline int16_t convert(int32_t i)
  863. {
  864. if (i > 0x43c07fff)
  865. return 32767;
  866. else if (i <= 0x43bf8000)
  867. return -32768;
  868. else
  869. return (i - 0x43c00000);
  870. }
  871. /* Decode ac3 frame.
  872. *
  873. * @param avctx Pointer to AVCodecContext
  874. * @param data Pointer to pcm smaples
  875. * @param data_size Set to number of pcm samples produced by decoding
  876. * @param buf Data to be decoded
  877. * @param buf_size Size of the buffer
  878. */
  879. static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
  880. {
  881. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  882. int16_t *out_samples = (int16_t *)data;
  883. int i, j, k, start;
  884. int32_t *int_ptr[6];
  885. for (i = 0; i < 6; i++)
  886. int_ptr[i] = (int32_t *)(&ctx->output[i]);
  887. //Initialize the GetBitContext with the start of valid AC3 Frame.
  888. init_get_bits(&ctx->gb, buf, buf_size * 8);
  889. //Parse the syncinfo.
  890. if (ac3_parse_header(ctx)) {
  891. av_log(avctx, AV_LOG_ERROR, "\n");
  892. *data_size = 0;
  893. return buf_size;
  894. }
  895. avctx->sample_rate = ctx->sampling_rate;
  896. avctx->bit_rate = ctx->bit_rate;
  897. /* channel config */
  898. if (avctx->channels == 0) {
  899. avctx->channels = ctx->out_channels;
  900. }
  901. if(avctx->channels != ctx->out_channels) {
  902. av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
  903. avctx->channels);
  904. return -1;
  905. }
  906. //av_log(avctx, AV_LOG_INFO, "channels = %d \t bit rate = %d \t sampling rate = %d \n", avctx->channels, avctx->bit_rate * 1000, avctx->sample_rate);
  907. //Parse the Audio Blocks.
  908. for (i = 0; i < NB_BLOCKS; i++) {
  909. if (ac3_parse_audio_block(ctx, i)) {
  910. av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
  911. *data_size = 0;
  912. return ctx->frame_size;
  913. }
  914. start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
  915. for (k = 0; k < 256; k++)
  916. for (j = start; j <= ctx->nfchans; j++)
  917. *(out_samples++) = convert(int_ptr[j][k]);
  918. }
  919. *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
  920. return ctx->frame_size;
  921. }
  922. /* Uninitialize ac3 decoder.
  923. */
  924. static int ac3_decode_end(AVCodecContext *avctx)
  925. {
  926. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  927. ff_mdct_end(&ctx->imdct_512);
  928. ff_mdct_end(&ctx->imdct_256);
  929. return 0;
  930. }
  931. AVCodec ac3_decoder = {
  932. .name = "ac3",
  933. .type = CODEC_TYPE_AUDIO,
  934. .id = CODEC_ID_AC3,
  935. .priv_data_size = sizeof (AC3DecodeContext),
  936. .init = ac3_decode_init,
  937. .close = ac3_decode_end,
  938. .decode = ac3_decode_frame,
  939. };