Libav 0.7.1
libavcodec/ac3enc.c
Go to the documentation of this file.
00001 /*
00002  * The simplest AC-3 encoder
00003  * Copyright (c) 2000 Fabrice Bellard
00004  * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
00005  * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
00006  *
00007  * This file is part of Libav.
00008  *
00009  * Libav is free software; you can redistribute it and/or
00010  * modify it under the terms of the GNU Lesser General Public
00011  * License as published by the Free Software Foundation; either
00012  * version 2.1 of the License, or (at your option) any later version.
00013  *
00014  * Libav is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00017  * Lesser General Public License for more details.
00018  *
00019  * You should have received a copy of the GNU Lesser General Public
00020  * License along with Libav; if not, write to the Free Software
00021  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00022  */
00023 
00029 //#define ASSERT_LEVEL 2
00030 
00031 #include <stdint.h>
00032 
00033 #include "libavutil/audioconvert.h"
00034 #include "libavutil/avassert.h"
00035 #include "libavutil/avstring.h"
00036 #include "libavutil/crc.h"
00037 #include "libavutil/opt.h"
00038 #include "avcodec.h"
00039 #include "put_bits.h"
00040 #include "dsputil.h"
00041 #include "ac3dsp.h"
00042 #include "ac3.h"
00043 #include "audioconvert.h"
00044 #include "fft.h"
00045 #include "ac3enc.h"
00046 #include "eac3enc.h"
00047 
00048 typedef struct AC3Mant {
00049     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; 
00050     int mant1_cnt, mant2_cnt, mant4_cnt;    
00051 } AC3Mant;
00052 
00053 #define CMIXLEV_NUM_OPTIONS 3
00054 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
00055     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
00056 };
00057 
00058 #define SURMIXLEV_NUM_OPTIONS 3
00059 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
00060     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
00061 };
00062 
00063 #define EXTMIXLEV_NUM_OPTIONS 8
00064 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
00065     LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
00066     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
00067 };
00068 
00069 
00074 static uint8_t exponent_group_tab[2][3][256];
00075 
00076 
00080 const int64_t ff_ac3_channel_layouts[19] = {
00081      AV_CH_LAYOUT_MONO,
00082      AV_CH_LAYOUT_STEREO,
00083      AV_CH_LAYOUT_2_1,
00084      AV_CH_LAYOUT_SURROUND,
00085      AV_CH_LAYOUT_2_2,
00086      AV_CH_LAYOUT_QUAD,
00087      AV_CH_LAYOUT_4POINT0,
00088      AV_CH_LAYOUT_5POINT0,
00089      AV_CH_LAYOUT_5POINT0_BACK,
00090     (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
00091     (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
00092     (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
00093     (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
00094     (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
00095     (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
00096     (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
00097      AV_CH_LAYOUT_5POINT1,
00098      AV_CH_LAYOUT_5POINT1_BACK,
00099      0
00100 };
00101 
00102 
00108 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
00109 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
00110 
00111     { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
00112       {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
00113       {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
00114 
00115     { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
00116       {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
00117       {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
00118 
00119     { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
00120       {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
00121       {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
00122 
00123     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
00124       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
00125       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
00126 
00127     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
00128       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
00129       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
00130 };
00131 
00132 
00141 static const int8_t ac3_coupling_start_tab[6][3][19] = {
00142 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
00143 
00144     // 2/0
00145     { {  0,  0,  0,  0,  0,  0,  0,  1,  1,  7,  8, 11, 12, -1, -1, -1, -1, -1, -1 },
00146       {  0,  0,  0,  0,  0,  0,  1,  3,  5,  7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
00147       {  0,  0,  0,  0,  1,  2,  2,  9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00148 
00149     // 3/0
00150     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
00151       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
00152       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00153 
00154     // 2/1 - untested
00155     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
00156       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
00157       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00158 
00159     // 3/1
00160     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
00161       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
00162       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00163 
00164     // 2/2 - untested
00165     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
00166       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
00167       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00168 
00169     // 3/2
00170     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
00171       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
00172       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
00173 };
00174 
00175 
00180 static void adjust_frame_size(AC3EncodeContext *s)
00181 {
00182     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
00183         s->bits_written    -= s->bit_rate;
00184         s->samples_written -= s->sample_rate;
00185     }
00186     s->frame_size = s->frame_size_min +
00187                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
00188     s->bits_written    += s->frame_size * 8;
00189     s->samples_written += AC3_FRAME_SIZE;
00190 }
00191 
00192 
00193 static void compute_coupling_strategy(AC3EncodeContext *s)
00194 {
00195     int blk, ch;
00196     int got_cpl_snr;
00197 
00198     /* set coupling use flags for each block/channel */
00199     /* TODO: turn coupling on/off and adjust start band based on bit usage */
00200     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00201         AC3Block *block = &s->blocks[blk];
00202         for (ch = 1; ch <= s->fbw_channels; ch++)
00203             block->channel_in_cpl[ch] = s->cpl_on;
00204     }
00205 
00206     /* enable coupling for each block if at least 2 channels have coupling
00207        enabled for that block */
00208     got_cpl_snr = 0;
00209     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00210         AC3Block *block = &s->blocks[blk];
00211         block->num_cpl_channels = 0;
00212         for (ch = 1; ch <= s->fbw_channels; ch++)
00213             block->num_cpl_channels += block->channel_in_cpl[ch];
00214         block->cpl_in_use = block->num_cpl_channels > 1;
00215         if (!block->cpl_in_use) {
00216             block->num_cpl_channels = 0;
00217             for (ch = 1; ch <= s->fbw_channels; ch++)
00218                 block->channel_in_cpl[ch] = 0;
00219         }
00220 
00221         block->new_cpl_strategy = !blk;
00222         if (blk) {
00223             for (ch = 1; ch <= s->fbw_channels; ch++) {
00224                 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
00225                     block->new_cpl_strategy = 1;
00226                     break;
00227                 }
00228             }
00229         }
00230         block->new_cpl_leak = block->new_cpl_strategy;
00231 
00232         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
00233             block->new_snr_offsets = 1;
00234             if (block->cpl_in_use)
00235                 got_cpl_snr = 1;
00236         } else {
00237             block->new_snr_offsets = 0;
00238         }
00239     }
00240 
00241     /* set bandwidth for each channel */
00242     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00243         AC3Block *block = &s->blocks[blk];
00244         for (ch = 1; ch <= s->fbw_channels; ch++) {
00245             if (block->channel_in_cpl[ch])
00246                 block->end_freq[ch] = s->start_freq[CPL_CH];
00247             else
00248                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
00249         }
00250     }
00251 }
00252 
00253 
00257 static void apply_rematrixing(AC3EncodeContext *s)
00258 {
00259     int nb_coefs;
00260     int blk, bnd, i;
00261     int start, end;
00262     uint8_t *flags;
00263 
00264     if (!s->rematrixing_enabled)
00265         return;
00266 
00267     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00268         AC3Block *block = &s->blocks[blk];
00269         if (block->new_rematrixing_strategy)
00270             flags = block->rematrixing_flags;
00271         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
00272         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
00273             if (flags[bnd]) {
00274                 start = ff_ac3_rematrix_band_tab[bnd];
00275                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
00276                 for (i = start; i < end; i++) {
00277                     int32_t lt = block->fixed_coef[1][i];
00278                     int32_t rt = block->fixed_coef[2][i];
00279                     block->fixed_coef[1][i] = (lt + rt) >> 1;
00280                     block->fixed_coef[2][i] = (lt - rt) >> 1;
00281                 }
00282             }
00283         }
00284     }
00285 }
00286 
00287 
00291 static av_cold void exponent_init(AC3EncodeContext *s)
00292 {
00293     int expstr, i, grpsize;
00294 
00295     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
00296         grpsize = 3 << expstr;
00297         for (i = 12; i < 256; i++) {
00298             exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
00299             exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
00300         }
00301     }
00302     /* LFE */
00303     exponent_group_tab[0][0][7] = 2;
00304 }
00305 
00306 
00312 static void extract_exponents(AC3EncodeContext *s)
00313 {
00314     int ch        = !s->cpl_on;
00315     int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
00316     AC3Block *block = &s->blocks[0];
00317 
00318     s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
00319 }
00320 
00321 
00326 #define EXP_DIFF_THRESHOLD 500
00327 
00328 
00333 static void compute_exp_strategy(AC3EncodeContext *s)
00334 {
00335     int ch, blk, blk1;
00336 
00337     for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
00338         uint8_t *exp_strategy = s->exp_strategy[ch];
00339         uint8_t *exp          = s->blocks[0].exp[ch];
00340         int exp_diff;
00341 
00342         /* estimate if the exponent variation & decide if they should be
00343            reused in the next frame */
00344         exp_strategy[0] = EXP_NEW;
00345         exp += AC3_MAX_COEFS;
00346         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
00347             if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
00348                 (ch  > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
00349                 exp_strategy[blk] = EXP_NEW;
00350                 continue;
00351             }
00352             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
00353             exp_strategy[blk] = EXP_REUSE;
00354             if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
00355                 exp_strategy[blk] = EXP_NEW;
00356             else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
00357                 exp_strategy[blk] = EXP_NEW;
00358         }
00359 
00360         /* now select the encoding strategy type : if exponents are often
00361            recoded, we use a coarse encoding */
00362         blk = 0;
00363         while (blk < AC3_MAX_BLOCKS) {
00364             blk1 = blk + 1;
00365             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
00366                 blk1++;
00367             switch (blk1 - blk) {
00368             case 1:  exp_strategy[blk] = EXP_D45; break;
00369             case 2:
00370             case 3:  exp_strategy[blk] = EXP_D25; break;
00371             default: exp_strategy[blk] = EXP_D15; break;
00372             }
00373             blk = blk1;
00374         }
00375     }
00376     if (s->lfe_on) {
00377         ch = s->lfe_channel;
00378         s->exp_strategy[ch][0] = EXP_D15;
00379         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
00380             s->exp_strategy[ch][blk] = EXP_REUSE;
00381     }
00382 }
00383 
00384 
00388 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
00389                                     int cpl)
00390 {
00391     int nb_groups, i, k;
00392 
00393     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
00394 
00395     /* for each group, compute the minimum exponent */
00396     switch(exp_strategy) {
00397     case EXP_D25:
00398         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
00399             uint8_t exp_min = exp[k];
00400             if (exp[k+1] < exp_min)
00401                 exp_min = exp[k+1];
00402             exp[i-cpl] = exp_min;
00403             k += 2;
00404         }
00405         break;
00406     case EXP_D45:
00407         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
00408             uint8_t exp_min = exp[k];
00409             if (exp[k+1] < exp_min)
00410                 exp_min = exp[k+1];
00411             if (exp[k+2] < exp_min)
00412                 exp_min = exp[k+2];
00413             if (exp[k+3] < exp_min)
00414                 exp_min = exp[k+3];
00415             exp[i-cpl] = exp_min;
00416             k += 4;
00417         }
00418         break;
00419     }
00420 
00421     /* constraint for DC exponent */
00422     if (!cpl && exp[0] > 15)
00423         exp[0] = 15;
00424 
00425     /* decrease the delta between each groups to within 2 so that they can be
00426        differentially encoded */
00427     for (i = 1; i <= nb_groups; i++)
00428         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
00429     i--;
00430     while (--i >= 0)
00431         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
00432 
00433     if (cpl)
00434         exp[-1] = exp[0] & ~1;
00435 
00436     /* now we have the exponent values the decoder will see */
00437     switch (exp_strategy) {
00438     case EXP_D25:
00439         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
00440             uint8_t exp1 = exp[i-cpl];
00441             exp[k--] = exp1;
00442             exp[k--] = exp1;
00443         }
00444         break;
00445     case EXP_D45:
00446         for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
00447             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
00448             k -= 4;
00449         }
00450         break;
00451     }
00452 }
00453 
00454 
00461 static void encode_exponents(AC3EncodeContext *s)
00462 {
00463     int blk, blk1, ch, cpl;
00464     uint8_t *exp, *exp_strategy;
00465     int nb_coefs, num_reuse_blocks;
00466 
00467     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
00468         exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
00469         exp_strategy = s->exp_strategy[ch];
00470 
00471         cpl = (ch == CPL_CH);
00472         blk = 0;
00473         while (blk < AC3_MAX_BLOCKS) {
00474             AC3Block *block = &s->blocks[blk];
00475             if (cpl && !block->cpl_in_use) {
00476                 exp += AC3_MAX_COEFS;
00477                 blk++;
00478                 continue;
00479             }
00480             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
00481             blk1 = blk + 1;
00482 
00483             /* count the number of EXP_REUSE blocks after the current block
00484                and set exponent reference block numbers */
00485             s->exp_ref_block[ch][blk] = blk;
00486             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
00487                 s->exp_ref_block[ch][blk1] = blk;
00488                 blk1++;
00489             }
00490             num_reuse_blocks = blk1 - blk - 1;
00491 
00492             /* for the EXP_REUSE case we select the min of the exponents */
00493             s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
00494                                        AC3_MAX_COEFS);
00495 
00496             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
00497 
00498             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
00499             blk = blk1;
00500         }
00501     }
00502 
00503     /* reference block numbers have been changed, so reset ref_bap_set */
00504     s->ref_bap_set = 0;
00505 }
00506 
00507 
00513 static void group_exponents(AC3EncodeContext *s)
00514 {
00515     int blk, ch, i, cpl;
00516     int group_size, nb_groups, bit_count;
00517     uint8_t *p;
00518     int delta0, delta1, delta2;
00519     int exp0, exp1;
00520 
00521     bit_count = 0;
00522     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00523         AC3Block *block = &s->blocks[blk];
00524         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00525             int exp_strategy = s->exp_strategy[ch][blk];
00526             if (exp_strategy == EXP_REUSE)
00527                 continue;
00528             cpl = (ch == CPL_CH);
00529             group_size = exp_strategy + (exp_strategy == EXP_D45);
00530             nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
00531             bit_count += 4 + (nb_groups * 7);
00532             p = block->exp[ch] + s->start_freq[ch] - cpl;
00533 
00534             /* DC exponent */
00535             exp1 = *p++;
00536             block->grouped_exp[ch][0] = exp1;
00537 
00538             /* remaining exponents are delta encoded */
00539             for (i = 1; i <= nb_groups; i++) {
00540                 /* merge three delta in one code */
00541                 exp0   = exp1;
00542                 exp1   = p[0];
00543                 p     += group_size;
00544                 delta0 = exp1 - exp0 + 2;
00545                 av_assert2(delta0 >= 0 && delta0 <= 4);
00546 
00547                 exp0   = exp1;
00548                 exp1   = p[0];
00549                 p     += group_size;
00550                 delta1 = exp1 - exp0 + 2;
00551                 av_assert2(delta1 >= 0 && delta1 <= 4);
00552 
00553                 exp0   = exp1;
00554                 exp1   = p[0];
00555                 p     += group_size;
00556                 delta2 = exp1 - exp0 + 2;
00557                 av_assert2(delta2 >= 0 && delta2 <= 4);
00558 
00559                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
00560             }
00561         }
00562     }
00563 
00564     s->exponent_bits = bit_count;
00565 }
00566 
00567 
00573 static void process_exponents(AC3EncodeContext *s)
00574 {
00575     extract_exponents(s);
00576 
00577     compute_exp_strategy(s);
00578 
00579     encode_exponents(s);
00580 
00581     group_exponents(s);
00582 
00583     emms_c();
00584 }
00585 
00586 
00591 static void count_frame_bits_fixed(AC3EncodeContext *s)
00592 {
00593     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
00594     int blk;
00595     int frame_bits;
00596 
00597     /* assumptions:
00598      *   no dynamic range codes
00599      *   bit allocation parameters do not change between blocks
00600      *   no delta bit allocation
00601      *   no skipped data
00602      *   no auxilliary data
00603      *   no E-AC-3 metadata
00604      */
00605 
00606     /* header */
00607     frame_bits = 16; /* sync info */
00608     if (s->eac3) {
00609         /* bitstream info header */
00610         frame_bits += 35;
00611         frame_bits += 1 + 1 + 1;
00612         /* audio frame header */
00613         frame_bits += 2;
00614         frame_bits += 10;
00615         /* exponent strategy */
00616         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
00617             frame_bits += 2 * s->fbw_channels + s->lfe_on;
00618         /* converter exponent strategy */
00619         frame_bits += s->fbw_channels * 5;
00620         /* snr offsets */
00621         frame_bits += 10;
00622         /* block start info */
00623         frame_bits++;
00624     } else {
00625         frame_bits += 49;
00626         frame_bits += frame_bits_inc[s->channel_mode];
00627     }
00628 
00629     /* audio blocks */
00630     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00631         if (!s->eac3) {
00632             /* block switch flags */
00633             frame_bits += s->fbw_channels;
00634 
00635             /* dither flags */
00636             frame_bits += s->fbw_channels;
00637         }
00638 
00639         /* dynamic range */
00640         frame_bits++;
00641 
00642         /* spectral extension */
00643         if (s->eac3)
00644             frame_bits++;
00645 
00646         if (!s->eac3) {
00647             /* exponent strategy */
00648             frame_bits += 2 * s->fbw_channels;
00649             if (s->lfe_on)
00650                 frame_bits++;
00651 
00652             /* bit allocation params */
00653             frame_bits++;
00654             if (!blk)
00655                 frame_bits += 2 + 2 + 2 + 2 + 3;
00656         }
00657 
00658         /* converter snr offset */
00659         if (s->eac3)
00660             frame_bits++;
00661 
00662         if (!s->eac3) {
00663             /* delta bit allocation */
00664             frame_bits++;
00665 
00666             /* skipped data */
00667             frame_bits++;
00668         }
00669     }
00670 
00671     /* auxiliary data */
00672     frame_bits++;
00673 
00674     /* CRC */
00675     frame_bits += 1 + 16;
00676 
00677     s->frame_bits_fixed = frame_bits;
00678 }
00679 
00680 
00685 static void bit_alloc_init(AC3EncodeContext *s)
00686 {
00687     int ch;
00688 
00689     /* init default parameters */
00690     s->slow_decay_code = 2;
00691     s->fast_decay_code = 1;
00692     s->slow_gain_code  = 1;
00693     s->db_per_bit_code = s->eac3 ? 2 : 3;
00694     s->floor_code      = 7;
00695     for (ch = 0; ch <= s->channels; ch++)
00696         s->fast_gain_code[ch] = 4;
00697 
00698     /* initial snr offset */
00699     s->coarse_snr_offset = 40;
00700 
00701     /* compute real values */
00702     /* currently none of these values change during encoding, so we can just
00703        set them once at initialization */
00704     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
00705     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
00706     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
00707     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
00708     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
00709     s->bit_alloc.cpl_fast_leak = 0;
00710     s->bit_alloc.cpl_slow_leak = 0;
00711 
00712     count_frame_bits_fixed(s);
00713 }
00714 
00715 
00721 static void count_frame_bits(AC3EncodeContext *s)
00722 {
00723     AC3EncOptions *opt = &s->options;
00724     int blk, ch;
00725     int frame_bits = 0;
00726 
00727     /* header */
00728     if (s->eac3) {
00729         /* coupling */
00730         if (s->channel_mode > AC3_CHMODE_MONO) {
00731             frame_bits++;
00732             for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
00733                 AC3Block *block = &s->blocks[blk];
00734                 frame_bits++;
00735                 if (block->new_cpl_strategy)
00736                     frame_bits++;
00737             }
00738         }
00739         /* coupling exponent strategy */
00740         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
00741             frame_bits += 2 * s->blocks[blk].cpl_in_use;
00742     } else {
00743         if (opt->audio_production_info)
00744             frame_bits += 7;
00745         if (s->bitstream_id == 6) {
00746             if (opt->extended_bsi_1)
00747                 frame_bits += 14;
00748             if (opt->extended_bsi_2)
00749                 frame_bits += 14;
00750         }
00751     }
00752 
00753     /* audio blocks */
00754     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00755         AC3Block *block = &s->blocks[blk];
00756 
00757         /* coupling strategy */
00758         if (!s->eac3)
00759             frame_bits++;
00760         if (block->new_cpl_strategy) {
00761             if (!s->eac3)
00762                 frame_bits++;
00763             if (block->cpl_in_use) {
00764                 if (s->eac3)
00765                     frame_bits++;
00766                 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
00767                     frame_bits += s->fbw_channels;
00768                 if (s->channel_mode == AC3_CHMODE_STEREO)
00769                     frame_bits++;
00770                 frame_bits += 4 + 4;
00771                 if (s->eac3)
00772                     frame_bits++;
00773                 else
00774                     frame_bits += s->num_cpl_subbands - 1;
00775             }
00776         }
00777 
00778         /* coupling coordinates */
00779         if (block->cpl_in_use) {
00780             for (ch = 1; ch <= s->fbw_channels; ch++) {
00781                 if (block->channel_in_cpl[ch]) {
00782                     if (!s->eac3 || block->new_cpl_coords != 2)
00783                         frame_bits++;
00784                     if (block->new_cpl_coords) {
00785                         frame_bits += 2;
00786                         frame_bits += (4 + 4) * s->num_cpl_bands;
00787                     }
00788                 }
00789             }
00790         }
00791 
00792         /* stereo rematrixing */
00793         if (s->channel_mode == AC3_CHMODE_STEREO) {
00794             if (!s->eac3 || blk > 0)
00795                 frame_bits++;
00796             if (s->blocks[blk].new_rematrixing_strategy)
00797                 frame_bits += block->num_rematrixing_bands;
00798         }
00799 
00800         /* bandwidth codes & gain range */
00801         for (ch = 1; ch <= s->fbw_channels; ch++) {
00802             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
00803                 if (!block->channel_in_cpl[ch])
00804                     frame_bits += 6;
00805                 frame_bits += 2;
00806             }
00807         }
00808 
00809         /* coupling exponent strategy */
00810         if (!s->eac3 && block->cpl_in_use)
00811             frame_bits += 2;
00812 
00813         /* snr offsets and fast gain codes */
00814         if (!s->eac3) {
00815             frame_bits++;
00816             if (block->new_snr_offsets)
00817                 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
00818         }
00819 
00820         /* coupling leak info */
00821         if (block->cpl_in_use) {
00822             if (!s->eac3 || block->new_cpl_leak != 2)
00823                 frame_bits++;
00824             if (block->new_cpl_leak)
00825                 frame_bits += 3 + 3;
00826         }
00827     }
00828 
00829     s->frame_bits = s->frame_bits_fixed + frame_bits;
00830 }
00831 
00832 
00837 static void bit_alloc_masking(AC3EncodeContext *s)
00838 {
00839     int blk, ch;
00840 
00841     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00842         AC3Block *block = &s->blocks[blk];
00843         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00844             /* We only need psd and mask for calculating bap.
00845                Since we currently do not calculate bap when exponent
00846                strategy is EXP_REUSE we do not need to calculate psd or mask. */
00847             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
00848                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
00849                                           block->end_freq[ch], block->psd[ch],
00850                                           block->band_psd[ch]);
00851                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
00852                                            s->start_freq[ch], block->end_freq[ch],
00853                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
00854                                            ch == s->lfe_channel,
00855                                            DBA_NONE, 0, NULL, NULL, NULL,
00856                                            block->mask[ch]);
00857             }
00858         }
00859     }
00860 }
00861 
00862 
00867 static void reset_block_bap(AC3EncodeContext *s)
00868 {
00869     int blk, ch;
00870     uint8_t *ref_bap;
00871 
00872     if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
00873         return;
00874 
00875     ref_bap = s->bap_buffer;
00876     for (ch = 0; ch <= s->channels; ch++) {
00877         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
00878             s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
00879         ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
00880     }
00881     s->ref_bap_set = 1;
00882 }
00883 
00884 
00890 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
00891 {
00892     int blk;
00893 
00894     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00895         memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
00896         mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
00897         mant_cnt[blk][4] = 1;
00898     }
00899 }
00900 
00901 
00906 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
00907                                           uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
00908                                           int start, int end)
00909 {
00910     int blk;
00911 
00912     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00913         AC3Block *block = &s->blocks[blk];
00914         if (ch == CPL_CH && !block->cpl_in_use)
00915             continue;
00916         s->ac3dsp.update_bap_counts(mant_cnt[blk],
00917                                     s->ref_bap[ch][blk] + start,
00918                                     FFMIN(end, block->end_freq[ch]) - start);
00919     }
00920 }
00921 
00922 
00926 static int count_mantissa_bits(AC3EncodeContext *s)
00927 {
00928     int ch, max_end_freq;
00929     LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
00930 
00931     count_mantissa_bits_init(mant_cnt);
00932 
00933     max_end_freq = s->bandwidth_code * 3 + 73;
00934     for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
00935         count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
00936                                       max_end_freq);
00937 
00938     return s->ac3dsp.compute_mantissa_size(mant_cnt);
00939 }
00940 
00941 
00949 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
00950 {
00951     int blk, ch;
00952 
00953     snr_offset = (snr_offset - 240) << 2;
00954 
00955     reset_block_bap(s);
00956     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
00957         AC3Block *block = &s->blocks[blk];
00958 
00959         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00960             /* Currently the only bit allocation parameters which vary across
00961                blocks within a frame are the exponent values.  We can take
00962                advantage of that by reusing the bit allocation pointers
00963                whenever we reuse exponents. */
00964             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
00965                 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
00966                                              s->start_freq[ch], block->end_freq[ch],
00967                                              snr_offset, s->bit_alloc.floor,
00968                                              ff_ac3_bap_tab, s->ref_bap[ch][blk]);
00969             }
00970         }
00971     }
00972     return count_mantissa_bits(s);
00973 }
00974 
00975 
00980 static int cbr_bit_allocation(AC3EncodeContext *s)
00981 {
00982     int ch;
00983     int bits_left;
00984     int snr_offset, snr_incr;
00985 
00986     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
00987     if (bits_left < 0)
00988         return AVERROR(EINVAL);
00989 
00990     snr_offset = s->coarse_snr_offset << 4;
00991 
00992     /* if previous frame SNR offset was 1023, check if current frame can also
00993        use SNR offset of 1023. if so, skip the search. */
00994     if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
00995         if (bit_alloc(s, 1023) <= bits_left)
00996             return 0;
00997     }
00998 
00999     while (snr_offset >= 0 &&
01000            bit_alloc(s, snr_offset) > bits_left) {
01001         snr_offset -= 64;
01002     }
01003     if (snr_offset < 0)
01004         return AVERROR(EINVAL);
01005 
01006     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01007     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
01008         while (snr_offset + snr_incr <= 1023 &&
01009                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
01010             snr_offset += snr_incr;
01011             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01012         }
01013     }
01014     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01015     reset_block_bap(s);
01016 
01017     s->coarse_snr_offset = snr_offset >> 4;
01018     for (ch = !s->cpl_on; ch <= s->channels; ch++)
01019         s->fine_snr_offset[ch] = snr_offset & 0xF;
01020 
01021     return 0;
01022 }
01023 
01024 
01032 static int downgrade_exponents(AC3EncodeContext *s)
01033 {
01034     int ch, blk;
01035 
01036     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
01037         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
01038             if (s->exp_strategy[ch][blk] == EXP_D15) {
01039                 s->exp_strategy[ch][blk] = EXP_D25;
01040                 return 0;
01041             }
01042         }
01043     }
01044     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
01045         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
01046             if (s->exp_strategy[ch][blk] == EXP_D25) {
01047                 s->exp_strategy[ch][blk] = EXP_D45;
01048                 return 0;
01049             }
01050         }
01051     }
01052     /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
01053        the block number > 0 */
01054     for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
01055         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
01056             if (s->exp_strategy[ch][blk] > EXP_REUSE) {
01057                 s->exp_strategy[ch][blk] = EXP_REUSE;
01058                 return 0;
01059             }
01060         }
01061     }
01062     return -1;
01063 }
01064 
01065 
01072 static int compute_bit_allocation(AC3EncodeContext *s)
01073 {
01074     int ret;
01075 
01076     count_frame_bits(s);
01077 
01078     bit_alloc_masking(s);
01079 
01080     ret = cbr_bit_allocation(s);
01081     while (ret) {
01082         /* fallback 1: disable channel coupling */
01083         if (s->cpl_on) {
01084             s->cpl_on = 0;
01085             compute_coupling_strategy(s);
01086             s->compute_rematrixing_strategy(s);
01087             apply_rematrixing(s);
01088             process_exponents(s);
01089             ret = compute_bit_allocation(s);
01090             continue;
01091         }
01092 
01093         /* fallback 2: downgrade exponents */
01094         if (!downgrade_exponents(s)) {
01095             extract_exponents(s);
01096             encode_exponents(s);
01097             group_exponents(s);
01098             ret = compute_bit_allocation(s);
01099             continue;
01100         }
01101 
01102         /* fallbacks were not enough... */
01103         break;
01104     }
01105 
01106     return ret;
01107 }
01108 
01109 
01113 static inline int sym_quant(int c, int e, int levels)
01114 {
01115     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
01116     av_assert2(v >= 0 && v < levels);
01117     return v;
01118 }
01119 
01120 
01124 static inline int asym_quant(int c, int e, int qbits)
01125 {
01126     int lshift, m, v;
01127 
01128     lshift = e + qbits - 24;
01129     if (lshift >= 0)
01130         v = c << lshift;
01131     else
01132         v = c >> (-lshift);
01133     /* rounding */
01134     v = (v + 1) >> 1;
01135     m = (1 << (qbits-1));
01136     if (v >= m)
01137         v = m - 1;
01138     av_assert2(v >= -m);
01139     return v & ((1 << qbits)-1);
01140 }
01141 
01142 
01146 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
01147                                       uint8_t *exp, uint8_t *bap,
01148                                       uint16_t *qmant, int start_freq,
01149                                       int end_freq)
01150 {
01151     int i;
01152 
01153     for (i = start_freq; i < end_freq; i++) {
01154         int v;
01155         int c = fixed_coef[i];
01156         int e = exp[i];
01157         int b = bap[i];
01158         switch (b) {
01159         case 0:
01160             v = 0;
01161             break;
01162         case 1:
01163             v = sym_quant(c, e, 3);
01164             switch (s->mant1_cnt) {
01165             case 0:
01166                 s->qmant1_ptr = &qmant[i];
01167                 v = 9 * v;
01168                 s->mant1_cnt = 1;
01169                 break;
01170             case 1:
01171                 *s->qmant1_ptr += 3 * v;
01172                 s->mant1_cnt = 2;
01173                 v = 128;
01174                 break;
01175             default:
01176                 *s->qmant1_ptr += v;
01177                 s->mant1_cnt = 0;
01178                 v = 128;
01179                 break;
01180             }
01181             break;
01182         case 2:
01183             v = sym_quant(c, e, 5);
01184             switch (s->mant2_cnt) {
01185             case 0:
01186                 s->qmant2_ptr = &qmant[i];
01187                 v = 25 * v;
01188                 s->mant2_cnt = 1;
01189                 break;
01190             case 1:
01191                 *s->qmant2_ptr += 5 * v;
01192                 s->mant2_cnt = 2;
01193                 v = 128;
01194                 break;
01195             default:
01196                 *s->qmant2_ptr += v;
01197                 s->mant2_cnt = 0;
01198                 v = 128;
01199                 break;
01200             }
01201             break;
01202         case 3:
01203             v = sym_quant(c, e, 7);
01204             break;
01205         case 4:
01206             v = sym_quant(c, e, 11);
01207             switch (s->mant4_cnt) {
01208             case 0:
01209                 s->qmant4_ptr = &qmant[i];
01210                 v = 11 * v;
01211                 s->mant4_cnt = 1;
01212                 break;
01213             default:
01214                 *s->qmant4_ptr += v;
01215                 s->mant4_cnt = 0;
01216                 v = 128;
01217                 break;
01218             }
01219             break;
01220         case 5:
01221             v = sym_quant(c, e, 15);
01222             break;
01223         case 14:
01224             v = asym_quant(c, e, 14);
01225             break;
01226         case 15:
01227             v = asym_quant(c, e, 16);
01228             break;
01229         default:
01230             v = asym_quant(c, e, b - 1);
01231             break;
01232         }
01233         qmant[i] = v;
01234     }
01235 }
01236 
01237 
01241 static void quantize_mantissas(AC3EncodeContext *s)
01242 {
01243     int blk, ch, ch0=0, got_cpl;
01244 
01245     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
01246         AC3Block *block = &s->blocks[blk];
01247         AC3Mant m = { 0 };
01248 
01249         got_cpl = !block->cpl_in_use;
01250         for (ch = 1; ch <= s->channels; ch++) {
01251             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
01252                 ch0     = ch - 1;
01253                 ch      = CPL_CH;
01254                 got_cpl = 1;
01255             }
01256             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
01257                                       s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
01258                                       s->ref_bap[ch][blk], block->qmant[ch],
01259                                       s->start_freq[ch], block->end_freq[ch]);
01260             if (ch == CPL_CH)
01261                 ch = ch0;
01262         }
01263     }
01264 }
01265 
01266 
01270 static void ac3_output_frame_header(AC3EncodeContext *s)
01271 {
01272     AC3EncOptions *opt = &s->options;
01273 
01274     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
01275     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
01276     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
01277     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
01278     put_bits(&s->pb, 5,  s->bitstream_id);
01279     put_bits(&s->pb, 3,  s->bitstream_mode);
01280     put_bits(&s->pb, 3,  s->channel_mode);
01281     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
01282         put_bits(&s->pb, 2, s->center_mix_level);
01283     if (s->channel_mode & 0x04)
01284         put_bits(&s->pb, 2, s->surround_mix_level);
01285     if (s->channel_mode == AC3_CHMODE_STEREO)
01286         put_bits(&s->pb, 2, opt->dolby_surround_mode);
01287     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
01288     put_bits(&s->pb, 5, -opt->dialogue_level);
01289     put_bits(&s->pb, 1, 0);         /* no compression control word */
01290     put_bits(&s->pb, 1, 0);         /* no lang code */
01291     put_bits(&s->pb, 1, opt->audio_production_info);
01292     if (opt->audio_production_info) {
01293         put_bits(&s->pb, 5, opt->mixing_level - 80);
01294         put_bits(&s->pb, 2, opt->room_type);
01295     }
01296     put_bits(&s->pb, 1, opt->copyright);
01297     put_bits(&s->pb, 1, opt->original);
01298     if (s->bitstream_id == 6) {
01299         /* alternate bit stream syntax */
01300         put_bits(&s->pb, 1, opt->extended_bsi_1);
01301         if (opt->extended_bsi_1) {
01302             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
01303             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
01304             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
01305             put_bits(&s->pb, 3, s->loro_center_mix_level);
01306             put_bits(&s->pb, 3, s->loro_surround_mix_level);
01307         }
01308         put_bits(&s->pb, 1, opt->extended_bsi_2);
01309         if (opt->extended_bsi_2) {
01310             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
01311             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
01312             put_bits(&s->pb, 1, opt->ad_converter_type);
01313             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
01314         }
01315     } else {
01316     put_bits(&s->pb, 1, 0);         /* no time code 1 */
01317     put_bits(&s->pb, 1, 0);         /* no time code 2 */
01318     }
01319     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
01320 }
01321 
01322 
01326 static void output_audio_block(AC3EncodeContext *s, int blk)
01327 {
01328     int ch, i, baie, bnd, got_cpl;
01329     int av_uninit(ch0);
01330     AC3Block *block = &s->blocks[blk];
01331 
01332     /* block switching */
01333     if (!s->eac3) {
01334         for (ch = 0; ch < s->fbw_channels; ch++)
01335             put_bits(&s->pb, 1, 0);
01336     }
01337 
01338     /* dither flags */
01339     if (!s->eac3) {
01340         for (ch = 0; ch < s->fbw_channels; ch++)
01341             put_bits(&s->pb, 1, 1);
01342     }
01343 
01344     /* dynamic range codes */
01345     put_bits(&s->pb, 1, 0);
01346 
01347     /* spectral extension */
01348     if (s->eac3)
01349         put_bits(&s->pb, 1, 0);
01350 
01351     /* channel coupling */
01352     if (!s->eac3)
01353         put_bits(&s->pb, 1, block->new_cpl_strategy);
01354     if (block->new_cpl_strategy) {
01355         if (!s->eac3)
01356             put_bits(&s->pb, 1, block->cpl_in_use);
01357         if (block->cpl_in_use) {
01358             int start_sub, end_sub;
01359             if (s->eac3)
01360                 put_bits(&s->pb, 1, 0); /* enhanced coupling */
01361             if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
01362                 for (ch = 1; ch <= s->fbw_channels; ch++)
01363                     put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
01364             }
01365             if (s->channel_mode == AC3_CHMODE_STEREO)
01366                 put_bits(&s->pb, 1, 0); /* phase flags in use */
01367             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
01368             end_sub   = (s->cpl_end_freq       - 37) / 12;
01369             put_bits(&s->pb, 4, start_sub);
01370             put_bits(&s->pb, 4, end_sub - 3);
01371             /* coupling band structure */
01372             if (s->eac3) {
01373                 put_bits(&s->pb, 1, 0); /* use default */
01374             } else {
01375                 for (bnd = start_sub+1; bnd < end_sub; bnd++)
01376                     put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
01377             }
01378         }
01379     }
01380 
01381     /* coupling coordinates */
01382     if (block->cpl_in_use) {
01383         for (ch = 1; ch <= s->fbw_channels; ch++) {
01384             if (block->channel_in_cpl[ch]) {
01385                 if (!s->eac3 || block->new_cpl_coords != 2)
01386                     put_bits(&s->pb, 1, block->new_cpl_coords);
01387                 if (block->new_cpl_coords) {
01388                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
01389                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
01390                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
01391                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
01392                     }
01393                 }
01394             }
01395         }
01396     }
01397 
01398     /* stereo rematrixing */
01399     if (s->channel_mode == AC3_CHMODE_STEREO) {
01400         if (!s->eac3 || blk > 0)
01401             put_bits(&s->pb, 1, block->new_rematrixing_strategy);
01402         if (block->new_rematrixing_strategy) {
01403             /* rematrixing flags */
01404             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
01405                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
01406         }
01407     }
01408 
01409     /* exponent strategy */
01410     if (!s->eac3) {
01411         for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
01412             put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
01413         if (s->lfe_on)
01414             put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
01415     }
01416 
01417     /* bandwidth */
01418     for (ch = 1; ch <= s->fbw_channels; ch++) {
01419         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
01420             put_bits(&s->pb, 6, s->bandwidth_code);
01421     }
01422 
01423     /* exponents */
01424     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
01425         int nb_groups;
01426         int cpl = (ch == CPL_CH);
01427 
01428         if (s->exp_strategy[ch][blk] == EXP_REUSE)
01429             continue;
01430 
01431         /* DC exponent */
01432         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
01433 
01434         /* exponent groups */
01435         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
01436         for (i = 1; i <= nb_groups; i++)
01437             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
01438 
01439         /* gain range info */
01440         if (ch != s->lfe_channel && !cpl)
01441             put_bits(&s->pb, 2, 0);
01442     }
01443 
01444     /* bit allocation info */
01445     if (!s->eac3) {
01446         baie = (blk == 0);
01447         put_bits(&s->pb, 1, baie);
01448         if (baie) {
01449             put_bits(&s->pb, 2, s->slow_decay_code);
01450             put_bits(&s->pb, 2, s->fast_decay_code);
01451             put_bits(&s->pb, 2, s->slow_gain_code);
01452             put_bits(&s->pb, 2, s->db_per_bit_code);
01453             put_bits(&s->pb, 3, s->floor_code);
01454         }
01455     }
01456 
01457     /* snr offset */
01458     if (!s->eac3) {
01459         put_bits(&s->pb, 1, block->new_snr_offsets);
01460         if (block->new_snr_offsets) {
01461             put_bits(&s->pb, 6, s->coarse_snr_offset);
01462             for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
01463                 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
01464                 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
01465             }
01466         }
01467     } else {
01468         put_bits(&s->pb, 1, 0); /* no converter snr offset */
01469     }
01470 
01471     /* coupling leak */
01472     if (block->cpl_in_use) {
01473         if (!s->eac3 || block->new_cpl_leak != 2)
01474             put_bits(&s->pb, 1, block->new_cpl_leak);
01475         if (block->new_cpl_leak) {
01476             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
01477             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
01478         }
01479     }
01480 
01481     if (!s->eac3) {
01482         put_bits(&s->pb, 1, 0); /* no delta bit allocation */
01483         put_bits(&s->pb, 1, 0); /* no data to skip */
01484     }
01485 
01486     /* mantissas */
01487     got_cpl = !block->cpl_in_use;
01488     for (ch = 1; ch <= s->channels; ch++) {
01489         int b, q;
01490 
01491         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
01492             ch0     = ch - 1;
01493             ch      = CPL_CH;
01494             got_cpl = 1;
01495         }
01496         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
01497             q = block->qmant[ch][i];
01498             b = s->ref_bap[ch][blk][i];
01499             switch (b) {
01500             case 0:                                         break;
01501             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
01502             case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
01503             case 3:               put_bits(&s->pb,   3, q); break;
01504             case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
01505             case 14:              put_bits(&s->pb,  14, q); break;
01506             case 15:              put_bits(&s->pb,  16, q); break;
01507             default:              put_bits(&s->pb, b-1, q); break;
01508             }
01509         }
01510         if (ch == CPL_CH)
01511             ch = ch0;
01512     }
01513 }
01514 
01515 
01517 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
01518 
01519 
01520 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
01521 {
01522     unsigned int c;
01523 
01524     c = 0;
01525     while (a) {
01526         if (a & 1)
01527             c ^= b;
01528         a = a >> 1;
01529         b = b << 1;
01530         if (b & (1 << 16))
01531             b ^= poly;
01532     }
01533     return c;
01534 }
01535 
01536 
01537 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
01538 {
01539     unsigned int r;
01540     r = 1;
01541     while (n) {
01542         if (n & 1)
01543             r = mul_poly(r, a, poly);
01544         a = mul_poly(a, a, poly);
01545         n >>= 1;
01546     }
01547     return r;
01548 }
01549 
01550 
01554 static void output_frame_end(AC3EncodeContext *s)
01555 {
01556     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
01557     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
01558     uint8_t *frame;
01559 
01560     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
01561 
01562     /* pad the remainder of the frame with zeros */
01563     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
01564     flush_put_bits(&s->pb);
01565     frame = s->pb.buf;
01566     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
01567     av_assert2(pad_bytes >= 0);
01568     if (pad_bytes > 0)
01569         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
01570 
01571     if (s->eac3) {
01572         /* compute crc2 */
01573         crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
01574     } else {
01575     /* compute crc1 */
01576     /* this is not so easy because it is at the beginning of the data... */
01577     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
01578     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
01579     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
01580     AV_WB16(frame + 2, crc1);
01581 
01582     /* compute crc2 */
01583     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
01584                           s->frame_size - frame_size_58 - 3);
01585     }
01586     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
01587     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
01588     if (crc2 == 0x770B) {
01589         frame[s->frame_size - 3] ^= 0x1;
01590         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
01591     }
01592     crc2 = av_bswap16(crc2);
01593     AV_WB16(frame + s->frame_size - 2, crc2);
01594 }
01595 
01596 
01600 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
01601 {
01602     int blk;
01603 
01604     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
01605 
01606     s->output_frame_header(s);
01607 
01608     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
01609         output_audio_block(s, blk);
01610 
01611     output_frame_end(s);
01612 }
01613 
01614 
01615 static void dprint_options(AVCodecContext *avctx)
01616 {
01617 #ifdef DEBUG
01618     AC3EncodeContext *s = avctx->priv_data;
01619     AC3EncOptions *opt = &s->options;
01620     char strbuf[32];
01621 
01622     switch (s->bitstream_id) {
01623     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
01624     case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
01625     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
01626     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
01627     case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
01628     default: snprintf(strbuf, 32, "ERROR");
01629     }
01630     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
01631     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
01632     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
01633     av_dlog(avctx, "channel_layout: %s\n", strbuf);
01634     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
01635     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
01636     if (s->cutoff)
01637         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
01638 
01639     av_dlog(avctx, "per_frame_metadata: %s\n",
01640             opt->allow_per_frame_metadata?"on":"off");
01641     if (s->has_center)
01642         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
01643                 s->center_mix_level);
01644     else
01645         av_dlog(avctx, "center_mixlev: {not written}\n");
01646     if (s->has_surround)
01647         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
01648                 s->surround_mix_level);
01649     else
01650         av_dlog(avctx, "surround_mixlev: {not written}\n");
01651     if (opt->audio_production_info) {
01652         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
01653         switch (opt->room_type) {
01654         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
01655         case 1:  av_strlcpy(strbuf, "large", 32);        break;
01656         case 2:  av_strlcpy(strbuf, "small", 32);        break;
01657         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
01658         }
01659         av_dlog(avctx, "room_type: %s\n", strbuf);
01660     } else {
01661         av_dlog(avctx, "mixing_level: {not written}\n");
01662         av_dlog(avctx, "room_type: {not written}\n");
01663     }
01664     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
01665     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
01666     if (s->channel_mode == AC3_CHMODE_STEREO) {
01667         switch (opt->dolby_surround_mode) {
01668         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
01669         case 1:  av_strlcpy(strbuf, "on", 32);           break;
01670         case 2:  av_strlcpy(strbuf, "off", 32);          break;
01671         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
01672         }
01673         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
01674     } else {
01675         av_dlog(avctx, "dsur_mode: {not written}\n");
01676     }
01677     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
01678 
01679     if (s->bitstream_id == 6) {
01680         if (opt->extended_bsi_1) {
01681             switch (opt->preferred_stereo_downmix) {
01682             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
01683             case 1:  av_strlcpy(strbuf, "ltrt", 32);         break;
01684             case 2:  av_strlcpy(strbuf, "loro", 32);         break;
01685             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
01686             }
01687             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
01688             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
01689                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
01690             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
01691                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
01692             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
01693                     opt->loro_center_mix_level, s->loro_center_mix_level);
01694             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
01695                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
01696         } else {
01697             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
01698         }
01699         if (opt->extended_bsi_2) {
01700             switch (opt->dolby_surround_ex_mode) {
01701             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
01702             case 1:  av_strlcpy(strbuf, "on", 32);           break;
01703             case 2:  av_strlcpy(strbuf, "off", 32);          break;
01704             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
01705             }
01706             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
01707             switch (opt->dolby_headphone_mode) {
01708             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
01709             case 1:  av_strlcpy(strbuf, "on", 32);           break;
01710             case 2:  av_strlcpy(strbuf, "off", 32);          break;
01711             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
01712             }
01713             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
01714 
01715             switch (opt->ad_converter_type) {
01716             case 0:  av_strlcpy(strbuf, "standard", 32); break;
01717             case 1:  av_strlcpy(strbuf, "hdcd", 32);     break;
01718             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
01719             }
01720             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
01721         } else {
01722             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
01723         }
01724     }
01725 #endif
01726 }
01727 
01728 
01729 #define FLT_OPTION_THRESHOLD 0.01
01730 
01731 static int validate_float_option(float v, const float *v_list, int v_list_size)
01732 {
01733     int i;
01734 
01735     for (i = 0; i < v_list_size; i++) {
01736         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
01737             v > (v_list[i] - FLT_OPTION_THRESHOLD))
01738             break;
01739     }
01740     if (i == v_list_size)
01741         return -1;
01742 
01743     return i;
01744 }
01745 
01746 
01747 static void validate_mix_level(void *log_ctx, const char *opt_name,
01748                                float *opt_param, const float *list,
01749                                int list_size, int default_value, int min_value,
01750                                int *ctx_param)
01751 {
01752     int mixlev = validate_float_option(*opt_param, list, list_size);
01753     if (mixlev < min_value) {
01754         mixlev = default_value;
01755         if (*opt_param >= 0.0) {
01756             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
01757                    "default value: %0.3f\n", opt_name, list[mixlev]);
01758         }
01759     }
01760     *opt_param = list[mixlev];
01761     *ctx_param = mixlev;
01762 }
01763 
01764 
01769 static int validate_metadata(AVCodecContext *avctx)
01770 {
01771     AC3EncodeContext *s = avctx->priv_data;
01772     AC3EncOptions *opt = &s->options;
01773 
01774     /* validate mixing levels */
01775     if (s->has_center) {
01776         validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
01777                            cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
01778                            &s->center_mix_level);
01779     }
01780     if (s->has_surround) {
01781         validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
01782                            surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
01783                            &s->surround_mix_level);
01784     }
01785 
01786     /* set audio production info flag */
01787     if (opt->mixing_level >= 0 || opt->room_type >= 0) {
01788         if (opt->mixing_level < 0) {
01789             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
01790                    "room_type is set\n");
01791             return AVERROR(EINVAL);
01792         }
01793         if (opt->mixing_level < 80) {
01794             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
01795                    "80dB and 111dB\n");
01796             return AVERROR(EINVAL);
01797         }
01798         /* default room type */
01799         if (opt->room_type < 0)
01800             opt->room_type = 0;
01801         opt->audio_production_info = 1;
01802     } else {
01803         opt->audio_production_info = 0;
01804     }
01805 
01806     /* set extended bsi 1 flag */
01807     if ((s->has_center || s->has_surround) &&
01808         (opt->preferred_stereo_downmix >= 0 ||
01809          opt->ltrt_center_mix_level   >= 0 ||
01810          opt->ltrt_surround_mix_level >= 0 ||
01811          opt->loro_center_mix_level   >= 0 ||
01812          opt->loro_surround_mix_level >= 0)) {
01813         /* default preferred stereo downmix */
01814         if (opt->preferred_stereo_downmix < 0)
01815             opt->preferred_stereo_downmix = 0;
01816         /* validate Lt/Rt center mix level */
01817         validate_mix_level(avctx, "ltrt_center_mix_level",
01818                            &opt->ltrt_center_mix_level, extmixlev_options,
01819                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
01820                            &s->ltrt_center_mix_level);
01821         /* validate Lt/Rt surround mix level */
01822         validate_mix_level(avctx, "ltrt_surround_mix_level",
01823                            &opt->ltrt_surround_mix_level, extmixlev_options,
01824                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
01825                            &s->ltrt_surround_mix_level);
01826         /* validate Lo/Ro center mix level */
01827         validate_mix_level(avctx, "loro_center_mix_level",
01828                            &opt->loro_center_mix_level, extmixlev_options,
01829                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
01830                            &s->loro_center_mix_level);
01831         /* validate Lo/Ro surround mix level */
01832         validate_mix_level(avctx, "loro_surround_mix_level",
01833                            &opt->loro_surround_mix_level, extmixlev_options,
01834                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
01835                            &s->loro_surround_mix_level);
01836         opt->extended_bsi_1 = 1;
01837     } else {
01838         opt->extended_bsi_1 = 0;
01839     }
01840 
01841     /* set extended bsi 2 flag */
01842     if (opt->dolby_surround_ex_mode >= 0 ||
01843         opt->dolby_headphone_mode   >= 0 ||
01844         opt->ad_converter_type      >= 0) {
01845         /* default dolby surround ex mode */
01846         if (opt->dolby_surround_ex_mode < 0)
01847             opt->dolby_surround_ex_mode = 0;
01848         /* default dolby headphone mode */
01849         if (opt->dolby_headphone_mode < 0)
01850             opt->dolby_headphone_mode = 0;
01851         /* default A/D converter type */
01852         if (opt->ad_converter_type < 0)
01853             opt->ad_converter_type = 0;
01854         opt->extended_bsi_2 = 1;
01855     } else {
01856         opt->extended_bsi_2 = 0;
01857     }
01858 
01859     /* set bitstream id for alternate bitstream syntax */
01860     if (opt->extended_bsi_1 || opt->extended_bsi_2) {
01861         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
01862             static int warn_once = 1;
01863             if (warn_once) {
01864                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
01865                        "not compatible with reduced samplerates. writing of "
01866                        "extended bitstream information will be disabled.\n");
01867                 warn_once = 0;
01868             }
01869         } else {
01870             s->bitstream_id = 6;
01871         }
01872     }
01873 
01874     return 0;
01875 }
01876 
01877 
01881 int ff_ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
01882                         int buf_size, void *data)
01883 {
01884     AC3EncodeContext *s = avctx->priv_data;
01885     const SampleType *samples = data;
01886     int ret;
01887 
01888     if (!s->eac3 && s->options.allow_per_frame_metadata) {
01889         ret = validate_metadata(avctx);
01890         if (ret)
01891             return ret;
01892     }
01893 
01894     if (s->bit_alloc.sr_code == 1 || s->eac3)
01895         adjust_frame_size(s);
01896 
01897     s->deinterleave_input_samples(s, samples);
01898 
01899     s->apply_mdct(s);
01900 
01901     s->scale_coefficients(s);
01902 
01903     s->cpl_on = s->cpl_enabled;
01904     compute_coupling_strategy(s);
01905 
01906     if (s->cpl_on)
01907         s->apply_channel_coupling(s);
01908 
01909     s->compute_rematrixing_strategy(s);
01910 
01911     apply_rematrixing(s);
01912 
01913     process_exponents(s);
01914 
01915     ret = compute_bit_allocation(s);
01916     if (ret) {
01917         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
01918         return ret;
01919     }
01920 
01921     quantize_mantissas(s);
01922 
01923     output_frame(s, frame);
01924 
01925     return s->frame_size;
01926 }
01927 
01928 
01932 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
01933 {
01934     int blk, ch;
01935     AC3EncodeContext *s = avctx->priv_data;
01936 
01937     av_freep(&s->windowed_samples);
01938     for (ch = 0; ch < s->channels; ch++)
01939         av_freep(&s->planar_samples[ch]);
01940     av_freep(&s->planar_samples);
01941     av_freep(&s->bap_buffer);
01942     av_freep(&s->bap1_buffer);
01943     av_freep(&s->mdct_coef_buffer);
01944     av_freep(&s->fixed_coef_buffer);
01945     av_freep(&s->exp_buffer);
01946     av_freep(&s->grouped_exp_buffer);
01947     av_freep(&s->psd_buffer);
01948     av_freep(&s->band_psd_buffer);
01949     av_freep(&s->mask_buffer);
01950     av_freep(&s->qmant_buffer);
01951     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
01952         AC3Block *block = &s->blocks[blk];
01953         av_freep(&block->mdct_coef);
01954         av_freep(&block->fixed_coef);
01955         av_freep(&block->exp);
01956         av_freep(&block->grouped_exp);
01957         av_freep(&block->psd);
01958         av_freep(&block->band_psd);
01959         av_freep(&block->mask);
01960         av_freep(&block->qmant);
01961     }
01962 
01963     s->mdct_end(s->mdct);
01964     av_freep(&s->mdct);
01965 
01966     av_freep(&avctx->coded_frame);
01967     return 0;
01968 }
01969 
01970 
01974 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
01975                                     int64_t *channel_layout)
01976 {
01977     int ch_layout;
01978 
01979     if (channels < 1 || channels > AC3_MAX_CHANNELS)
01980         return AVERROR(EINVAL);
01981     if ((uint64_t)*channel_layout > 0x7FF)
01982         return AVERROR(EINVAL);
01983     ch_layout = *channel_layout;
01984     if (!ch_layout)
01985         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
01986 
01987     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
01988     s->channels     = channels;
01989     s->fbw_channels = channels - s->lfe_on;
01990     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
01991     if (s->lfe_on)
01992         ch_layout -= AV_CH_LOW_FREQUENCY;
01993 
01994     switch (ch_layout) {
01995     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
01996     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
01997     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
01998     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
01999     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
02000     case AV_CH_LAYOUT_QUAD:
02001     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
02002     case AV_CH_LAYOUT_5POINT0:
02003     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
02004     default:
02005         return AVERROR(EINVAL);
02006     }
02007     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
02008     s->has_surround =  s->channel_mode & 0x04;
02009 
02010     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
02011     *channel_layout = ch_layout;
02012     if (s->lfe_on)
02013         *channel_layout |= AV_CH_LOW_FREQUENCY;
02014 
02015     return 0;
02016 }
02017 
02018 
02019 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
02020 {
02021     int i, ret, max_sr;
02022 
02023     /* validate channel layout */
02024     if (!avctx->channel_layout) {
02025         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
02026                                       "encoder will guess the layout, but it "
02027                                       "might be incorrect.\n");
02028     }
02029     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
02030     if (ret) {
02031         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
02032         return ret;
02033     }
02034 
02035     /* validate sample rate */
02036     /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
02037              decoder that supports half sample rate so we can validate that
02038              the generated files are correct. */
02039     max_sr = s->eac3 ? 2 : 8;
02040     for (i = 0; i <= max_sr; i++) {
02041         if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
02042             break;
02043     }
02044     if (i > max_sr) {
02045         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
02046         return AVERROR(EINVAL);
02047     }
02048     s->sample_rate        = avctx->sample_rate;
02049     s->bit_alloc.sr_shift = i / 3;
02050     s->bit_alloc.sr_code  = i % 3;
02051     s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
02052 
02053     /* validate bit rate */
02054     if (s->eac3) {
02055         int max_br, min_br, wpf, min_br_dist, min_br_code;
02056 
02057         /* calculate min/max bitrate */
02058         max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
02059         min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
02060         if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
02061             av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
02062                    "for this sample rate\n", min_br, max_br);
02063             return AVERROR(EINVAL);
02064         }
02065 
02066         /* calculate words-per-frame for the selected bitrate */
02067         wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
02068         av_assert1(wpf > 0 && wpf <= 2048);
02069 
02070         /* find the closest AC-3 bitrate code to the selected bitrate.
02071            this is needed for lookup tables for bandwidth and coupling
02072            parameter selection */
02073         min_br_code = -1;
02074         min_br_dist = INT_MAX;
02075         for (i = 0; i < 19; i++) {
02076             int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
02077             if (br_dist < min_br_dist) {
02078                 min_br_dist = br_dist;
02079                 min_br_code = i;
02080             }
02081         }
02082 
02083         /* make sure the minimum frame size is below the average frame size */
02084         s->frame_size_code = min_br_code << 1;
02085         while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
02086             wpf--;
02087         s->frame_size_min = 2 * wpf;
02088     } else {
02089         for (i = 0; i < 19; i++) {
02090             if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
02091                 break;
02092         }
02093         if (i == 19) {
02094             av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
02095             return AVERROR(EINVAL);
02096         }
02097         s->frame_size_code = i << 1;
02098         s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
02099     }
02100     s->bit_rate   = avctx->bit_rate;
02101     s->frame_size = s->frame_size_min;
02102 
02103     /* validate cutoff */
02104     if (avctx->cutoff < 0) {
02105         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
02106         return AVERROR(EINVAL);
02107     }
02108     s->cutoff = avctx->cutoff;
02109     if (s->cutoff > (s->sample_rate >> 1))
02110         s->cutoff = s->sample_rate >> 1;
02111 
02112     /* validate audio service type / channels combination */
02113     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
02114          avctx->channels == 1) ||
02115         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
02116           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
02117           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
02118          && avctx->channels > 1)) {
02119         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
02120                                     "specified number of channels\n");
02121         return AVERROR(EINVAL);
02122     }
02123 
02124     if (!s->eac3) {
02125         ret = validate_metadata(avctx);
02126         if (ret)
02127             return ret;
02128     }
02129 
02130     s->rematrixing_enabled = s->options.stereo_rematrixing &&
02131                              (s->channel_mode == AC3_CHMODE_STEREO);
02132 
02133     s->cpl_enabled = s->options.channel_coupling &&
02134                      s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
02135 
02136     return 0;
02137 }
02138 
02139 
02145 static av_cold void set_bandwidth(AC3EncodeContext *s)
02146 {
02147     int blk, ch;
02148     int av_uninit(cpl_start);
02149 
02150     if (s->cutoff) {
02151         /* calculate bandwidth based on user-specified cutoff frequency */
02152         int fbw_coeffs;
02153         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
02154         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
02155     } else {
02156         /* use default bandwidth setting */
02157         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
02158     }
02159 
02160     /* set number of coefficients for each channel */
02161     for (ch = 1; ch <= s->fbw_channels; ch++) {
02162         s->start_freq[ch] = 0;
02163         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
02164             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
02165     }
02166     /* LFE channel always has 7 coefs */
02167     if (s->lfe_on) {
02168         s->start_freq[s->lfe_channel] = 0;
02169         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
02170             s->blocks[blk].end_freq[ch] = 7;
02171     }
02172 
02173     /* initialize coupling strategy */
02174     if (s->cpl_enabled) {
02175         if (s->options.cpl_start >= 0) {
02176             cpl_start = s->options.cpl_start;
02177         } else {
02178             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
02179             if (cpl_start < 0)
02180                 s->cpl_enabled = 0;
02181         }
02182     }
02183     if (s->cpl_enabled) {
02184         int i, cpl_start_band, cpl_end_band;
02185         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
02186 
02187         cpl_end_band   = s->bandwidth_code / 4 + 3;
02188         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
02189 
02190         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
02191 
02192         s->num_cpl_bands = 1;
02193         *cpl_band_sizes  = 12;
02194         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
02195             if (ff_eac3_default_cpl_band_struct[i]) {
02196                 *cpl_band_sizes += 12;
02197             } else {
02198                 s->num_cpl_bands++;
02199                 cpl_band_sizes++;
02200                 *cpl_band_sizes = 12;
02201             }
02202         }
02203 
02204         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
02205         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
02206         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
02207             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
02208     }
02209 }
02210 
02211 
02212 static av_cold int allocate_buffers(AVCodecContext *avctx)
02213 {
02214     int blk, ch;
02215     AC3EncodeContext *s = avctx->priv_data;
02216     int channels = s->channels + 1; /* includes coupling channel */
02217 
02218     if (s->allocate_sample_buffers(s))
02219         goto alloc_fail;
02220 
02221     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * channels *
02222                      AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
02223     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
02224                      AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
02225     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
02226                       AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
02227     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
02228                      AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
02229     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
02230                      128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
02231     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
02232                      AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
02233     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
02234                      64 * sizeof(*s->band_psd_buffer), alloc_fail);
02235     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
02236                      64 * sizeof(*s->mask_buffer), alloc_fail);
02237     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
02238                      AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
02239     if (s->cpl_enabled) {
02240         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
02241                          16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
02242         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
02243                          16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
02244     }
02245     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
02246         AC3Block *block = &s->blocks[blk];
02247         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
02248                           alloc_fail);
02249         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
02250                           alloc_fail);
02251         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
02252                           alloc_fail);
02253         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
02254                           alloc_fail);
02255         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
02256                           alloc_fail);
02257         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
02258                           alloc_fail);
02259         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
02260                           alloc_fail);
02261         if (s->cpl_enabled) {
02262             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
02263                               alloc_fail);
02264             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
02265                               alloc_fail);
02266         }
02267 
02268         for (ch = 0; ch < channels; ch++) {
02269             /* arrangement: block, channel, coeff */
02270             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
02271             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
02272             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
02273             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
02274             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
02275             if (s->cpl_enabled) {
02276                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
02277                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
02278             }
02279 
02280             /* arrangement: channel, block, coeff */
02281             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
02282             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
02283         }
02284     }
02285 
02286     if (!s->fixed_point) {
02287         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
02288                           AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
02289         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
02290             AC3Block *block = &s->blocks[blk];
02291             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
02292                               sizeof(*block->fixed_coef), alloc_fail);
02293             for (ch = 0; ch < channels; ch++)
02294                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
02295         }
02296     } else {
02297         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
02298             AC3Block *block = &s->blocks[blk];
02299             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
02300                               sizeof(*block->fixed_coef), alloc_fail);
02301             for (ch = 0; ch < channels; ch++)
02302                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
02303         }
02304     }
02305 
02306     return 0;
02307 alloc_fail:
02308     return AVERROR(ENOMEM);
02309 }
02310 
02311 
02315 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
02316 {
02317     AC3EncodeContext *s = avctx->priv_data;
02318     int ret, frame_size_58;
02319 
02320     s->avctx = avctx;
02321 
02322     s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
02323 
02324     avctx->frame_size = AC3_FRAME_SIZE;
02325 
02326     ff_ac3_common_init();
02327 
02328     ret = validate_options(avctx, s);
02329     if (ret)
02330         return ret;
02331 
02332     s->bitstream_mode = avctx->audio_service_type;
02333     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
02334         s->bitstream_mode = 0x7;
02335 
02336     s->bits_written    = 0;
02337     s->samples_written = 0;
02338 
02339     /* calculate crc_inv for both possible frame sizes */
02340     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
02341     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
02342     if (s->bit_alloc.sr_code == 1) {
02343         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
02344         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
02345     }
02346 
02347     /* set function pointers */
02348     if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
02349         s->mdct_end                     = ff_ac3_fixed_mdct_end;
02350         s->mdct_init                    = ff_ac3_fixed_mdct_init;
02351         s->apply_window                 = ff_ac3_fixed_apply_window;
02352         s->normalize_samples            = ff_ac3_fixed_normalize_samples;
02353         s->scale_coefficients           = ff_ac3_fixed_scale_coefficients;
02354         s->allocate_sample_buffers      = ff_ac3_fixed_allocate_sample_buffers;
02355         s->deinterleave_input_samples   = ff_ac3_fixed_deinterleave_input_samples;
02356         s->apply_mdct                   = ff_ac3_fixed_apply_mdct;
02357         s->apply_channel_coupling       = ff_ac3_fixed_apply_channel_coupling;
02358         s->compute_rematrixing_strategy = ff_ac3_fixed_compute_rematrixing_strategy;
02359     } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
02360         s->mdct_end                     = ff_ac3_float_mdct_end;
02361         s->mdct_init                    = ff_ac3_float_mdct_init;
02362         s->apply_window                 = ff_ac3_float_apply_window;
02363         s->scale_coefficients           = ff_ac3_float_scale_coefficients;
02364         s->allocate_sample_buffers      = ff_ac3_float_allocate_sample_buffers;
02365         s->deinterleave_input_samples   = ff_ac3_float_deinterleave_input_samples;
02366         s->apply_mdct                   = ff_ac3_float_apply_mdct;
02367         s->apply_channel_coupling       = ff_ac3_float_apply_channel_coupling;
02368         s->compute_rematrixing_strategy = ff_ac3_float_compute_rematrixing_strategy;
02369     }
02370     if (CONFIG_EAC3_ENCODER && s->eac3)
02371         s->output_frame_header = ff_eac3_output_frame_header;
02372     else
02373         s->output_frame_header = ac3_output_frame_header;
02374 
02375     set_bandwidth(s);
02376 
02377     exponent_init(s);
02378 
02379     bit_alloc_init(s);
02380 
02381     FF_ALLOCZ_OR_GOTO(avctx, s->mdct, sizeof(AC3MDCTContext), init_fail);
02382     ret = s->mdct_init(avctx, s->mdct, 9);
02383     if (ret)
02384         goto init_fail;
02385 
02386     ret = allocate_buffers(avctx);
02387     if (ret)
02388         goto init_fail;
02389 
02390     avctx->coded_frame= avcodec_alloc_frame();
02391 
02392     dsputil_init(&s->dsp, avctx);
02393     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
02394 
02395     dprint_options(avctx);
02396 
02397     return 0;
02398 init_fail:
02399     ff_ac3_encode_close(avctx);
02400     return ret;
02401 }