ac3dec.c

Go to the documentation of this file.
00001 /*
00002  * AC-3 Audio Decoder
00003  * This code is developed as part of Google Summer of Code 2006 Program.
00004  *
00005  * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
00006  * Copyright (c) 2007 Justin Ruggles
00007  *
00008  * Portions of this code are derived from liba52
00009  * http://liba52.sourceforge.net
00010  * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
00011  * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
00012  *
00013  * This file is part of FFmpeg.
00014  *
00015  * FFmpeg is free software; you can redistribute it and/or
00016  * modify it under the terms of the GNU General Public
00017  * License as published by the Free Software Foundation; either
00018  * version 2 of the License, or (at your option) any later version.
00019  *
00020  * FFmpeg is distributed in the hope that it will be useful,
00021  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00022  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00023  * General Public License for more details.
00024  *
00025  * You should have received a copy of the GNU General Public
00026  * License along with FFmpeg; if not, write to the Free Software
00027  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00028  */
00029 
00030 #include <stdio.h>
00031 #include <stddef.h>
00032 #include <math.h>
00033 #include <string.h>
00034 
00035 #include "libavutil/crc.h"
00036 #include "libavutil/random.h"
00037 #include "avcodec.h"
00038 #include "ac3_parser.h"
00039 #include "bitstream.h"
00040 #include "dsputil.h"
00041 #include "ac3dec.h"
00042 #include "ac3dec_data.h"
00043 
00044 /** Maximum possible frame size when the specification limit is ignored */
00045 #define AC3_MAX_FRAME_SIZE 21695
00046 
00047 /** table for grouping exponents */
00048 static uint8_t exp_ungroup_tab[128][3];
00049 
00050 
00051 /** tables for ungrouping mantissas */
00052 static int b1_mantissas[32][3];
00053 static int b2_mantissas[128][3];
00054 static int b3_mantissas[8];
00055 static int b4_mantissas[128][2];
00056 static int b5_mantissas[16];
00057 
00058 /**
00059  * Quantization table: levels for symmetric. bits for asymmetric.
00060  * reference: Table 7.18 Mapping of bap to Quantizer
00061  */
00062 static const uint8_t quantization_tab[16] = {
00063     0, 3, 5, 7, 11, 15,
00064     5, 6, 7, 8, 9, 10, 11, 12, 14, 16
00065 };
00066 
00067 /** dynamic range table. converts codes to scale factors. */
00068 static float dynamic_range_tab[256];
00069 
00070 /** Adjustments in dB gain */
00071 #define LEVEL_PLUS_3DB          1.4142135623730950
00072 #define LEVEL_PLUS_1POINT5DB    1.1892071150027209
00073 #define LEVEL_MINUS_1POINT5DB   0.8408964152537145
00074 #define LEVEL_MINUS_3DB         0.7071067811865476
00075 #define LEVEL_MINUS_4POINT5DB   0.5946035575013605
00076 #define LEVEL_MINUS_6DB         0.5000000000000000
00077 #define LEVEL_MINUS_9DB         0.3535533905932738
00078 #define LEVEL_ZERO              0.0000000000000000
00079 #define LEVEL_ONE               1.0000000000000000
00080 
00081 static const float gain_levels[9] = {
00082     LEVEL_PLUS_3DB,
00083     LEVEL_PLUS_1POINT5DB,
00084     LEVEL_ONE,
00085     LEVEL_MINUS_1POINT5DB,
00086     LEVEL_MINUS_3DB,
00087     LEVEL_MINUS_4POINT5DB,
00088     LEVEL_MINUS_6DB,
00089     LEVEL_ZERO,
00090     LEVEL_MINUS_9DB
00091 };
00092 
00093 /**
00094  * Table for center mix levels
00095  * reference: Section 5.4.2.4 cmixlev
00096  */
00097 static const uint8_t center_levels[4] = { 4, 5, 6, 5 };
00098 
00099 /**
00100  * Table for surround mix levels
00101  * reference: Section 5.4.2.5 surmixlev
00102  */
00103 static const uint8_t surround_levels[4] = { 4, 6, 7, 6 };
00104 
00105 /**
00106  * Table for default stereo downmixing coefficients
00107  * reference: Section 7.8.2 Downmixing Into Two Channels
00108  */
00109 static const uint8_t ac3_default_coeffs[8][5][2] = {
00110     { { 2, 7 }, { 7, 2 },                               },
00111     { { 4, 4 },                                         },
00112     { { 2, 7 }, { 7, 2 },                               },
00113     { { 2, 7 }, { 5, 5 }, { 7, 2 },                     },
00114     { { 2, 7 }, { 7, 2 }, { 6, 6 },                     },
00115     { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 8, 8 },           },
00116     { { 2, 7 }, { 7, 2 }, { 6, 7 }, { 7, 6 },           },
00117     { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 6, 7 }, { 7, 6 }, },
00118 };
00119 
00120 /**
00121  * Symmetrical Dequantization
00122  * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
00123  *            Tables 7.19 to 7.23
00124  */
00125 static inline int
00126 symmetric_dequant(int code, int levels)
00127 {
00128     return ((code - (levels >> 1)) << 24) / levels;
00129 }
00130 
00131 /*
00132  * Initialize tables at runtime.
00133  */
00134 static av_cold void ac3_tables_init(void)
00135 {
00136     int i;
00137 
00138     /* generate grouped mantissa tables
00139        reference: Section 7.3.5 Ungrouping of Mantissas */
00140     for(i=0; i<32; i++) {
00141         /* bap=1 mantissas */
00142         b1_mantissas[i][0] = symmetric_dequant( i / 9     , 3);
00143         b1_mantissas[i][1] = symmetric_dequant((i % 9) / 3, 3);
00144         b1_mantissas[i][2] = symmetric_dequant((i % 9) % 3, 3);
00145     }
00146     for(i=0; i<128; i++) {
00147         /* bap=2 mantissas */
00148         b2_mantissas[i][0] = symmetric_dequant( i / 25     , 5);
00149         b2_mantissas[i][1] = symmetric_dequant((i % 25) / 5, 5);
00150         b2_mantissas[i][2] = symmetric_dequant((i % 25) % 5, 5);
00151 
00152         /* bap=4 mantissas */
00153         b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
00154         b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
00155     }
00156     /* generate ungrouped mantissa tables
00157        reference: Tables 7.21 and 7.23 */
00158     for(i=0; i<7; i++) {
00159         /* bap=3 mantissas */
00160         b3_mantissas[i] = symmetric_dequant(i, 7);
00161     }
00162     for(i=0; i<15; i++) {
00163         /* bap=5 mantissas */
00164         b5_mantissas[i] = symmetric_dequant(i, 15);
00165     }
00166 
00167     /* generate dynamic range table
00168        reference: Section 7.7.1 Dynamic Range Control */
00169     for(i=0; i<256; i++) {
00170         int v = (i >> 5) - ((i >> 7) << 3) - 5;
00171         dynamic_range_tab[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
00172     }
00173 
00174     /* generate exponent tables
00175        reference: Section 7.1.3 Exponent Decoding */
00176     for(i=0; i<128; i++) {
00177         exp_ungroup_tab[i][0] =  i / 25;
00178         exp_ungroup_tab[i][1] = (i % 25) / 5;
00179         exp_ungroup_tab[i][2] = (i % 25) % 5;
00180     }
00181 }
00182 
00183 
00184 /**
00185  * AVCodec initialization
00186  */
00187 static av_cold int ac3_decode_init(AVCodecContext *avctx)
00188 {
00189     AC3DecodeContext *s = avctx->priv_data;
00190     s->avctx = avctx;
00191 
00192     ac3_common_init();
00193     ac3_tables_init();
00194     ff_mdct_init(&s->imdct_256, 8, 1);
00195     ff_mdct_init(&s->imdct_512, 9, 1);
00196     ff_kbd_window_init(s->window, 5.0, 256);
00197     dsputil_init(&s->dsp, avctx);
00198     av_init_random(0, &s->dith_state);
00199 
00200     /* set bias values for float to int16 conversion */
00201     if(s->dsp.float_to_int16 == ff_float_to_int16_c) {
00202         s->add_bias = 385.0f;
00203         s->mul_bias = 1.0f;
00204     } else {
00205         s->add_bias = 0.0f;
00206         s->mul_bias = 32767.0f;
00207     }
00208 
00209     /* allow downmixing to stereo or mono */
00210     if (avctx->channels > 0 && avctx->request_channels > 0 &&
00211             avctx->request_channels < avctx->channels &&
00212             avctx->request_channels <= 2) {
00213         avctx->channels = avctx->request_channels;
00214     }
00215     s->downmixed = 1;
00216 
00217     /* allocate context input buffer */
00218     if (avctx->error_resilience >= FF_ER_CAREFUL) {
00219         s->input_buffer = av_mallocz(AC3_MAX_FRAME_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
00220         if (!s->input_buffer)
00221             return AVERROR_NOMEM;
00222     }
00223 
00224     return 0;
00225 }
00226 
00227 /**
00228  * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
00229  * GetBitContext within AC3DecodeContext must point to
00230  * start of the synchronized ac3 bitstream.
00231  */
00232 static int ac3_parse_header(AC3DecodeContext *s)
00233 {
00234     GetBitContext *gbc = &s->gbc;
00235     int i;
00236 
00237     /* read the rest of the bsi. read twice for dual mono mode. */
00238     i = !(s->channel_mode);
00239     do {
00240         skip_bits(gbc, 5); // skip dialog normalization
00241         if (get_bits1(gbc))
00242             skip_bits(gbc, 8); //skip compression
00243         if (get_bits1(gbc))
00244             skip_bits(gbc, 8); //skip language code
00245         if (get_bits1(gbc))
00246             skip_bits(gbc, 7); //skip audio production information
00247     } while (i--);
00248 
00249     skip_bits(gbc, 2); //skip copyright bit and original bitstream bit
00250 
00251     /* skip the timecodes (or extra bitstream information for Alternate Syntax)
00252        TODO: read & use the xbsi1 downmix levels */
00253     if (get_bits1(gbc))
00254         skip_bits(gbc, 14); //skip timecode1 / xbsi1
00255     if (get_bits1(gbc))
00256         skip_bits(gbc, 14); //skip timecode2 / xbsi2
00257 
00258     /* skip additional bitstream info */
00259     if (get_bits1(gbc)) {
00260         i = get_bits(gbc, 6);
00261         do {
00262             skip_bits(gbc, 8);
00263         } while(i--);
00264     }
00265 
00266     return 0;
00267 }
00268 
00269 /**
00270  * Common function to parse AC3 or E-AC3 frame header
00271  */
00272 static int parse_frame_header(AC3DecodeContext *s)
00273 {
00274     AC3HeaderInfo hdr;
00275     GetBitContext *gbc = &s->gbc;
00276     int err;
00277 
00278     err = ff_ac3_parse_header(gbc, &hdr);
00279     if(err)
00280         return err;
00281 
00282     if(hdr.bitstream_id > 10)
00283         return AC3_PARSE_ERROR_BSID;
00284 
00285     /* get decoding parameters from header info */
00286     s->bit_alloc_params.sr_code     = hdr.sr_code;
00287     s->channel_mode                 = hdr.channel_mode;
00288     s->lfe_on                       = hdr.lfe_on;
00289     s->bit_alloc_params.sr_shift    = hdr.sr_shift;
00290     s->sample_rate                  = hdr.sample_rate;
00291     s->bit_rate                     = hdr.bit_rate;
00292     s->channels                     = hdr.channels;
00293     s->fbw_channels                 = s->channels - s->lfe_on;
00294     s->lfe_ch                       = s->fbw_channels + 1;
00295     s->frame_size                   = hdr.frame_size;
00296     s->center_mix_level             = hdr.center_mix_level;
00297     s->surround_mix_level           = hdr.surround_mix_level;
00298     s->num_blocks                   = hdr.num_blocks;
00299     s->frame_type                   = hdr.frame_type;
00300     s->substreamid                  = hdr.substreamid;
00301 
00302     if(s->lfe_on) {
00303         s->start_freq[s->lfe_ch] = 0;
00304         s->end_freq[s->lfe_ch] = 7;
00305         s->num_exp_groups[s->lfe_ch] = 2;
00306         s->channel_in_cpl[s->lfe_ch] = 0;
00307     }
00308 
00309     return ac3_parse_header(s);
00310 }
00311 
00312 /**
00313  * Set stereo downmixing coefficients based on frame header info.
00314  * reference: Section 7.8.2 Downmixing Into Two Channels
00315  */
00316 static void set_downmix_coeffs(AC3DecodeContext *s)
00317 {
00318     int i;
00319     float cmix = gain_levels[center_levels[s->center_mix_level]];
00320     float smix = gain_levels[surround_levels[s->surround_mix_level]];
00321 
00322     for(i=0; i<s->fbw_channels; i++) {
00323         s->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[s->channel_mode][i][0]];
00324         s->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[s->channel_mode][i][1]];
00325     }
00326     if(s->channel_mode > 1 && s->channel_mode & 1) {
00327         s->downmix_coeffs[1][0] = s->downmix_coeffs[1][1] = cmix;
00328     }
00329     if(s->channel_mode == AC3_CHMODE_2F1R || s->channel_mode == AC3_CHMODE_3F1R) {
00330         int nf = s->channel_mode - 2;
00331         s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf][1] = smix * LEVEL_MINUS_3DB;
00332     }
00333     if(s->channel_mode == AC3_CHMODE_2F2R || s->channel_mode == AC3_CHMODE_3F2R) {
00334         int nf = s->channel_mode - 4;
00335         s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf+1][1] = smix;
00336     }
00337 
00338     /* calculate adjustment needed for each channel to avoid clipping */
00339     s->downmix_coeff_adjust[0] = s->downmix_coeff_adjust[1] = 0.0f;
00340     for(i=0; i<s->fbw_channels; i++) {
00341         s->downmix_coeff_adjust[0] += s->downmix_coeffs[i][0];
00342         s->downmix_coeff_adjust[1] += s->downmix_coeffs[i][1];
00343     }
00344     s->downmix_coeff_adjust[0] = 1.0f / s->downmix_coeff_adjust[0];
00345     s->downmix_coeff_adjust[1] = 1.0f / s->downmix_coeff_adjust[1];
00346 }
00347 
00348 /**
00349  * Decode the grouped exponents according to exponent strategy.
00350  * reference: Section 7.1.3 Exponent Decoding
00351  */
00352 static void decode_exponents(GetBitContext *gbc, int exp_strategy, int ngrps,
00353                              uint8_t absexp, int8_t *dexps)
00354 {
00355     int i, j, grp, group_size;
00356     int dexp[256];
00357     int expacc, prevexp;
00358 
00359     /* unpack groups */
00360     group_size = exp_strategy + (exp_strategy == EXP_D45);
00361     for(grp=0,i=0; grp<ngrps; grp++) {
00362         expacc = get_bits(gbc, 7);
00363         dexp[i++] = exp_ungroup_tab[expacc][0];
00364         dexp[i++] = exp_ungroup_tab[expacc][1];
00365         dexp[i++] = exp_ungroup_tab[expacc][2];
00366     }
00367 
00368     /* convert to absolute exps and expand groups */
00369     prevexp = absexp;
00370     for(i=0; i<ngrps*3; i++) {
00371         prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
00372         for(j=0; j<group_size; j++) {
00373             dexps[(i*group_size)+j] = prevexp;
00374         }
00375     }
00376 }
00377 
00378 /**
00379  * Generate transform coefficients for each coupled channel in the coupling
00380  * range using the coupling coefficients and coupling coordinates.
00381  * reference: Section 7.4.3 Coupling Coordinate Format
00382  */
00383 static void uncouple_channels(AC3DecodeContext *s)
00384 {
00385     int i, j, ch, bnd, subbnd;
00386 
00387     subbnd = -1;
00388     i = s->start_freq[CPL_CH];
00389     for(bnd=0; bnd<s->num_cpl_bands; bnd++) {
00390         do {
00391             subbnd++;
00392             for(j=0; j<12; j++) {
00393                 for(ch=1; ch<=s->fbw_channels; ch++) {
00394                     if(s->channel_in_cpl[ch]) {
00395                         s->fixed_coeffs[ch][i] = ((int64_t)s->fixed_coeffs[CPL_CH][i] * (int64_t)s->cpl_coords[ch][bnd]) >> 23;
00396                         if (ch == 2 && s->phase_flags[bnd])
00397                             s->fixed_coeffs[ch][i] = -s->fixed_coeffs[ch][i];
00398                     }
00399                 }
00400                 i++;
00401             }
00402         } while(s->cpl_band_struct[subbnd]);
00403     }
00404 }
00405 
00406 /**
00407  * Grouped mantissas for 3-level 5-level and 11-level quantization
00408  */
00409 typedef struct {
00410     int b1_mant[3];
00411     int b2_mant[3];
00412     int b4_mant[2];
00413     int b1ptr;
00414     int b2ptr;
00415     int b4ptr;
00416 } mant_groups;
00417 
00418 /**
00419  * Get the transform coefficients for a particular channel
00420  * reference: Section 7.3 Quantization and Decoding of Mantissas
00421  */
00422 static void get_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)
00423 {
00424     GetBitContext *gbc = &s->gbc;
00425     int i, gcode, tbap, start, end;
00426     uint8_t *exps;
00427     uint8_t *bap;
00428     int *coeffs;
00429 
00430     exps = s->dexps[ch_index];
00431     bap = s->bap[ch_index];
00432     coeffs = s->fixed_coeffs[ch_index];
00433     start = s->start_freq[ch_index];
00434     end = s->end_freq[ch_index];
00435 
00436     for (i = start; i < end; i++) {
00437         tbap = bap[i];
00438         switch (tbap) {
00439             case 0:
00440                 coeffs[i] = (av_random(&s->dith_state) & 0x7FFFFF) - 0x400000;
00441                 break;
00442 
00443             case 1:
00444                 if(m->b1ptr > 2) {
00445                     gcode = get_bits(gbc, 5);
00446                     m->b1_mant[0] = b1_mantissas[gcode][0];
00447                     m->b1_mant[1] = b1_mantissas[gcode][1];
00448                     m->b1_mant[2] = b1_mantissas[gcode][2];
00449                     m->b1ptr = 0;
00450                 }
00451                 coeffs[i] = m->b1_mant[m->b1ptr++];
00452                 break;
00453 
00454             case 2:
00455                 if(m->b2ptr > 2) {
00456                     gcode = get_bits(gbc, 7);
00457                     m->b2_mant[0] = b2_mantissas[gcode][0];
00458                     m->b2_mant[1] = b2_mantissas[gcode][1];
00459                     m->b2_mant[2] = b2_mantissas[gcode][2];
00460                     m->b2ptr = 0;
00461                 }
00462                 coeffs[i] = m->b2_mant[m->b2ptr++];
00463                 break;
00464 
00465             case 3:
00466                 coeffs[i] = b3_mantissas[get_bits(gbc, 3)];
00467                 break;
00468 
00469             case 4:
00470                 if(m->b4ptr > 1) {
00471                     gcode = get_bits(gbc, 7);
00472                     m->b4_mant[0] = b4_mantissas[gcode][0];
00473                     m->b4_mant[1] = b4_mantissas[gcode][1];
00474                     m->b4ptr = 0;
00475                 }
00476                 coeffs[i] = m->b4_mant[m->b4ptr++];
00477                 break;
00478 
00479             case 5:
00480                 coeffs[i] = b5_mantissas[get_bits(gbc, 4)];
00481                 break;
00482 
00483             default: {
00484                 /* asymmetric dequantization */
00485                 int qlevel = quantization_tab[tbap];
00486                 coeffs[i] = get_sbits(gbc, qlevel) << (24 - qlevel);
00487                 break;
00488             }
00489         }
00490         coeffs[i] >>= exps[i];
00491     }
00492 }
00493 
00494 /**
00495  * Remove random dithering from coefficients with zero-bit mantissas
00496  * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
00497  */
00498 static void remove_dithering(AC3DecodeContext *s) {
00499     int ch, i;
00500     int end=0;
00501     int *coeffs;
00502     uint8_t *bap;
00503 
00504     for(ch=1; ch<=s->fbw_channels; ch++) {
00505         if(!s->dither_flag[ch]) {
00506             coeffs = s->fixed_coeffs[ch];
00507             bap = s->bap[ch];
00508             if(s->channel_in_cpl[ch])
00509                 end = s->start_freq[CPL_CH];
00510             else
00511                 end = s->end_freq[ch];
00512             for(i=0; i<end; i++) {
00513                 if(!bap[i])
00514                     coeffs[i] = 0;
00515             }
00516             if(s->channel_in_cpl[ch]) {
00517                 bap = s->bap[CPL_CH];
00518                 for(; i<s->end_freq[CPL_CH]; i++) {
00519                     if(!bap[i])
00520                         coeffs[i] = 0;
00521                 }
00522             }
00523         }
00524     }
00525 }
00526 
00527 /**
00528  * Get the transform coefficients.
00529  */
00530 static void get_transform_coeffs(AC3DecodeContext *s)
00531 {
00532     int ch, end;
00533     int got_cplchan = 0;
00534     mant_groups m;
00535 
00536     m.b1ptr = m.b2ptr = m.b4ptr = 3;
00537 
00538     for (ch = 1; ch <= s->channels; ch++) {
00539         /* transform coefficients for full-bandwidth channel */
00540         get_transform_coeffs_ch(s, ch, &m);
00541         /* tranform coefficients for coupling channel come right after the
00542            coefficients for the first coupled channel*/
00543         if (s->channel_in_cpl[ch])  {
00544             if (!got_cplchan) {
00545                 get_transform_coeffs_ch(s, CPL_CH, &m);
00546                 uncouple_channels(s);
00547                 got_cplchan = 1;
00548             }
00549             end = s->end_freq[CPL_CH];
00550         } else {
00551             end = s->end_freq[ch];
00552         }
00553         do
00554             s->fixed_coeffs[ch][end] = 0;
00555         while(++end < 256);
00556     }
00557 
00558     /* if any channel doesn't use dithering, zero appropriate coefficients */
00559     if(!s->dither_all)
00560         remove_dithering(s);
00561 }
00562 
00563 /**
00564  * Stereo rematrixing.
00565  * reference: Section 7.5.4 Rematrixing : Decoding Technique
00566  */
00567 static void do_rematrixing(AC3DecodeContext *s)
00568 {
00569     int bnd, i;
00570     int end, bndend;
00571     int tmp0, tmp1;
00572 
00573     end = FFMIN(s->end_freq[1], s->end_freq[2]);
00574 
00575     for(bnd=0; bnd<s->num_rematrixing_bands; bnd++) {
00576         if(s->rematrixing_flags[bnd]) {
00577             bndend = FFMIN(end, ff_ac3_rematrix_band_tab[bnd+1]);
00578             for(i=ff_ac3_rematrix_band_tab[bnd]; i<bndend; i++) {
00579                 tmp0 = s->fixed_coeffs[1][i];
00580                 tmp1 = s->fixed_coeffs[2][i];
00581                 s->fixed_coeffs[1][i] = tmp0 + tmp1;
00582                 s->fixed_coeffs[2][i] = tmp0 - tmp1;
00583             }
00584         }
00585     }
00586 }
00587 
00588 /**
00589  * Perform the 256-point IMDCT
00590  */
00591 static void do_imdct_256(AC3DecodeContext *s, int chindex)
00592 {
00593     int i, k;
00594     DECLARE_ALIGNED_16(float, x[128]);
00595     FFTComplex z[2][64];
00596     float *o_ptr = s->tmp_output;
00597 
00598     for(i=0; i<2; i++) {
00599         /* de-interleave coefficients */
00600         for(k=0; k<128; k++) {
00601             x[k] = s->transform_coeffs[chindex][2*k+i];
00602         }
00603 
00604         /* run standard IMDCT */
00605         s->imdct_256.fft.imdct_calc(&s->imdct_256, o_ptr, x, s->tmp_imdct);
00606 
00607         /* reverse the post-rotation & reordering from standard IMDCT */
00608         for(k=0; k<32; k++) {
00609             z[i][32+k].re = -o_ptr[128+2*k];
00610             z[i][32+k].im = -o_ptr[2*k];
00611             z[i][31-k].re =  o_ptr[2*k+1];
00612             z[i][31-k].im =  o_ptr[128+2*k+1];
00613         }
00614     }
00615 
00616     /* apply AC-3 post-rotation & reordering */
00617     for(k=0; k<64; k++) {
00618         o_ptr[    2*k  ] = -z[0][   k].im;
00619         o_ptr[    2*k+1] =  z[0][63-k].re;
00620         o_ptr[128+2*k  ] = -z[0][   k].re;
00621         o_ptr[128+2*k+1] =  z[0][63-k].im;
00622         o_ptr[256+2*k  ] = -z[1][   k].re;
00623         o_ptr[256+2*k+1] =  z[1][63-k].im;
00624         o_ptr[384+2*k  ] =  z[1][   k].im;
00625         o_ptr[384+2*k+1] = -z[1][63-k].re;
00626     }
00627 }
00628 
00629 /**
00630  * Inverse MDCT Transform.
00631  * Convert frequency domain coefficients to time-domain audio samples.
00632  * reference: Section 7.9.4 Transformation Equations
00633  */
00634 static inline void do_imdct(AC3DecodeContext *s, int channels)
00635 {
00636     int ch;
00637 
00638     for (ch=1; ch<=channels; ch++) {
00639         if (s->block_switch[ch]) {
00640             do_imdct_256(s, ch);
00641         } else {
00642             s->imdct_512.fft.imdct_calc(&s->imdct_512, s->tmp_output,
00643                                         s->transform_coeffs[ch], s->tmp_imdct);
00644         }
00645         /* For the first half of the block, apply the window, add the delay
00646            from the previous block, and send to output */
00647         s->dsp.vector_fmul_add_add(s->output[ch-1], s->tmp_output,
00648                                      s->window, s->delay[ch-1], 0, 256, 1);
00649         /* For the second half of the block, apply the window and store the
00650            samples to delay, to be combined with the next block */
00651         s->dsp.vector_fmul_reverse(s->delay[ch-1], s->tmp_output+256,
00652                                    s->window, 256);
00653     }
00654 }
00655 
00656 /**
00657  * Downmix the output to mono or stereo.
00658  */
00659 static void ac3_downmix(AC3DecodeContext *s,
00660                         float samples[AC3_MAX_CHANNELS][256], int ch_offset)
00661 {
00662     int i, j;
00663     float v0, v1;
00664 
00665     for(i=0; i<256; i++) {
00666         v0 = v1 = 0.0f;
00667         for(j=0; j<s->fbw_channels; j++) {
00668             v0 += samples[j+ch_offset][i] * s->downmix_coeffs[j][0];
00669             v1 += samples[j+ch_offset][i] * s->downmix_coeffs[j][1];
00670         }
00671         v0 *= s->downmix_coeff_adjust[0];
00672         v1 *= s->downmix_coeff_adjust[1];
00673         if(s->output_mode == AC3_CHMODE_MONO) {
00674             samples[ch_offset][i] = (v0 + v1) * LEVEL_MINUS_3DB;
00675         } else if(s->output_mode == AC3_CHMODE_STEREO) {
00676             samples[  ch_offset][i] = v0;
00677             samples[1+ch_offset][i] = v1;
00678         }
00679     }
00680 }
00681 
00682 /**
00683  * Upmix delay samples from stereo to original channel layout.
00684  */
00685 static void ac3_upmix_delay(AC3DecodeContext *s)
00686 {
00687     int channel_data_size = sizeof(s->delay[0]);
00688     switch(s->channel_mode) {
00689         case AC3_CHMODE_DUALMONO:
00690         case AC3_CHMODE_STEREO:
00691             /* upmix mono to stereo */
00692             memcpy(s->delay[1], s->delay[0], channel_data_size);
00693             break;
00694         case AC3_CHMODE_2F2R:
00695             memset(s->delay[3], 0, channel_data_size);
00696         case AC3_CHMODE_2F1R:
00697             memset(s->delay[2], 0, channel_data_size);
00698             break;
00699         case AC3_CHMODE_3F2R:
00700             memset(s->delay[4], 0, channel_data_size);
00701         case AC3_CHMODE_3F1R:
00702             memset(s->delay[3], 0, channel_data_size);
00703         case AC3_CHMODE_3F:
00704             memcpy(s->delay[2], s->delay[1], channel_data_size);
00705             memset(s->delay[1], 0, channel_data_size);
00706             break;
00707     }
00708 }
00709 
00710 /**
00711  * Parse an audio block from AC-3 bitstream.
00712  */
00713 static int ac3_parse_audio_block(AC3DecodeContext *s, int blk)
00714 {
00715     int fbw_channels = s->fbw_channels;
00716     int channel_mode = s->channel_mode;
00717     int i, bnd, seg, ch;
00718     int different_transforms;
00719     int downmix_output;
00720     int cpl_in_use;
00721     GetBitContext *gbc = &s->gbc;
00722     uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
00723 
00724     memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
00725 
00726     /* block switch flags */
00727     different_transforms = 0;
00728     for (ch = 1; ch <= fbw_channels; ch++) {
00729         s->block_switch[ch] = get_bits1(gbc);
00730         if(ch > 1 && s->block_switch[ch] != s->block_switch[1])
00731             different_transforms = 1;
00732     }
00733 
00734     /* dithering flags */
00735     s->dither_all = 1;
00736     for (ch = 1; ch <= fbw_channels; ch++) {
00737         s->dither_flag[ch] = get_bits1(gbc);
00738         if(!s->dither_flag[ch])
00739             s->dither_all = 0;
00740     }
00741 
00742     /* dynamic range */
00743     i = !(s->channel_mode);
00744     do {
00745         if(get_bits1(gbc)) {
00746             s->dynamic_range[i] = ((dynamic_range_tab[get_bits(gbc, 8)]-1.0) *
00747                                   s->avctx->drc_scale)+1.0;
00748         } else if(blk == 0) {
00749             s->dynamic_range[i] = 1.0f;
00750         }
00751     } while(i--);
00752 
00753     /* coupling strategy */
00754     if (get_bits1(gbc)) {
00755         memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
00756         s->cpl_in_use[blk] = get_bits1(gbc);
00757         if (s->cpl_in_use[blk]) {
00758             /* coupling in use */
00759             int cpl_begin_freq, cpl_end_freq;
00760 
00761             if (channel_mode < AC3_CHMODE_STEREO) {
00762                 av_log(s->avctx, AV_LOG_ERROR, "coupling not allowed in mono or dual-mono\n");
00763                 return -1;
00764             }
00765 
00766             /* determine which channels are coupled */
00767             for (ch = 1; ch <= fbw_channels; ch++)
00768                 s->channel_in_cpl[ch] = get_bits1(gbc);
00769 
00770             /* phase flags in use */
00771             if (channel_mode == AC3_CHMODE_STEREO)
00772                 s->phase_flags_in_use = get_bits1(gbc);
00773 
00774             /* coupling frequency range and band structure */
00775             cpl_begin_freq = get_bits(gbc, 4);
00776             cpl_end_freq = get_bits(gbc, 4);
00777             if (3 + cpl_end_freq - cpl_begin_freq < 0) {
00778                 av_log(s->avctx, AV_LOG_ERROR, "3+cplendf = %d < cplbegf = %d\n", 3+cpl_end_freq, cpl_begin_freq);
00779                 return -1;
00780             }
00781             s->num_cpl_bands = s->num_cpl_subbands = 3 + cpl_end_freq - cpl_begin_freq;
00782             s->start_freq[CPL_CH] = cpl_begin_freq * 12 + 37;
00783             s->end_freq[CPL_CH] = cpl_end_freq * 12 + 73;
00784             for (bnd = 0; bnd < s->num_cpl_subbands - 1; bnd++) {
00785                 if (get_bits1(gbc)) {
00786                     s->cpl_band_struct[bnd] = 1;
00787                     s->num_cpl_bands--;
00788                 }
00789             }
00790             s->cpl_band_struct[s->num_cpl_subbands-1] = 0;
00791         } else {
00792             /* coupling not in use */
00793             for (ch = 1; ch <= fbw_channels; ch++)
00794                 s->channel_in_cpl[ch] = 0;
00795         }
00796     } else if (!blk) {
00797         av_log(s->avctx, AV_LOG_ERROR, "new coupling strategy must be present in block 0\n");
00798         return -1;
00799     } else {
00800         s->cpl_in_use[blk] = s->cpl_in_use[blk-1];
00801     }
00802     cpl_in_use = s->cpl_in_use[blk];
00803 
00804     /* coupling coordinates */
00805     if (cpl_in_use) {
00806         int cpl_coords_exist = 0;
00807 
00808         for (ch = 1; ch <= fbw_channels; ch++) {
00809             if (s->channel_in_cpl[ch]) {
00810                 if (get_bits1(gbc)) {
00811                     int master_cpl_coord, cpl_coord_exp, cpl_coord_mant;
00812                     cpl_coords_exist = 1;
00813                     master_cpl_coord = 3 * get_bits(gbc, 2);
00814                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00815                         cpl_coord_exp = get_bits(gbc, 4);
00816                         cpl_coord_mant = get_bits(gbc, 4);
00817                         if (cpl_coord_exp == 15)
00818                             s->cpl_coords[ch][bnd] = cpl_coord_mant << 22;
00819                         else
00820                             s->cpl_coords[ch][bnd] = (cpl_coord_mant + 16) << 21;
00821                         s->cpl_coords[ch][bnd] >>= (cpl_coord_exp + master_cpl_coord);
00822                     }
00823                 } else if (!blk) {
00824                     av_log(s->avctx, AV_LOG_ERROR, "new coupling coordinates must be present in block 0\n");
00825                     return -1;
00826                 }
00827             }
00828         }
00829         /* phase flags */
00830         if (channel_mode == AC3_CHMODE_STEREO && cpl_coords_exist) {
00831             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00832                 s->phase_flags[bnd] = s->phase_flags_in_use? get_bits1(gbc) : 0;
00833             }
00834         }
00835     }
00836 
00837     /* stereo rematrixing strategy and band structure */
00838     if (channel_mode == AC3_CHMODE_STEREO) {
00839         if (get_bits1(gbc)) {
00840             s->num_rematrixing_bands = 4;
00841             if(cpl_in_use && s->start_freq[CPL_CH] <= 61)
00842                 s->num_rematrixing_bands -= 1 + (s->start_freq[CPL_CH] == 37);
00843             for(bnd=0; bnd<s->num_rematrixing_bands; bnd++)
00844                 s->rematrixing_flags[bnd] = get_bits1(gbc);
00845         } else if (!blk) {
00846             av_log(s->avctx, AV_LOG_ERROR, "new rematrixing strategy must be present in block 0\n");
00847             return -1;
00848         }
00849     }
00850 
00851     /* exponent strategies for each channel */
00852     s->exp_strategy[blk][CPL_CH] = EXP_REUSE;
00853     s->exp_strategy[blk][s->lfe_ch] = EXP_REUSE;
00854     for (ch = !cpl_in_use; ch <= s->channels; ch++) {
00855         s->exp_strategy[blk][ch] = get_bits(gbc, 2 - (ch == s->lfe_ch));
00856         if(s->exp_strategy[blk][ch] != EXP_REUSE)
00857             bit_alloc_stages[ch] = 3;
00858     }
00859 
00860     /* channel bandwidth */
00861     for (ch = 1; ch <= fbw_channels; ch++) {
00862         s->start_freq[ch] = 0;
00863         if (s->exp_strategy[blk][ch] != EXP_REUSE) {
00864             int group_size;
00865             int prev = s->end_freq[ch];
00866             if (s->channel_in_cpl[ch])
00867                 s->end_freq[ch] = s->start_freq[CPL_CH];
00868             else {
00869                 int bandwidth_code = get_bits(gbc, 6);
00870                 if (bandwidth_code > 60) {
00871                     av_log(s->avctx, AV_LOG_ERROR, "bandwidth code = %d > 60", bandwidth_code);
00872                     return -1;
00873                 }
00874                 s->end_freq[ch] = bandwidth_code * 3 + 73;
00875             }
00876             group_size = 3 << (s->exp_strategy[blk][ch] - 1);
00877             s->num_exp_groups[ch] = (s->end_freq[ch]+group_size-4) / group_size;
00878             if(blk > 0 && s->end_freq[ch] != prev)
00879                 memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
00880         }
00881     }
00882     if (cpl_in_use && s->exp_strategy[blk][CPL_CH] != EXP_REUSE) {
00883         s->num_exp_groups[CPL_CH] = (s->end_freq[CPL_CH] - s->start_freq[CPL_CH]) /
00884                                     (3 << (s->exp_strategy[blk][CPL_CH] - 1));
00885     }
00886 
00887     /* decode exponents for each channel */
00888     for (ch = !cpl_in_use; ch <= s->channels; ch++) {
00889         if (s->exp_strategy[blk][ch] != EXP_REUSE) {
00890             s->dexps[ch][0] = get_bits(gbc, 4) << !ch;
00891             decode_exponents(gbc, s->exp_strategy[blk][ch],
00892                              s->num_exp_groups[ch], s->dexps[ch][0],
00893                              &s->dexps[ch][s->start_freq[ch]+!!ch]);
00894             if(ch != CPL_CH && ch != s->lfe_ch)
00895                 skip_bits(gbc, 2); /* skip gainrng */
00896         }
00897     }
00898 
00899     /* bit allocation information */
00900     if (get_bits1(gbc)) {
00901         s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
00902         s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
00903         s->bit_alloc_params.slow_gain  = ff_ac3_slow_gain_tab[get_bits(gbc, 2)];
00904         s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gbc, 2)];
00905         s->bit_alloc_params.floor  = ff_ac3_floor_tab[get_bits(gbc, 3)];
00906         for(ch=!cpl_in_use; ch<=s->channels; ch++)
00907             bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
00908     } else if (!blk) {
00909         av_log(s->avctx, AV_LOG_ERROR, "new bit allocation info must be present in block 0\n");
00910         return -1;
00911     }
00912 
00913     /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
00914     if (get_bits1(gbc)) {
00915         int csnr;
00916         csnr = (get_bits(gbc, 6) - 15) << 4;
00917         for (ch = !cpl_in_use; ch <= s->channels; ch++) { /* snr offset and fast gain */
00918             s->snr_offset[ch] = (csnr + get_bits(gbc, 4)) << 2;
00919             s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
00920         }
00921         memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
00922     } else if (!blk) {
00923         av_log(s->avctx, AV_LOG_ERROR, "new snr offsets must be present in block 0\n");
00924         return -1;
00925     }
00926 
00927     /* coupling leak information */
00928     if (cpl_in_use) {
00929         if (get_bits1(gbc)) {
00930             s->bit_alloc_params.cpl_fast_leak = get_bits(gbc, 3);
00931             s->bit_alloc_params.cpl_slow_leak = get_bits(gbc, 3);
00932             bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
00933         } else if (!blk) {
00934             av_log(s->avctx, AV_LOG_ERROR, "new coupling leak info must be present in block 0\n");
00935             return -1;
00936         }
00937     }
00938 
00939     /* delta bit allocation information */
00940     if (get_bits1(gbc)) {
00941         /* delta bit allocation exists (strategy) */
00942         for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
00943             s->dba_mode[ch] = get_bits(gbc, 2);
00944             if (s->dba_mode[ch] == DBA_RESERVED) {
00945                 av_log(s->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
00946                 return -1;
00947             }
00948             bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
00949         }
00950         /* channel delta offset, len and bit allocation */
00951         for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
00952             if (s->dba_mode[ch] == DBA_NEW) {
00953                 s->dba_nsegs[ch] = get_bits(gbc, 3);
00954                 for (seg = 0; seg <= s->dba_nsegs[ch]; seg++) {
00955                     s->dba_offsets[ch][seg] = get_bits(gbc, 5);
00956                     s->dba_lengths[ch][seg] = get_bits(gbc, 4);
00957                     s->dba_values[ch][seg] = get_bits(gbc, 3);
00958                 }
00959                 /* run last 2 bit allocation stages if new dba values */
00960                 bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
00961             }
00962         }
00963     } else if(blk == 0) {
00964         for(ch=0; ch<=s->channels; ch++) {
00965             s->dba_mode[ch] = DBA_NONE;
00966         }
00967     }
00968 
00969     /* Bit allocation */
00970     for(ch=!cpl_in_use; ch<=s->channels; ch++) {
00971         if(bit_alloc_stages[ch] > 2) {
00972             /* Exponent mapping into PSD and PSD integration */
00973             ff_ac3_bit_alloc_calc_psd(s->dexps[ch],
00974                                       s->start_freq[ch], s->end_freq[ch],
00975                                       s->psd[ch], s->band_psd[ch]);
00976         }
00977         if(bit_alloc_stages[ch] > 1) {
00978             /* Compute excitation function, Compute masking curve, and
00979                Apply delta bit allocation */
00980             ff_ac3_bit_alloc_calc_mask(&s->bit_alloc_params, s->band_psd[ch],
00981                                        s->start_freq[ch], s->end_freq[ch],
00982                                        s->fast_gain[ch], (ch == s->lfe_ch),
00983                                        s->dba_mode[ch], s->dba_nsegs[ch],
00984                                        s->dba_offsets[ch], s->dba_lengths[ch],
00985                                        s->dba_values[ch], s->mask[ch]);
00986         }
00987         if(bit_alloc_stages[ch] > 0) {
00988             /* Compute bit allocation */
00989             ff_ac3_bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
00990                                       s->start_freq[ch], s->end_freq[ch],
00991                                       s->snr_offset[ch],
00992                                       s->bit_alloc_params.floor,
00993                                       ff_ac3_bap_tab, s->bap[ch]);
00994         }
00995     }
00996 
00997     /* unused dummy data */
00998     if (get_bits1(gbc)) {
00999         int skipl = get_bits(gbc, 9);
01000         while(skipl--)
01001             skip_bits(gbc, 8);
01002     }
01003 
01004     /* unpack the transform coefficients
01005        this also uncouples channels if coupling is in use. */
01006     get_transform_coeffs(s);
01007 
01008     /* recover coefficients if rematrixing is in use */
01009     if(s->channel_mode == AC3_CHMODE_STEREO)
01010         do_rematrixing(s);
01011 
01012     /* apply scaling to coefficients (headroom, dynrng) */
01013     for(ch=1; ch<=s->channels; ch++) {
01014         float gain = s->mul_bias / 4194304.0f;
01015         if(s->channel_mode == AC3_CHMODE_DUALMONO) {
01016             gain *= s->dynamic_range[ch-1];
01017         }