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.

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