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
35KB

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