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.

1093 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. }
  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. }
  603. ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
  604. ctx->window, ctx->delay[ch], 384, 256, 1);
  605. ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
  606. ctx->window, 256);
  607. }
  608. }
  609. /* Parse the audio block from ac3 bitstream.
  610. * This function extract the audio block from the ac3 bitstream
  611. * and produces the output for the block. This function must
  612. * be called for each of the six audio block in the ac3 bitstream.
  613. */
  614. static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
  615. {
  616. int nfchans = ctx->nfchans;
  617. int acmod = ctx->acmod;
  618. int i, bnd, seg, grpsize, ch;
  619. GetBitContext *gb = &ctx->gb;
  620. int bit_alloc_flags = 0;
  621. int8_t *dexps;
  622. int mstrcplco, cplcoexp, cplcomant;
  623. int chbwcod, ngrps, cplabsexp, skipl;
  624. for (i = 0; i < nfchans; i++) /*block switch flag */
  625. ctx->blksw[i] = get_bits1(gb);
  626. ctx->dither_all = 1;
  627. for (i = 0; i < nfchans; i++) { /* dithering flag */
  628. ctx->dithflag[i] = get_bits1(gb);
  629. if(!ctx->dithflag[i])
  630. ctx->dither_all = 0;
  631. }
  632. if (get_bits1(gb)) { /* dynamic range */
  633. ctx->dynrng = dynrng_tbl[get_bits(gb, 8)];
  634. } else if(blk == 0) {
  635. ctx->dynrng = 1.0;
  636. }
  637. if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
  638. if(get_bits1(gb)) {
  639. ctx->dynrng2 = dynrng_tbl[get_bits(gb, 8)];
  640. } else if(blk == 0) {
  641. ctx->dynrng2 = 1.0;
  642. }
  643. }
  644. if (get_bits1(gb)) { /* coupling strategy */
  645. ctx->cplinu = get_bits1(gb);
  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[i] = 1;
  664. ctx->ncplbnd--;
  665. }
  666. }
  667. } else {
  668. for (i = 0; i < nfchans; i++)
  669. ctx->chincpl[i] = 0;
  670. }
  671. }
  672. if (ctx->cplinu) {
  673. int cplcoe = 0;
  674. for (i = 0; i < nfchans; i++) {
  675. if (ctx->chincpl[i]) {
  676. if (get_bits1(gb)) { /* coupling co-ordinates */
  677. cplcoe = 1;
  678. mstrcplco = 3 * get_bits(gb, 2);
  679. for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
  680. cplcoexp = get_bits(gb, 4);
  681. cplcomant = get_bits(gb, 4);
  682. if (cplcoexp == 15)
  683. ctx->cplco[i][bnd] = cplcomant / 16.0f;
  684. else
  685. ctx->cplco[i][bnd] = (cplcomant + 16.0f) / 32.0f;
  686. ctx->cplco[i][bnd] *= scale_factors[cplcoexp + mstrcplco];
  687. }
  688. }
  689. }
  690. }
  691. if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && cplcoe) {
  692. for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
  693. if (get_bits1(gb))
  694. ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
  695. }
  696. }
  697. }
  698. if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
  699. ctx->rematstr = get_bits1(gb);
  700. if (ctx->rematstr) {
  701. ctx->nrematbnd = 4;
  702. if(ctx->cplinu && ctx->cplstrtmant <= 61)
  703. ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
  704. for(bnd=0; bnd<ctx->nrematbnd; bnd++)
  705. ctx->rematflg[bnd] = get_bits1(gb);
  706. }
  707. }
  708. ctx->cplexpstr = EXP_REUSE;
  709. ctx->lfeexpstr = EXP_REUSE;
  710. if (ctx->cplinu) /* coupling exponent strategy */
  711. ctx->cplexpstr = get_bits(gb, 2);
  712. for (i = 0; i < nfchans; i++) /* channel exponent strategy */
  713. ctx->chexpstr[i] = get_bits(gb, 2);
  714. if (ctx->lfeon) /* lfe exponent strategy */
  715. ctx->lfeexpstr = get_bits1(gb);
  716. for (i = 0; i < nfchans; i++) { /* channel bandwidth code */
  717. if (ctx->chexpstr[i] != EXP_REUSE) {
  718. if (ctx->chincpl[i])
  719. ctx->endmant[i] = ctx->cplstrtmant;
  720. else {
  721. chbwcod = get_bits(gb, 6);
  722. if (chbwcod > 60) {
  723. av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
  724. return -1;
  725. }
  726. ctx->endmant[i] = chbwcod * 3 + 73;
  727. }
  728. }
  729. }
  730. if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
  731. bit_alloc_flags = 64;
  732. cplabsexp = get_bits(gb, 4) << 1;
  733. ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
  734. decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
  735. }
  736. for (i = 0; i < nfchans; i++) { /* fbw channel exponents */
  737. if (ctx->chexpstr[i] != EXP_REUSE) {
  738. bit_alloc_flags |= 1 << i;
  739. grpsize = 3 << (ctx->chexpstr[i] - 1);
  740. ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
  741. dexps = ctx->dexps[i];
  742. dexps[0] = get_bits(gb, 4);
  743. decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
  744. skip_bits(gb, 2); /* skip gainrng */
  745. }
  746. }
  747. if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
  748. bit_alloc_flags |= 32;
  749. ctx->dlfeexps[0] = get_bits(gb, 4);
  750. decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
  751. }
  752. if (get_bits1(gb)) { /* bit allocation information */
  753. bit_alloc_flags = 127;
  754. ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
  755. ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
  756. ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
  757. ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
  758. ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
  759. }
  760. if (get_bits1(gb)) { /* snroffset */
  761. int csnr;
  762. bit_alloc_flags = 127;
  763. csnr = (get_bits(gb, 6) - 15) << 4;
  764. if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
  765. ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
  766. ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
  767. }
  768. for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
  769. ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
  770. ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
  771. }
  772. if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
  773. ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
  774. ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
  775. }
  776. }
  777. if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
  778. bit_alloc_flags |= 64;
  779. ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
  780. ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
  781. }
  782. if (get_bits1(gb)) { /* delta bit allocation information */
  783. bit_alloc_flags = 127;
  784. if (ctx->cplinu) {
  785. ctx->cpldeltbae = get_bits(gb, 2);
  786. if (ctx->cpldeltbae == DBA_RESERVED) {
  787. av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
  788. return -1;
  789. }
  790. }
  791. for (i = 0; i < nfchans; i++) {
  792. ctx->deltbae[i] = get_bits(gb, 2);
  793. if (ctx->deltbae[i] == DBA_RESERVED) {
  794. av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
  795. return -1;
  796. }
  797. }
  798. if (ctx->cplinu) {
  799. if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
  800. ctx->cpldeltnseg = get_bits(gb, 3);
  801. for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
  802. ctx->cpldeltoffst[seg] = get_bits(gb, 5);
  803. ctx->cpldeltlen[seg] = get_bits(gb, 4);
  804. ctx->cpldeltba[seg] = get_bits(gb, 3);
  805. }
  806. }
  807. }
  808. for (i = 0; i < nfchans; i++) {
  809. if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
  810. ctx->deltnseg[i] = get_bits(gb, 3);
  811. for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
  812. ctx->deltoffst[i][seg] = get_bits(gb, 5);
  813. ctx->deltlen[i][seg] = get_bits(gb, 4);
  814. ctx->deltba[i][seg] = get_bits(gb, 3);
  815. }
  816. }
  817. }
  818. } else if(blk == 0) {
  819. if(ctx->cplinu)
  820. ctx->cpldeltbae = DBA_NONE;
  821. for(i=0; i<nfchans; i++) {
  822. ctx->deltbae[i] = DBA_NONE;
  823. }
  824. }
  825. if (bit_alloc_flags) {
  826. if (ctx->cplinu && (bit_alloc_flags & 64)) {
  827. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
  828. ctx->dcplexps, ctx->cplstrtmant,
  829. ctx->cplendmant, ctx->cplsnroffst,
  830. ctx->cplfgain, 0,
  831. ctx->cpldeltbae, ctx->cpldeltnseg,
  832. ctx->cpldeltoffst, ctx->cpldeltlen,
  833. ctx->cpldeltba);
  834. }
  835. for (i = 0; i < nfchans; i++) {
  836. if ((bit_alloc_flags >> i) & 1) {
  837. ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
  838. ctx->bap[i], ctx->dexps[i], 0,
  839. ctx->endmant[i], ctx->snroffst[i],
  840. ctx->fgain[i], 0, ctx->deltbae[i],
  841. ctx->deltnseg[i], ctx->deltoffst[i],
  842. ctx->deltlen[i], ctx->deltba[i]);
  843. }
  844. }
  845. if (ctx->lfeon && (bit_alloc_flags & 32)) {
  846. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
  847. ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
  848. ctx->lfefgain, 1,
  849. DBA_NONE, 0, NULL, NULL, NULL);
  850. }
  851. }
  852. if (get_bits1(gb)) { /* unused dummy data */
  853. skipl = get_bits(gb, 9);
  854. while(skipl--)
  855. skip_bits(gb, 8);
  856. }
  857. /* unpack the transform coefficients
  858. * * this also uncouples channels if coupling is in use.
  859. */
  860. if (get_transform_coeffs(ctx)) {
  861. av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
  862. return -1;
  863. }
  864. /* recover coefficients if rematrixing is in use */
  865. if(ctx->acmod == AC3_ACMOD_STEREO)
  866. do_rematrixing(ctx);
  867. /* apply scaling to coefficients (headroom, dynrng) */
  868. if(ctx->lfeon) {
  869. for(i=0; i<7; i++) {
  870. ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
  871. }
  872. }
  873. for(ch=1; ch<=ctx->nfchans; ch++) {
  874. float gain = 2.0f;
  875. if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
  876. gain *= ctx->dynrng2;
  877. } else {
  878. gain *= ctx->dynrng;
  879. }
  880. for(i=0; i<ctx->endmant[ch-1]; i++) {
  881. ctx->transform_coeffs[ch][i] *= gain;
  882. }
  883. }
  884. do_imdct(ctx);
  885. return 0;
  886. }
  887. static inline int16_t convert(int32_t i)
  888. {
  889. if (i > 0x43c07fff)
  890. return 32767;
  891. else if (i <= 0x43bf8000)
  892. return -32768;
  893. else
  894. return (i - 0x43c00000);
  895. }
  896. /* Decode ac3 frame.
  897. *
  898. * @param avctx Pointer to AVCodecContext
  899. * @param data Pointer to pcm smaples
  900. * @param data_size Set to number of pcm samples produced by decoding
  901. * @param buf Data to be decoded
  902. * @param buf_size Size of the buffer
  903. */
  904. static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
  905. {
  906. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  907. int16_t *out_samples = (int16_t *)data;
  908. int i, j, k, start;
  909. int32_t *int_ptr[6];
  910. for (i = 0; i < 6; i++)
  911. int_ptr[i] = (int32_t *)(&ctx->output[i]);
  912. //Initialize the GetBitContext with the start of valid AC3 Frame.
  913. init_get_bits(&ctx->gb, buf, buf_size * 8);
  914. //Parse the syncinfo.
  915. if (ac3_parse_header(ctx)) {
  916. av_log(avctx, AV_LOG_ERROR, "\n");
  917. *data_size = 0;
  918. return buf_size;
  919. }
  920. avctx->sample_rate = ctx->sampling_rate;
  921. avctx->bit_rate = ctx->bit_rate;
  922. /* channel config */
  923. if (avctx->channels == 0) {
  924. avctx->channels = ctx->out_channels;
  925. }
  926. if(avctx->channels != ctx->out_channels) {
  927. av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
  928. avctx->channels);
  929. return -1;
  930. }
  931. //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);
  932. //Parse the Audio Blocks.
  933. for (i = 0; i < NB_BLOCKS; i++) {
  934. if (ac3_parse_audio_block(ctx, i)) {
  935. av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
  936. *data_size = 0;
  937. return ctx->frame_size;
  938. }
  939. start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
  940. for (k = 0; k < 256; k++)
  941. for (j = start; j <= ctx->nfchans; j++)
  942. *(out_samples++) = convert(int_ptr[j][k]);
  943. }
  944. *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
  945. return ctx->frame_size;
  946. }
  947. /* Uninitialize ac3 decoder.
  948. */
  949. static int ac3_decode_end(AVCodecContext *avctx)
  950. {
  951. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  952. ff_mdct_end(&ctx->imdct_512);
  953. ff_mdct_end(&ctx->imdct_256);
  954. return 0;
  955. }
  956. AVCodec ac3_decoder = {
  957. .name = "ac3",
  958. .type = CODEC_TYPE_AUDIO,
  959. .id = CODEC_ID_AC3,
  960. .priv_data_size = sizeof (AC3DecodeContext),
  961. .init = ac3_decode_init,
  962. .close = ac3_decode_end,
  963. .decode = ac3_decode_frame,
  964. };