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.

1031 lines
34KB

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