• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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     int16_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 uint64_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 
00182 void ff_ac3_adjust_frame_size(AC3EncodeContext *s)
00183 {
00184     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
00185         s->bits_written    -= s->bit_rate;
00186         s->samples_written -= s->sample_rate;
00187     }
00188     s->frame_size = s->frame_size_min +
00189                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
00190     s->bits_written    += s->frame_size * 8;
00191     s->samples_written += AC3_BLOCK_SIZE * s->num_blocks;
00192 }
00193 
00194 
00200 void ff_ac3_compute_coupling_strategy(AC3EncodeContext *s)
00201 {
00202     int blk, ch;
00203     int got_cpl_snr;
00204     int num_cpl_blocks;
00205 
00206     /* set coupling use flags for each block/channel */
00207     /* TODO: turn coupling on/off and adjust start band based on bit usage */
00208     for (blk = 0; blk < s->num_blocks; blk++) {
00209         AC3Block *block = &s->blocks[blk];
00210         for (ch = 1; ch <= s->fbw_channels; ch++)
00211             block->channel_in_cpl[ch] = s->cpl_on;
00212     }
00213 
00214     /* enable coupling for each block if at least 2 channels have coupling
00215        enabled for that block */
00216     got_cpl_snr = 0;
00217     num_cpl_blocks = 0;
00218     for (blk = 0; blk < s->num_blocks; blk++) {
00219         AC3Block *block = &s->blocks[blk];
00220         block->num_cpl_channels = 0;
00221         for (ch = 1; ch <= s->fbw_channels; ch++)
00222             block->num_cpl_channels += block->channel_in_cpl[ch];
00223         block->cpl_in_use = block->num_cpl_channels > 1;
00224         num_cpl_blocks += block->cpl_in_use;
00225         if (!block->cpl_in_use) {
00226             block->num_cpl_channels = 0;
00227             for (ch = 1; ch <= s->fbw_channels; ch++)
00228                 block->channel_in_cpl[ch] = 0;
00229         }
00230 
00231         block->new_cpl_strategy = !blk;
00232         if (blk) {
00233             for (ch = 1; ch <= s->fbw_channels; ch++) {
00234                 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
00235                     block->new_cpl_strategy = 1;
00236                     break;
00237                 }
00238             }
00239         }
00240         block->new_cpl_leak = block->new_cpl_strategy;
00241 
00242         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
00243             block->new_snr_offsets = 1;
00244             if (block->cpl_in_use)
00245                 got_cpl_snr = 1;
00246         } else {
00247             block->new_snr_offsets = 0;
00248         }
00249     }
00250     if (!num_cpl_blocks)
00251         s->cpl_on = 0;
00252 
00253     /* set bandwidth for each channel */
00254     for (blk = 0; blk < s->num_blocks; blk++) {
00255         AC3Block *block = &s->blocks[blk];
00256         for (ch = 1; ch <= s->fbw_channels; ch++) {
00257             if (block->channel_in_cpl[ch])
00258                 block->end_freq[ch] = s->start_freq[CPL_CH];
00259             else
00260                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
00261         }
00262     }
00263 }
00264 
00265 
00271 void ff_ac3_apply_rematrixing(AC3EncodeContext *s)
00272 {
00273     int nb_coefs;
00274     int blk, bnd, i;
00275     int start, end;
00276     uint8_t *flags;
00277 
00278     if (!s->rematrixing_enabled)
00279         return;
00280 
00281     for (blk = 0; blk < s->num_blocks; blk++) {
00282         AC3Block *block = &s->blocks[blk];
00283         if (block->new_rematrixing_strategy)
00284             flags = block->rematrixing_flags;
00285         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
00286         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
00287             if (flags[bnd]) {
00288                 start = ff_ac3_rematrix_band_tab[bnd];
00289                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
00290                 for (i = start; i < end; i++) {
00291                     int32_t lt = block->fixed_coef[1][i];
00292                     int32_t rt = block->fixed_coef[2][i];
00293                     block->fixed_coef[1][i] = (lt + rt) >> 1;
00294                     block->fixed_coef[2][i] = (lt - rt) >> 1;
00295                 }
00296             }
00297         }
00298     }
00299 }
00300 
00301 
00302 /*
00303  * Initialize exponent tables.
00304  */
00305 static av_cold void exponent_init(AC3EncodeContext *s)
00306 {
00307     int expstr, i, grpsize;
00308 
00309     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
00310         grpsize = 3 << expstr;
00311         for (i = 12; i < 256; i++) {
00312             exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
00313             exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
00314         }
00315     }
00316     /* LFE */
00317     exponent_group_tab[0][0][7] = 2;
00318 
00319     if (CONFIG_EAC3_ENCODER && s->eac3)
00320         ff_eac3_exponent_init();
00321 }
00322 
00323 
00324 /*
00325  * Extract exponents from the MDCT coefficients.
00326  */
00327 static void extract_exponents(AC3EncodeContext *s)
00328 {
00329     int ch        = !s->cpl_on;
00330     int chan_size = AC3_MAX_COEFS * s->num_blocks * (s->channels - ch + 1);
00331     AC3Block *block = &s->blocks[0];
00332 
00333     s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
00334 }
00335 
00336 
00341 #define EXP_DIFF_THRESHOLD 500
00342 
00346 static const uint8_t exp_strategy_reuse_tab[4][6] = {
00347     { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
00348     { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
00349     { EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
00350     { EXP_D45, EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15 }
00351 };
00352 
00353 /*
00354  * Calculate exponent strategies for all channels.
00355  * Array arrangement is reversed to simplify the per-channel calculation.
00356  */
00357 static void compute_exp_strategy(AC3EncodeContext *s)
00358 {
00359     int ch, blk, blk1;
00360 
00361     for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
00362         uint8_t *exp_strategy = s->exp_strategy[ch];
00363         uint8_t *exp          = s->blocks[0].exp[ch];
00364         int exp_diff;
00365 
00366         /* estimate if the exponent variation & decide if they should be
00367            reused in the next frame */
00368         exp_strategy[0] = EXP_NEW;
00369         exp += AC3_MAX_COEFS;
00370         for (blk = 1; blk < s->num_blocks; blk++, exp += AC3_MAX_COEFS) {
00371             if (ch == CPL_CH) {
00372                 if (!s->blocks[blk-1].cpl_in_use) {
00373                     exp_strategy[blk] = EXP_NEW;
00374                     continue;
00375                 } else if (!s->blocks[blk].cpl_in_use) {
00376                     exp_strategy[blk] = EXP_REUSE;
00377                     continue;
00378                 }
00379             } else if (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
00380                 exp_strategy[blk] = EXP_NEW;
00381                 continue;
00382             }
00383             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
00384             exp_strategy[blk] = EXP_REUSE;
00385             if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
00386                 exp_strategy[blk] = EXP_NEW;
00387             else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
00388                 exp_strategy[blk] = EXP_NEW;
00389         }
00390 
00391         /* now select the encoding strategy type : if exponents are often
00392            recoded, we use a coarse encoding */
00393         blk = 0;
00394         while (blk < s->num_blocks) {
00395             blk1 = blk + 1;
00396             while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE)
00397                 blk1++;
00398             exp_strategy[blk] = exp_strategy_reuse_tab[s->num_blks_code][blk1-blk-1];
00399             blk = blk1;
00400         }
00401     }
00402     if (s->lfe_on) {
00403         ch = s->lfe_channel;
00404         s->exp_strategy[ch][0] = EXP_D15;
00405         for (blk = 1; blk < s->num_blocks; blk++)
00406             s->exp_strategy[ch][blk] = EXP_REUSE;
00407     }
00408 
00409     /* for E-AC-3, determine frame exponent strategy */
00410     if (CONFIG_EAC3_ENCODER && s->eac3)
00411         ff_eac3_get_frame_exp_strategy(s);
00412 }
00413 
00414 
00423 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
00424                                     int cpl)
00425 {
00426     int nb_groups, i, k;
00427 
00428     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
00429 
00430     /* for each group, compute the minimum exponent */
00431     switch(exp_strategy) {
00432     case EXP_D25:
00433         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
00434             uint8_t exp_min = exp[k];
00435             if (exp[k+1] < exp_min)
00436                 exp_min = exp[k+1];
00437             exp[i-cpl] = exp_min;
00438             k += 2;
00439         }
00440         break;
00441     case EXP_D45:
00442         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
00443             uint8_t exp_min = exp[k];
00444             if (exp[k+1] < exp_min)
00445                 exp_min = exp[k+1];
00446             if (exp[k+2] < exp_min)
00447                 exp_min = exp[k+2];
00448             if (exp[k+3] < exp_min)
00449                 exp_min = exp[k+3];
00450             exp[i-cpl] = exp_min;
00451             k += 4;
00452         }
00453         break;
00454     }
00455 
00456     /* constraint for DC exponent */
00457     if (!cpl && exp[0] > 15)
00458         exp[0] = 15;
00459 
00460     /* decrease the delta between each groups to within 2 so that they can be
00461        differentially encoded */
00462     for (i = 1; i <= nb_groups; i++)
00463         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
00464     i--;
00465     while (--i >= 0)
00466         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
00467 
00468     if (cpl)
00469         exp[-1] = exp[0] & ~1;
00470 
00471     /* now we have the exponent values the decoder will see */
00472     switch (exp_strategy) {
00473     case EXP_D25:
00474         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
00475             uint8_t exp1 = exp[i-cpl];
00476             exp[k--] = exp1;
00477             exp[k--] = exp1;
00478         }
00479         break;
00480     case EXP_D45:
00481         for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
00482             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
00483             k -= 4;
00484         }
00485         break;
00486     }
00487 }
00488 
00489 
00490 /*
00491  * Encode exponents from original extracted form to what the decoder will see.
00492  * This copies and groups exponents based on exponent strategy and reduces
00493  * deltas between adjacent exponent groups so that they can be differentially
00494  * encoded.
00495  */
00496 static void encode_exponents(AC3EncodeContext *s)
00497 {
00498     int blk, blk1, ch, cpl;
00499     uint8_t *exp, *exp_strategy;
00500     int nb_coefs, num_reuse_blocks;
00501 
00502     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
00503         exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
00504         exp_strategy = s->exp_strategy[ch];
00505 
00506         cpl = (ch == CPL_CH);
00507         blk = 0;
00508         while (blk < s->num_blocks) {
00509             AC3Block *block = &s->blocks[blk];
00510             if (cpl && !block->cpl_in_use) {
00511                 exp += AC3_MAX_COEFS;
00512                 blk++;
00513                 continue;
00514             }
00515             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
00516             blk1 = blk + 1;
00517 
00518             /* count the number of EXP_REUSE blocks after the current block
00519                and set exponent reference block numbers */
00520             s->exp_ref_block[ch][blk] = blk;
00521             while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE) {
00522                 s->exp_ref_block[ch][blk1] = blk;
00523                 blk1++;
00524             }
00525             num_reuse_blocks = blk1 - blk - 1;
00526 
00527             /* for the EXP_REUSE case we select the min of the exponents */
00528             s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
00529                                        AC3_MAX_COEFS);
00530 
00531             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
00532 
00533             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
00534             blk = blk1;
00535         }
00536     }
00537 
00538     /* reference block numbers have been changed, so reset ref_bap_set */
00539     s->ref_bap_set = 0;
00540 }
00541 
00542 
00543 /*
00544  * Count exponent bits based on bandwidth, coupling, and exponent strategies.
00545  */
00546 static int count_exponent_bits(AC3EncodeContext *s)
00547 {
00548     int blk, ch;
00549     int nb_groups, bit_count;
00550 
00551     bit_count = 0;
00552     for (blk = 0; blk < s->num_blocks; blk++) {
00553         AC3Block *block = &s->blocks[blk];
00554         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00555             int exp_strategy = s->exp_strategy[ch][blk];
00556             int cpl          = (ch == CPL_CH);
00557             int nb_coefs     = block->end_freq[ch] - s->start_freq[ch];
00558 
00559             if (exp_strategy == EXP_REUSE)
00560                 continue;
00561 
00562             nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_coefs];
00563             bit_count += 4 + (nb_groups * 7);
00564         }
00565     }
00566 
00567     return bit_count;
00568 }
00569 
00570 
00578 void ff_ac3_group_exponents(AC3EncodeContext *s)
00579 {
00580     int blk, ch, i, cpl;
00581     int group_size, nb_groups;
00582     uint8_t *p;
00583     int delta0, delta1, delta2;
00584     int exp0, exp1;
00585 
00586     for (blk = 0; blk < s->num_blocks; blk++) {
00587         AC3Block *block = &s->blocks[blk];
00588         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00589             int exp_strategy = s->exp_strategy[ch][blk];
00590             if (exp_strategy == EXP_REUSE)
00591                 continue;
00592             cpl = (ch == CPL_CH);
00593             group_size = exp_strategy + (exp_strategy == EXP_D45);
00594             nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
00595             p = block->exp[ch] + s->start_freq[ch] - cpl;
00596 
00597             /* DC exponent */
00598             exp1 = *p++;
00599             block->grouped_exp[ch][0] = exp1;
00600 
00601             /* remaining exponents are delta encoded */
00602             for (i = 1; i <= nb_groups; i++) {
00603                 /* merge three delta in one code */
00604                 exp0   = exp1;
00605                 exp1   = p[0];
00606                 p     += group_size;
00607                 delta0 = exp1 - exp0 + 2;
00608                 av_assert2(delta0 >= 0 && delta0 <= 4);
00609 
00610                 exp0   = exp1;
00611                 exp1   = p[0];
00612                 p     += group_size;
00613                 delta1 = exp1 - exp0 + 2;
00614                 av_assert2(delta1 >= 0 && delta1 <= 4);
00615 
00616                 exp0   = exp1;
00617                 exp1   = p[0];
00618                 p     += group_size;
00619                 delta2 = exp1 - exp0 + 2;
00620                 av_assert2(delta2 >= 0 && delta2 <= 4);
00621 
00622                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
00623             }
00624         }
00625     }
00626 }
00627 
00628 
00636 void ff_ac3_process_exponents(AC3EncodeContext *s)
00637 {
00638     extract_exponents(s);
00639 
00640     compute_exp_strategy(s);
00641 
00642     encode_exponents(s);
00643 
00644     emms_c();
00645 }
00646 
00647 
00648 /*
00649  * Count frame bits that are based solely on fixed parameters.
00650  * This only has to be run once when the encoder is initialized.
00651  */
00652 static void count_frame_bits_fixed(AC3EncodeContext *s)
00653 {
00654     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
00655     int blk;
00656     int frame_bits;
00657 
00658     /* assumptions:
00659      *   no dynamic range codes
00660      *   bit allocation parameters do not change between blocks
00661      *   no delta bit allocation
00662      *   no skipped data
00663      *   no auxilliary data
00664      *   no E-AC-3 metadata
00665      */
00666 
00667     /* header */
00668     frame_bits = 16; /* sync info */
00669     if (s->eac3) {
00670         /* bitstream info header */
00671         frame_bits += 35;
00672         frame_bits += 1 + 1;
00673         if (s->num_blocks != 0x6)
00674             frame_bits++;
00675         frame_bits++;
00676         /* audio frame header */
00677         if (s->num_blocks == 6)
00678             frame_bits += 2;
00679         frame_bits += 10;
00680         /* exponent strategy */
00681         if (s->use_frame_exp_strategy)
00682             frame_bits += 5 * s->fbw_channels;
00683         else
00684             frame_bits += s->num_blocks * 2 * s->fbw_channels;
00685         if (s->lfe_on)
00686             frame_bits += s->num_blocks;
00687         /* converter exponent strategy */
00688         if (s->num_blks_code != 0x3)
00689             frame_bits++;
00690         else
00691             frame_bits += s->fbw_channels * 5;
00692         /* snr offsets */
00693         frame_bits += 10;
00694         /* block start info */
00695         if (s->num_blocks != 1)
00696             frame_bits++;
00697     } else {
00698         frame_bits += 49;
00699         frame_bits += frame_bits_inc[s->channel_mode];
00700     }
00701 
00702     /* audio blocks */
00703     for (blk = 0; blk < s->num_blocks; blk++) {
00704         if (!s->eac3) {
00705             /* block switch flags */
00706             frame_bits += s->fbw_channels;
00707 
00708             /* dither flags */
00709             frame_bits += s->fbw_channels;
00710         }
00711 
00712         /* dynamic range */
00713         frame_bits++;
00714 
00715         /* spectral extension */
00716         if (s->eac3)
00717             frame_bits++;
00718 
00719         if (!s->eac3) {
00720             /* exponent strategy */
00721             frame_bits += 2 * s->fbw_channels;
00722             if (s->lfe_on)
00723                 frame_bits++;
00724 
00725             /* bit allocation params */
00726             frame_bits++;
00727             if (!blk)
00728                 frame_bits += 2 + 2 + 2 + 2 + 3;
00729         }
00730 
00731         /* converter snr offset */
00732         if (s->eac3)
00733             frame_bits++;
00734 
00735         if (!s->eac3) {
00736             /* delta bit allocation */
00737             frame_bits++;
00738 
00739             /* skipped data */
00740             frame_bits++;
00741         }
00742     }
00743 
00744     /* auxiliary data */
00745     frame_bits++;
00746 
00747     /* CRC */
00748     frame_bits += 1 + 16;
00749 
00750     s->frame_bits_fixed = frame_bits;
00751 }
00752 
00753 
00754 /*
00755  * Initialize bit allocation.
00756  * Set default parameter codes and calculate parameter values.
00757  */
00758 static void bit_alloc_init(AC3EncodeContext *s)
00759 {
00760     int ch;
00761 
00762     /* init default parameters */
00763     s->slow_decay_code = 2;
00764     s->fast_decay_code = 1;
00765     s->slow_gain_code  = 1;
00766     s->db_per_bit_code = s->eac3 ? 2 : 3;
00767     s->floor_code      = 7;
00768     for (ch = 0; ch <= s->channels; ch++)
00769         s->fast_gain_code[ch] = 4;
00770 
00771     /* initial snr offset */
00772     s->coarse_snr_offset = 40;
00773 
00774     /* compute real values */
00775     /* currently none of these values change during encoding, so we can just
00776        set them once at initialization */
00777     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
00778     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
00779     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
00780     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
00781     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
00782     s->bit_alloc.cpl_fast_leak = 0;
00783     s->bit_alloc.cpl_slow_leak = 0;
00784 
00785     count_frame_bits_fixed(s);
00786 }
00787 
00788 
00789 /*
00790  * Count the bits used to encode the frame, minus exponents and mantissas.
00791  * Bits based on fixed parameters have already been counted, so now we just
00792  * have to add the bits based on parameters that change during encoding.
00793  */
00794 static void count_frame_bits(AC3EncodeContext *s)
00795 {
00796     AC3EncOptions *opt = &s->options;
00797     int blk, ch;
00798     int frame_bits = 0;
00799 
00800     /* header */
00801     if (s->eac3) {
00802         if (opt->eac3_mixing_metadata) {
00803             if (s->channel_mode > AC3_CHMODE_STEREO)
00804                 frame_bits += 2;
00805             if (s->has_center)
00806                 frame_bits += 6;
00807             if (s->has_surround)
00808                 frame_bits += 6;
00809             frame_bits += s->lfe_on;
00810             frame_bits += 1 + 1 + 2;
00811             if (s->channel_mode < AC3_CHMODE_STEREO)
00812                 frame_bits++;
00813             frame_bits++;
00814         }
00815         if (opt->eac3_info_metadata) {
00816             frame_bits += 3 + 1 + 1;
00817             if (s->channel_mode == AC3_CHMODE_STEREO)
00818                 frame_bits += 2 + 2;
00819             if (s->channel_mode >= AC3_CHMODE_2F2R)
00820                 frame_bits += 2;
00821             frame_bits++;
00822             if (opt->audio_production_info)
00823                 frame_bits += 5 + 2 + 1;
00824             frame_bits++;
00825         }
00826         /* coupling */
00827         if (s->channel_mode > AC3_CHMODE_MONO) {
00828             frame_bits++;
00829             for (blk = 1; blk < s->num_blocks; blk++) {
00830                 AC3Block *block = &s->blocks[blk];
00831                 frame_bits++;
00832                 if (block->new_cpl_strategy)
00833                     frame_bits++;
00834             }
00835         }
00836         /* coupling exponent strategy */
00837         if (s->cpl_on) {
00838             if (s->use_frame_exp_strategy) {
00839                 frame_bits += 5 * s->cpl_on;
00840             } else {
00841                 for (blk = 0; blk < s->num_blocks; blk++)
00842                     frame_bits += 2 * s->blocks[blk].cpl_in_use;
00843             }
00844         }
00845     } else {
00846         if (opt->audio_production_info)
00847             frame_bits += 7;
00848         if (s->bitstream_id == 6) {
00849             if (opt->extended_bsi_1)
00850                 frame_bits += 14;
00851             if (opt->extended_bsi_2)
00852                 frame_bits += 14;
00853         }
00854     }
00855 
00856     /* audio blocks */
00857     for (blk = 0; blk < s->num_blocks; blk++) {
00858         AC3Block *block = &s->blocks[blk];
00859 
00860         /* coupling strategy */
00861         if (!s->eac3)
00862             frame_bits++;
00863         if (block->new_cpl_strategy) {
00864             if (!s->eac3)
00865                 frame_bits++;
00866             if (block->cpl_in_use) {
00867                 if (s->eac3)
00868                     frame_bits++;
00869                 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
00870                     frame_bits += s->fbw_channels;
00871                 if (s->channel_mode == AC3_CHMODE_STEREO)
00872                     frame_bits++;
00873                 frame_bits += 4 + 4;
00874                 if (s->eac3)
00875                     frame_bits++;
00876                 else
00877                     frame_bits += s->num_cpl_subbands - 1;
00878             }
00879         }
00880 
00881         /* coupling coordinates */
00882         if (block->cpl_in_use) {
00883             for (ch = 1; ch <= s->fbw_channels; ch++) {
00884                 if (block->channel_in_cpl[ch]) {
00885                     if (!s->eac3 || block->new_cpl_coords[ch] != 2)
00886                         frame_bits++;
00887                     if (block->new_cpl_coords[ch]) {
00888                         frame_bits += 2;
00889                         frame_bits += (4 + 4) * s->num_cpl_bands;
00890                     }
00891                 }
00892             }
00893         }
00894 
00895         /* stereo rematrixing */
00896         if (s->channel_mode == AC3_CHMODE_STEREO) {
00897             if (!s->eac3 || blk > 0)
00898                 frame_bits++;
00899             if (s->blocks[blk].new_rematrixing_strategy)
00900                 frame_bits += block->num_rematrixing_bands;
00901         }
00902 
00903         /* bandwidth codes & gain range */
00904         for (ch = 1; ch <= s->fbw_channels; ch++) {
00905             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
00906                 if (!block->channel_in_cpl[ch])
00907                     frame_bits += 6;
00908                 frame_bits += 2;
00909             }
00910         }
00911 
00912         /* coupling exponent strategy */
00913         if (!s->eac3 && block->cpl_in_use)
00914             frame_bits += 2;
00915 
00916         /* snr offsets and fast gain codes */
00917         if (!s->eac3) {
00918             frame_bits++;
00919             if (block->new_snr_offsets)
00920                 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
00921         }
00922 
00923         /* coupling leak info */
00924         if (block->cpl_in_use) {
00925             if (!s->eac3 || block->new_cpl_leak != 2)
00926                 frame_bits++;
00927             if (block->new_cpl_leak)
00928                 frame_bits += 3 + 3;
00929         }
00930     }
00931 
00932     s->frame_bits = s->frame_bits_fixed + frame_bits;
00933 }
00934 
00935 
00936 /*
00937  * Calculate masking curve based on the final exponents.
00938  * Also calculate the power spectral densities to use in future calculations.
00939  */
00940 static void bit_alloc_masking(AC3EncodeContext *s)
00941 {
00942     int blk, ch;
00943 
00944     for (blk = 0; blk < s->num_blocks; blk++) {
00945         AC3Block *block = &s->blocks[blk];
00946         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
00947             /* We only need psd and mask for calculating bap.
00948                Since we currently do not calculate bap when exponent
00949                strategy is EXP_REUSE we do not need to calculate psd or mask. */
00950             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
00951                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
00952                                           block->end_freq[ch], block->psd[ch],
00953                                           block->band_psd[ch]);
00954                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
00955                                            s->start_freq[ch], block->end_freq[ch],
00956                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
00957                                            ch == s->lfe_channel,
00958                                            DBA_NONE, 0, NULL, NULL, NULL,
00959                                            block->mask[ch]);
00960             }
00961         }
00962     }
00963 }
00964 
00965 
00966 /*
00967  * Ensure that bap for each block and channel point to the current bap_buffer.
00968  * They may have been switched during the bit allocation search.
00969  */
00970 static void reset_block_bap(AC3EncodeContext *s)
00971 {
00972     int blk, ch;
00973     uint8_t *ref_bap;
00974 
00975     if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
00976         return;
00977 
00978     ref_bap = s->bap_buffer;
00979     for (ch = 0; ch <= s->channels; ch++) {
00980         for (blk = 0; blk < s->num_blocks; blk++)
00981             s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
00982         ref_bap += AC3_MAX_COEFS * s->num_blocks;
00983     }
00984     s->ref_bap_set = 1;
00985 }
00986 
00987 
00995 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
00996 {
00997     int blk;
00998 
00999     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
01000         memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
01001         mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
01002         mant_cnt[blk][4] = 1;
01003     }
01004 }
01005 
01006 
01017 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
01018                                           uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
01019                                           int start, int end)
01020 {
01021     int blk;
01022 
01023     for (blk = 0; blk < s->num_blocks; blk++) {
01024         AC3Block *block = &s->blocks[blk];
01025         if (ch == CPL_CH && !block->cpl_in_use)
01026             continue;
01027         s->ac3dsp.update_bap_counts(mant_cnt[blk],
01028                                     s->ref_bap[ch][blk] + start,
01029                                     FFMIN(end, block->end_freq[ch]) - start);
01030     }
01031 }
01032 
01033 
01034 /*
01035  * Count the number of mantissa bits in the frame based on the bap values.
01036  */
01037 static int count_mantissa_bits(AC3EncodeContext *s)
01038 {
01039     int ch, max_end_freq;
01040     LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
01041 
01042     count_mantissa_bits_init(mant_cnt);
01043 
01044     max_end_freq = s->bandwidth_code * 3 + 73;
01045     for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
01046         count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
01047                                       max_end_freq);
01048 
01049     return s->ac3dsp.compute_mantissa_size(mant_cnt);
01050 }
01051 
01052 
01063 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
01064 {
01065     int blk, ch;
01066 
01067     snr_offset = (snr_offset - 240) << 2;
01068 
01069     reset_block_bap(s);
01070     for (blk = 0; blk < s->num_blocks; blk++) {
01071         AC3Block *block = &s->blocks[blk];
01072 
01073         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
01074             /* Currently the only bit allocation parameters which vary across
01075                blocks within a frame are the exponent values.  We can take
01076                advantage of that by reusing the bit allocation pointers
01077                whenever we reuse exponents. */
01078             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
01079                 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
01080                                              s->start_freq[ch], block->end_freq[ch],
01081                                              snr_offset, s->bit_alloc.floor,
01082                                              ff_ac3_bap_tab, s->ref_bap[ch][blk]);
01083             }
01084         }
01085     }
01086     return count_mantissa_bits(s);
01087 }
01088 
01089 
01090 /*
01091  * Constant bitrate bit allocation search.
01092  * Find the largest SNR offset that will allow data to fit in the frame.
01093  */
01094 static int cbr_bit_allocation(AC3EncodeContext *s)
01095 {
01096     int ch;
01097     int bits_left;
01098     int snr_offset, snr_incr;
01099 
01100     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
01101     if (bits_left < 0)
01102         return AVERROR(EINVAL);
01103 
01104     snr_offset = s->coarse_snr_offset << 4;
01105 
01106     /* if previous frame SNR offset was 1023, check if current frame can also
01107        use SNR offset of 1023. if so, skip the search. */
01108     if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
01109         if (bit_alloc(s, 1023) <= bits_left)
01110             return 0;
01111     }
01112 
01113     while (snr_offset >= 0 &&
01114            bit_alloc(s, snr_offset) > bits_left) {
01115         snr_offset -= 64;
01116     }
01117     if (snr_offset < 0)
01118         return AVERROR(EINVAL);
01119 
01120     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01121     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
01122         while (snr_offset + snr_incr <= 1023 &&
01123                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
01124             snr_offset += snr_incr;
01125             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01126         }
01127     }
01128     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
01129     reset_block_bap(s);
01130 
01131     s->coarse_snr_offset = snr_offset >> 4;
01132     for (ch = !s->cpl_on; ch <= s->channels; ch++)
01133         s->fine_snr_offset[ch] = snr_offset & 0xF;
01134 
01135     return 0;
01136 }
01137 
01138 
01139 /*
01140  * Perform bit allocation search.
01141  * Finds the SNR offset value that maximizes quality and fits in the specified
01142  * frame size.  Output is the SNR offset and a set of bit allocation pointers
01143  * used to quantize the mantissas.
01144  */
01145 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
01146 {
01147     count_frame_bits(s);
01148 
01149     s->exponent_bits = count_exponent_bits(s);
01150 
01151     bit_alloc_masking(s);
01152 
01153     return cbr_bit_allocation(s);
01154 }
01155 
01156 
01165 static inline int sym_quant(int c, int e, int levels)
01166 {
01167     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
01168     av_assert2(v >= 0 && v < levels);
01169     return v;
01170 }
01171 
01172 
01181 static inline int asym_quant(int c, int e, int qbits)
01182 {
01183     int m;
01184 
01185     c = (((c << e) >> (24 - qbits)) + 1) >> 1;
01186     m = (1 << (qbits-1));
01187     if (c >= m)
01188         c = m - 1;
01189     av_assert2(c >= -m);
01190     return c;
01191 }
01192 
01193 
01205 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
01206                                       uint8_t *exp, uint8_t *bap,
01207                                       int16_t *qmant, int start_freq,
01208                                       int end_freq)
01209 {
01210     int i;
01211 
01212     for (i = start_freq; i < end_freq; i++) {
01213         int v;
01214         int c = fixed_coef[i];
01215         int e = exp[i];
01216         int b = bap[i];
01217         switch (b) {
01218         case 0:
01219             v = 0;
01220             break;
01221         case 1:
01222             v = sym_quant(c, e, 3);
01223             switch (s->mant1_cnt) {
01224             case 0:
01225                 s->qmant1_ptr = &qmant[i];
01226                 v = 9 * v;
01227                 s->mant1_cnt = 1;
01228                 break;
01229             case 1:
01230                 *s->qmant1_ptr += 3 * v;
01231                 s->mant1_cnt = 2;
01232                 v = 128;
01233                 break;
01234             default:
01235                 *s->qmant1_ptr += v;
01236                 s->mant1_cnt = 0;
01237                 v = 128;
01238                 break;
01239             }
01240             break;
01241         case 2:
01242             v = sym_quant(c, e, 5);
01243             switch (s->mant2_cnt) {
01244             case 0:
01245                 s->qmant2_ptr = &qmant[i];
01246                 v = 25 * v;
01247                 s->mant2_cnt = 1;
01248                 break;
01249             case 1:
01250                 *s->qmant2_ptr += 5 * v;
01251                 s->mant2_cnt = 2;
01252                 v = 128;
01253                 break;
01254             default:
01255                 *s->qmant2_ptr += v;
01256                 s->mant2_cnt = 0;
01257                 v = 128;
01258                 break;
01259             }
01260             break;
01261         case 3:
01262             v = sym_quant(c, e, 7);
01263             break;
01264         case 4:
01265             v = sym_quant(c, e, 11);
01266             switch (s->mant4_cnt) {
01267             case 0:
01268                 s->qmant4_ptr = &qmant[i];
01269                 v = 11 * v;
01270                 s->mant4_cnt = 1;
01271                 break;
01272             default:
01273                 *s->qmant4_ptr += v;
01274                 s->mant4_cnt = 0;
01275                 v = 128;
01276                 break;
01277             }
01278             break;
01279         case 5:
01280             v = sym_quant(c, e, 15);
01281             break;
01282         case 14:
01283             v = asym_quant(c, e, 14);
01284             break;
01285         case 15:
01286             v = asym_quant(c, e, 16);
01287             break;
01288         default:
01289             v = asym_quant(c, e, b - 1);
01290             break;
01291         }
01292         qmant[i] = v;
01293     }
01294 }
01295 
01296 
01302 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
01303 {
01304     int blk, ch, ch0=0, got_cpl;
01305 
01306     for (blk = 0; blk < s->num_blocks; blk++) {
01307         AC3Block *block = &s->blocks[blk];
01308         AC3Mant m = { 0 };
01309 
01310         got_cpl = !block->cpl_in_use;
01311         for (ch = 1; ch <= s->channels; ch++) {
01312             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
01313                 ch0     = ch - 1;
01314                 ch      = CPL_CH;
01315                 got_cpl = 1;
01316             }
01317             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
01318                                       s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
01319                                       s->ref_bap[ch][blk], block->qmant[ch],
01320                                       s->start_freq[ch], block->end_freq[ch]);
01321             if (ch == CPL_CH)
01322                 ch = ch0;
01323         }
01324     }
01325 }
01326 
01327 
01328 /*
01329  * Write the AC-3 frame header to the output bitstream.
01330  */
01331 static void ac3_output_frame_header(AC3EncodeContext *s)
01332 {
01333     AC3EncOptions *opt = &s->options;
01334 
01335     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
01336     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
01337     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
01338     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
01339     put_bits(&s->pb, 5,  s->bitstream_id);
01340     put_bits(&s->pb, 3,  s->bitstream_mode);
01341     put_bits(&s->pb, 3,  s->channel_mode);
01342     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
01343         put_bits(&s->pb, 2, s->center_mix_level);
01344     if (s->channel_mode & 0x04)
01345         put_bits(&s->pb, 2, s->surround_mix_level);
01346     if (s->channel_mode == AC3_CHMODE_STEREO)
01347         put_bits(&s->pb, 2, opt->dolby_surround_mode);
01348     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
01349     put_bits(&s->pb, 5, -opt->dialogue_level);
01350     put_bits(&s->pb, 1, 0);         /* no compression control word */
01351     put_bits(&s->pb, 1, 0);         /* no lang code */
01352     put_bits(&s->pb, 1, opt->audio_production_info);
01353     if (opt->audio_production_info) {
01354         put_bits(&s->pb, 5, opt->mixing_level - 80);
01355         put_bits(&s->pb, 2, opt->room_type);
01356     }
01357     put_bits(&s->pb, 1, opt->copyright);
01358     put_bits(&s->pb, 1, opt->original);
01359     if (s->bitstream_id == 6) {
01360         /* alternate bit stream syntax */
01361         put_bits(&s->pb, 1, opt->extended_bsi_1);
01362         if (opt->extended_bsi_1) {
01363             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
01364             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
01365             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
01366             put_bits(&s->pb, 3, s->loro_center_mix_level);
01367             put_bits(&s->pb, 3, s->loro_surround_mix_level);
01368         }
01369         put_bits(&s->pb, 1, opt->extended_bsi_2);
01370         if (opt->extended_bsi_2) {
01371             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
01372             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
01373             put_bits(&s->pb, 1, opt->ad_converter_type);
01374             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
01375         }
01376     } else {
01377     put_bits(&s->pb, 1, 0);         /* no time code 1 */
01378     put_bits(&s->pb, 1, 0);         /* no time code 2 */
01379     }
01380     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
01381 }
01382 
01383 
01384 /*
01385  * Write one audio block to the output bitstream.
01386  */
01387 static void output_audio_block(AC3EncodeContext *s, int blk)
01388 {
01389     int ch, i, baie, bnd, got_cpl;
01390     int av_uninit(ch0);
01391     AC3Block *block = &s->blocks[blk];
01392 
01393     /* block switching */
01394     if (!s->eac3) {
01395         for (ch = 0; ch < s->fbw_channels; ch++)
01396             put_bits(&s->pb, 1, 0);
01397     }
01398 
01399     /* dither flags */
01400     if (!s->eac3) {
01401         for (ch = 0; ch < s->fbw_channels; ch++)
01402             put_bits(&s->pb, 1, 1);
01403     }
01404 
01405     /* dynamic range codes */
01406     put_bits(&s->pb, 1, 0);
01407 
01408     /* spectral extension */
01409     if (s->eac3)
01410         put_bits(&s->pb, 1, 0);
01411 
01412     /* channel coupling */
01413     if (!s->eac3)
01414         put_bits(&s->pb, 1, block->new_cpl_strategy);
01415     if (block->new_cpl_strategy) {
01416         if (!s->eac3)
01417             put_bits(&s->pb, 1, block->cpl_in_use);
01418         if (block->cpl_in_use) {
01419             int start_sub, end_sub;
01420             if (s->eac3)
01421                 put_bits(&s->pb, 1, 0); /* enhanced coupling */
01422             if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
01423                 for (ch = 1; ch <= s->fbw_channels; ch++)
01424                     put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
01425             }
01426             if (s->channel_mode == AC3_CHMODE_STEREO)
01427                 put_bits(&s->pb, 1, 0); /* phase flags in use */
01428             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
01429             end_sub   = (s->cpl_end_freq       - 37) / 12;
01430             put_bits(&s->pb, 4, start_sub);
01431             put_bits(&s->pb, 4, end_sub - 3);
01432             /* coupling band structure */
01433             if (s->eac3) {
01434                 put_bits(&s->pb, 1, 0); /* use default */
01435             } else {
01436                 for (bnd = start_sub+1; bnd < end_sub; bnd++)
01437                     put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
01438             }
01439         }
01440     }
01441 
01442     /* coupling coordinates */
01443     if (block->cpl_in_use) {
01444         for (ch = 1; ch <= s->fbw_channels; ch++) {
01445             if (block->channel_in_cpl[ch]) {
01446                 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
01447                     put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
01448                 if (block->new_cpl_coords[ch]) {
01449                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
01450                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
01451                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
01452                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
01453                     }
01454                 }
01455             }
01456         }
01457     }
01458 
01459     /* stereo rematrixing */
01460     if (s->channel_mode == AC3_CHMODE_STEREO) {
01461         if (!s->eac3 || blk > 0)
01462             put_bits(&s->pb, 1, block->new_rematrixing_strategy);
01463         if (block->new_rematrixing_strategy) {
01464             /* rematrixing flags */
01465             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
01466                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
01467         }
01468     }
01469 
01470     /* exponent strategy */
01471     if (!s->eac3) {
01472         for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
01473             put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
01474         if (s->lfe_on)
01475             put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
01476     }
01477 
01478     /* bandwidth */
01479     for (ch = 1; ch <= s->fbw_channels; ch++) {
01480         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
01481             put_bits(&s->pb, 6, s->bandwidth_code);
01482     }
01483 
01484     /* exponents */
01485     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
01486         int nb_groups;
01487         int cpl = (ch == CPL_CH);
01488 
01489         if (s->exp_strategy[ch][blk] == EXP_REUSE)
01490             continue;
01491 
01492         /* DC exponent */
01493         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
01494 
01495         /* exponent groups */
01496         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
01497         for (i = 1; i <= nb_groups; i++)
01498             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
01499 
01500         /* gain range info */
01501         if (ch != s->lfe_channel && !cpl)
01502             put_bits(&s->pb, 2, 0);
01503     }
01504 
01505     /* bit allocation info */
01506     if (!s->eac3) {
01507         baie = (blk == 0);
01508         put_bits(&s->pb, 1, baie);
01509         if (baie) {
01510             put_bits(&s->pb, 2, s->slow_decay_code);
01511             put_bits(&s->pb, 2, s->fast_decay_code);
01512             put_bits(&s->pb, 2, s->slow_gain_code);
01513             put_bits(&s->pb, 2, s->db_per_bit_code);
01514             put_bits(&s->pb, 3, s->floor_code);
01515         }
01516     }
01517 
01518     /* snr offset */
01519     if (!s->eac3) {
01520         put_bits(&s->pb, 1, block->new_snr_offsets);
01521         if (block->new_snr_offsets) {
01522             put_bits(&s->pb, 6, s->coarse_snr_offset);
01523             for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
01524                 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
01525                 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
01526             }
01527         }
01528     } else {
01529         put_bits(&s->pb, 1, 0); /* no converter snr offset */
01530     }
01531 
01532     /* coupling leak */
01533     if (block->cpl_in_use) {
01534         if (!s->eac3 || block->new_cpl_leak != 2)
01535             put_bits(&s->pb, 1, block->new_cpl_leak);
01536         if (block->new_cpl_leak) {
01537             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
01538             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
01539         }
01540     }
01541 
01542     if (!s->eac3) {
01543         put_bits(&s->pb, 1, 0); /* no delta bit allocation */
01544         put_bits(&s->pb, 1, 0); /* no data to skip */
01545     }
01546 
01547     /* mantissas */
01548     got_cpl = !block->cpl_in_use;
01549     for (ch = 1; ch <= s->channels; ch++) {
01550         int b, q;
01551 
01552         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
01553             ch0     = ch - 1;
01554             ch      = CPL_CH;
01555             got_cpl = 1;
01556         }
01557         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
01558             q = block->qmant[ch][i];
01559             b = s->ref_bap[ch][blk][i];
01560             switch (b) {
01561             case 0:                                          break;
01562             case 1: if (q != 128) put_bits (&s->pb,   5, q); break;
01563             case 2: if (q != 128) put_bits (&s->pb,   7, q); break;
01564             case 3:               put_sbits(&s->pb,   3, q); break;
01565             case 4: if (q != 128) put_bits (&s->pb,   7, q); break;
01566             case 14:              put_sbits(&s->pb,  14, q); break;
01567             case 15:              put_sbits(&s->pb,  16, q); break;
01568             default:              put_sbits(&s->pb, b-1, q); break;
01569             }
01570         }
01571         if (ch == CPL_CH)
01572             ch = ch0;
01573     }
01574 }
01575 
01576 
01578 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
01579 
01580 
01581 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
01582 {
01583     unsigned int c;
01584 
01585     c = 0;
01586     while (a) {
01587         if (a & 1)
01588             c ^= b;
01589         a = a >> 1;
01590         b = b << 1;
01591         if (b & (1 << 16))
01592             b ^= poly;
01593     }
01594     return c;
01595 }
01596 
01597 
01598 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
01599 {
01600     unsigned int r;
01601     r = 1;
01602     while (n) {
01603         if (n & 1)
01604             r = mul_poly(r, a, poly);
01605         a = mul_poly(a, a, poly);
01606         n >>= 1;
01607     }
01608     return r;
01609 }
01610 
01611 
01612 /*
01613  * Fill the end of the frame with 0's and compute the two CRCs.
01614  */
01615 static void output_frame_end(AC3EncodeContext *s)
01616 {
01617     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
01618     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
01619     uint8_t *frame;
01620 
01621     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
01622 
01623     /* pad the remainder of the frame with zeros */
01624     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
01625     flush_put_bits(&s->pb);
01626     frame = s->pb.buf;
01627     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
01628     av_assert2(pad_bytes >= 0);
01629     if (pad_bytes > 0)
01630         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
01631 
01632     if (s->eac3) {
01633         /* compute crc2 */
01634         crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
01635     } else {
01636     /* compute crc1 */
01637     /* this is not so easy because it is at the beginning of the data... */
01638     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
01639     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
01640     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
01641     AV_WB16(frame + 2, crc1);
01642 
01643     /* compute crc2 */
01644     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
01645                           s->frame_size - frame_size_58 - 3);
01646     }
01647     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
01648     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
01649     if (crc2 == 0x770B) {
01650         frame[s->frame_size - 3] ^= 0x1;
01651         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
01652     }
01653     crc2 = av_bswap16(crc2);
01654     AV_WB16(frame + s->frame_size - 2, crc2);
01655 }
01656 
01657 
01664 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
01665 {
01666     int blk;
01667 
01668     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
01669 
01670     s->output_frame_header(s);
01671 
01672     for (blk = 0; blk < s->num_blocks; blk++)
01673         output_audio_block(s, blk);
01674 
01675     output_frame_end(s);
01676 }
01677 
01678 
01679 static void dprint_options(AC3EncodeContext *s)
01680 {
01681 #ifdef DEBUG
01682     AVCodecContext *avctx = s->avctx;
01683     AC3EncOptions *opt = &s->options;
01684     char strbuf[32];
01685 
01686     switch (s->bitstream_id) {
01687     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
01688     case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
01689     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
01690     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
01691     case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
01692     default: snprintf(strbuf, 32, "ERROR");
01693     }
01694     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
01695     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
01696     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
01697     av_dlog(avctx, "channel_layout: %s\n", strbuf);
01698     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
01699     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
01700     av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
01701     if (s->cutoff)
01702         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
01703 
01704     av_dlog(avctx, "per_frame_metadata: %s\n",
01705             opt->allow_per_frame_metadata?"on":"off");
01706     if (s->has_center)
01707         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
01708                 s->center_mix_level);
01709     else
01710         av_dlog(avctx, "center_mixlev: {not written}\n");
01711     if (s->has_surround)
01712         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
01713                 s->surround_mix_level);
01714     else
01715         av_dlog(avctx, "surround_mixlev: {not written}\n");
01716     if (opt->audio_production_info) {
01717         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
01718         switch (opt->room_type) {
01719         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
01720         case AC3ENC_OPT_LARGE_ROOM:    av_strlcpy(strbuf, "large", 32);        break;
01721         case AC3ENC_OPT_SMALL_ROOM:    av_strlcpy(strbuf, "small", 32);        break;
01722         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
01723         }
01724         av_dlog(avctx, "room_type: %s\n", strbuf);
01725     } else {
01726         av_dlog(avctx, "mixing_level: {not written}\n");
01727         av_dlog(avctx, "room_type: {not written}\n");
01728     }
01729     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
01730     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
01731     if (s->channel_mode == AC3_CHMODE_STEREO) {
01732         switch (opt->dolby_surround_mode) {
01733         case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
01734         case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
01735         case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
01736         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
01737         }
01738         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
01739     } else {
01740         av_dlog(avctx, "dsur_mode: {not written}\n");
01741     }
01742     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
01743 
01744     if (s->bitstream_id == 6) {
01745         if (opt->extended_bsi_1) {
01746             switch (opt->preferred_stereo_downmix) {
01747             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
01748             case AC3ENC_OPT_DOWNMIX_LTRT:  av_strlcpy(strbuf, "ltrt", 32);         break;
01749             case AC3ENC_OPT_DOWNMIX_LORO:  av_strlcpy(strbuf, "loro", 32);         break;
01750             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
01751             }
01752             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
01753             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
01754                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
01755             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
01756                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
01757             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
01758                     opt->loro_center_mix_level, s->loro_center_mix_level);
01759             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
01760                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
01761         } else {
01762             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
01763         }
01764         if (opt->extended_bsi_2) {
01765             switch (opt->dolby_surround_ex_mode) {
01766             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
01767             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
01768             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
01769             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
01770             }
01771             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
01772             switch (opt->dolby_headphone_mode) {
01773             case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
01774             case AC3ENC_OPT_MODE_ON:       av_strlcpy(strbuf, "on", 32);           break;
01775             case AC3ENC_OPT_MODE_OFF:      av_strlcpy(strbuf, "off", 32);          break;
01776             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
01777             }
01778             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
01779 
01780             switch (opt->ad_converter_type) {
01781             case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
01782             case AC3ENC_OPT_ADCONV_HDCD:     av_strlcpy(strbuf, "hdcd", 32);     break;
01783             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
01784             }
01785             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
01786         } else {
01787             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
01788         }
01789     }
01790 #endif
01791 }
01792 
01793 
01794 #define FLT_OPTION_THRESHOLD 0.01
01795 
01796 static int validate_float_option(float v, const float *v_list, int v_list_size)
01797 {
01798     int i;
01799 
01800     for (i = 0; i < v_list_size; i++) {
01801         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
01802             v > (v_list[i] - FLT_OPTION_THRESHOLD))
01803             break;
01804     }
01805     if (i == v_list_size)
01806         return -1;
01807 
01808     return i;
01809 }
01810 
01811 
01812 static void validate_mix_level(void *log_ctx, const char *opt_name,
01813                                float *opt_param, const float *list,
01814                                int list_size, int default_value, int min_value,
01815                                int *ctx_param)
01816 {
01817     int mixlev = validate_float_option(*opt_param, list, list_size);
01818     if (mixlev < min_value) {
01819         mixlev = default_value;
01820         if (*opt_param >= 0.0) {
01821             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
01822                    "default value: %0.3f\n", opt_name, list[mixlev]);
01823         }
01824     }
01825     *opt_param = list[mixlev];
01826     *ctx_param = mixlev;
01827 }
01828 
01829 
01836 int ff_ac3_validate_metadata(AC3EncodeContext *s)
01837 {
01838     AVCodecContext *avctx = s->avctx;
01839     AC3EncOptions *opt = &s->options;
01840 
01841     opt->audio_production_info = 0;
01842     opt->extended_bsi_1        = 0;
01843     opt->extended_bsi_2        = 0;
01844     opt->eac3_mixing_metadata  = 0;
01845     opt->eac3_info_metadata    = 0;
01846 
01847     /* determine mixing metadata / xbsi1 use */
01848     if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
01849         opt->extended_bsi_1       = 1;
01850         opt->eac3_mixing_metadata = 1;
01851     }
01852     if (s->has_center &&
01853         (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
01854         opt->extended_bsi_1       = 1;
01855         opt->eac3_mixing_metadata = 1;
01856     }
01857     if (s->has_surround &&
01858         (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
01859         opt->extended_bsi_1       = 1;
01860         opt->eac3_mixing_metadata = 1;
01861     }
01862 
01863     if (s->eac3) {
01864         /* determine info metadata use */
01865         if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
01866             opt->eac3_info_metadata = 1;
01867         if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
01868             opt->eac3_info_metadata = 1;
01869         if (s->channel_mode == AC3_CHMODE_STEREO &&
01870             (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
01871             opt->eac3_info_metadata = 1;
01872         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
01873             opt->eac3_info_metadata = 1;
01874         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
01875             opt->ad_converter_type != AC3ENC_OPT_NONE) {
01876             opt->audio_production_info = 1;
01877             opt->eac3_info_metadata    = 1;
01878         }
01879     } else {
01880         /* determine audio production info use */
01881         if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
01882             opt->audio_production_info = 1;
01883 
01884         /* determine xbsi2 use */
01885         if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
01886             opt->extended_bsi_2 = 1;
01887         if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
01888             opt->extended_bsi_2 = 1;
01889         if (opt->ad_converter_type != AC3ENC_OPT_NONE)
01890             opt->extended_bsi_2 = 1;
01891     }
01892 
01893     /* validate AC-3 mixing levels */
01894     if (!s->eac3) {
01895         if (s->has_center) {
01896             validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
01897                             cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
01898                             &s->center_mix_level);
01899         }
01900         if (s->has_surround) {
01901             validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
01902                             surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
01903                             &s->surround_mix_level);
01904         }
01905     }
01906 
01907     /* validate extended bsi 1 / mixing metadata */
01908     if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
01909         /* default preferred stereo downmix */
01910         if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
01911             opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
01912         if (!s->eac3 || s->has_center) {
01913             /* validate Lt/Rt center mix level */
01914             validate_mix_level(avctx, "ltrt_center_mix_level",
01915                                &opt->ltrt_center_mix_level, extmixlev_options,
01916                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
01917                                &s->ltrt_center_mix_level);
01918             /* validate Lo/Ro center mix level */
01919             validate_mix_level(avctx, "loro_center_mix_level",
01920                                &opt->loro_center_mix_level, extmixlev_options,
01921                                EXTMIXLEV_NUM_OPTIONS, 5, 0,
01922                                &s->loro_center_mix_level);
01923         }
01924         if (!s->eac3 || s->has_surround) {
01925             /* validate Lt/Rt surround mix level */
01926             validate_mix_level(avctx, "ltrt_surround_mix_level",
01927                                &opt->ltrt_surround_mix_level, extmixlev_options,
01928                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
01929                                &s->ltrt_surround_mix_level);
01930             /* validate Lo/Ro surround mix level */
01931             validate_mix_level(avctx, "loro_surround_mix_level",
01932                                &opt->loro_surround_mix_level, extmixlev_options,
01933                                EXTMIXLEV_NUM_OPTIONS, 6, 3,
01934                                &s->loro_surround_mix_level);
01935         }
01936     }
01937 
01938     /* validate audio service type / channels combination */
01939     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
01940          avctx->channels == 1) ||
01941         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
01942           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
01943           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
01944          && avctx->channels > 1)) {
01945         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
01946                                     "specified number of channels\n");
01947         return AVERROR(EINVAL);
01948     }
01949 
01950     /* validate extended bsi 2 / info metadata */
01951     if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
01952         /* default dolby headphone mode */
01953         if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
01954             opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
01955         /* default dolby surround ex mode */
01956         if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
01957             opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
01958         /* default A/D converter type */
01959         if (opt->ad_converter_type == AC3ENC_OPT_NONE)
01960             opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
01961     }
01962 
01963     /* copyright & original defaults */
01964     if (!s->eac3 || opt->eac3_info_metadata) {
01965         /* default copyright */
01966         if (opt->copyright == AC3ENC_OPT_NONE)
01967             opt->copyright = AC3ENC_OPT_OFF;
01968         /* default original */
01969         if (opt->original == AC3ENC_OPT_NONE)
01970             opt->original = AC3ENC_OPT_ON;
01971     }
01972 
01973     /* dolby surround mode default */
01974     if (!s->eac3 || opt->eac3_info_metadata) {
01975         if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
01976             opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
01977     }
01978 
01979     /* validate audio production info */
01980     if (opt->audio_production_info) {
01981         if (opt->mixing_level == AC3ENC_OPT_NONE) {
01982             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
01983                    "room_type is set\n");
01984             return AVERROR(EINVAL);
01985         }
01986         if (opt->mixing_level < 80) {
01987             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
01988                    "80dB and 111dB\n");
01989             return AVERROR(EINVAL);
01990         }
01991         /* default room type */
01992         if (opt->room_type == AC3ENC_OPT_NONE)
01993             opt->room_type = AC3ENC_OPT_NOT_INDICATED;
01994     }
01995 
01996     /* set bitstream id for alternate bitstream syntax */
01997     if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
01998         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
01999             static int warn_once = 1;
02000             if (warn_once) {
02001                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
02002                        "not compatible with reduced samplerates. writing of "
02003                        "extended bitstream information will be disabled.\n");
02004                 warn_once = 0;
02005             }
02006         } else {
02007             s->bitstream_id = 6;
02008         }
02009     }
02010 
02011     return 0;
02012 }
02013 
02014 
02020 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
02021 {
02022     int blk, ch;
02023     AC3EncodeContext *s = avctx->priv_data;
02024 
02025     av_freep(&s->windowed_samples);
02026     for (ch = 0; ch < s->channels; ch++)
02027         av_freep(&s->planar_samples[ch]);
02028     av_freep(&s->planar_samples);
02029     av_freep(&s->bap_buffer);
02030     av_freep(&s->bap1_buffer);
02031     av_freep(&s->mdct_coef_buffer);
02032     av_freep(&s->fixed_coef_buffer);
02033     av_freep(&s->exp_buffer);
02034     av_freep(&s->grouped_exp_buffer);
02035     av_freep(&s->psd_buffer);
02036     av_freep(&s->band_psd_buffer);
02037     av_freep(&s->mask_buffer);
02038     av_freep(&s->qmant_buffer);
02039     av_freep(&s->cpl_coord_exp_buffer);
02040     av_freep(&s->cpl_coord_mant_buffer);
02041     for (blk = 0; blk < s->num_blocks; blk++) {
02042         AC3Block *block = &s->blocks[blk];
02043         av_freep(&block->mdct_coef);
02044         av_freep(&block->fixed_coef);
02045         av_freep(&block->exp);
02046         av_freep(&block->grouped_exp);
02047         av_freep(&block->psd);
02048         av_freep(&block->band_psd);
02049         av_freep(&block->mask);
02050         av_freep(&block->qmant);
02051         av_freep(&block->cpl_coord_exp);
02052         av_freep(&block->cpl_coord_mant);
02053     }
02054 
02055     s->mdct_end(s);
02056 
02057     av_freep(&avctx->coded_frame);
02058     return 0;
02059 }
02060 
02061 
02062 /*
02063  * Set channel information during initialization.
02064  */
02065 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
02066                                     uint64_t *channel_layout)
02067 {
02068     int ch_layout;
02069 
02070     if (channels < 1 || channels > AC3_MAX_CHANNELS)
02071         return AVERROR(EINVAL);
02072     if (*channel_layout > 0x7FF)
02073         return AVERROR(EINVAL);
02074     ch_layout = *channel_layout;
02075     if (!ch_layout)
02076         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
02077 
02078     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
02079     s->channels     = channels;
02080     s->fbw_channels = channels - s->lfe_on;
02081     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
02082     if (s->lfe_on)
02083         ch_layout -= AV_CH_LOW_FREQUENCY;
02084 
02085     switch (ch_layout) {
02086     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
02087     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
02088     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
02089     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
02090     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
02091     case AV_CH_LAYOUT_QUAD:
02092     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
02093     case AV_CH_LAYOUT_5POINT0:
02094     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
02095     default:
02096         return AVERROR(EINVAL);
02097     }
02098     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
02099     s->has_surround =  s->channel_mode & 0x04;
02100 
02101     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
02102     *channel_layout = ch_layout;
02103     if (s->lfe_on)
02104         *channel_layout |= AV_CH_LOW_FREQUENCY;
02105 
02106     return 0;
02107 }
02108 
02109 
02110 static av_cold int validate_options(AC3EncodeContext *s)
02111 {
02112     AVCodecContext *avctx = s->avctx;
02113     int i, ret, max_sr;
02114 
02115     /* validate channel layout */
02116     if (!avctx->channel_layout) {
02117         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
02118                                       "encoder will guess the layout, but it "
02119                                       "might be incorrect.\n");
02120     }
02121     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
02122     if (ret) {
02123         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
02124         return ret;
02125     }
02126 
02127     /* validate sample rate */
02128     /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
02129              decoder that supports half sample rate so we can validate that
02130              the generated files are correct. */
02131     max_sr = s->eac3 ? 2 : 8;
02132     for (i = 0; i <= max_sr; i++) {
02133         if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
02134             break;
02135     }
02136     if (i > max_sr) {
02137         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
02138         return AVERROR(EINVAL);
02139     }
02140     s->sample_rate        = avctx->sample_rate;
02141     s->bit_alloc.sr_shift = i / 3;
02142     s->bit_alloc.sr_code  = i % 3;
02143     s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
02144 
02145     /* validate bit rate */
02146     if (s->eac3) {
02147         int max_br, min_br, wpf, min_br_dist, min_br_code;
02148         int num_blks_code, num_blocks, frame_samples;
02149 
02150         /* calculate min/max bitrate */
02151         /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
02152                  found use either 6 blocks or 1 block, even though 2 or 3 blocks
02153                  would work as far as the bit rate is concerned. */
02154         for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
02155             num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
02156             frame_samples  = AC3_BLOCK_SIZE * num_blocks;
02157             max_br = 2048 * s->sample_rate / frame_samples * 16;
02158             min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
02159             if (avctx->bit_rate <= max_br)
02160                 break;
02161         }
02162         if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
02163             av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
02164                    "for this sample rate\n", min_br, max_br);
02165             return AVERROR(EINVAL);
02166         }
02167         s->num_blks_code = num_blks_code;
02168         s->num_blocks    = num_blocks;
02169 
02170         /* calculate words-per-frame for the selected bitrate */
02171         wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
02172         av_assert1(wpf > 0 && wpf <= 2048);
02173 
02174         /* find the closest AC-3 bitrate code to the selected bitrate.
02175            this is needed for lookup tables for bandwidth and coupling
02176            parameter selection */
02177         min_br_code = -1;
02178         min_br_dist = INT_MAX;
02179         for (i = 0; i < 19; i++) {
02180             int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
02181             if (br_dist < min_br_dist) {
02182                 min_br_dist = br_dist;
02183                 min_br_code = i;
02184             }
02185         }
02186 
02187         /* make sure the minimum frame size is below the average frame size */
02188         s->frame_size_code = min_br_code << 1;
02189         while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
02190             wpf--;
02191         s->frame_size_min = 2 * wpf;
02192     } else {
02193         for (i = 0; i < 19; i++) {
02194             if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
02195                 break;
02196         }
02197         if (i == 19) {
02198             av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
02199             return AVERROR(EINVAL);
02200         }
02201         s->frame_size_code = i << 1;
02202         s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
02203         s->num_blks_code   = 0x3;
02204         s->num_blocks      = 6;
02205     }
02206     s->bit_rate   = avctx->bit_rate;
02207     s->frame_size = s->frame_size_min;
02208 
02209     /* validate cutoff */
02210     if (avctx->cutoff < 0) {
02211         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
02212         return AVERROR(EINVAL);
02213     }
02214     s->cutoff = avctx->cutoff;
02215     if (s->cutoff > (s->sample_rate >> 1))
02216         s->cutoff = s->sample_rate >> 1;
02217 
02218     ret = ff_ac3_validate_metadata(s);
02219     if (ret)
02220         return ret;
02221 
02222     s->rematrixing_enabled = s->options.stereo_rematrixing &&
02223                              (s->channel_mode == AC3_CHMODE_STEREO);
02224 
02225     s->cpl_enabled = s->options.channel_coupling &&
02226                      s->channel_mode >= AC3_CHMODE_STEREO;
02227 
02228     return 0;
02229 }
02230 
02231 
02232 /*
02233  * Set bandwidth for all channels.
02234  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
02235  * default value will be used.
02236  */
02237 static av_cold void set_bandwidth(AC3EncodeContext *s)
02238 {
02239     int blk, ch;
02240     int av_uninit(cpl_start);
02241 
02242     if (s->cutoff) {
02243         /* calculate bandwidth based on user-specified cutoff frequency */
02244         int fbw_coeffs;
02245         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
02246         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
02247     } else {
02248         /* use default bandwidth setting */
02249         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
02250     }
02251 
02252     /* set number of coefficients for each channel */
02253     for (ch = 1; ch <= s->fbw_channels; ch++) {
02254         s->start_freq[ch] = 0;
02255         for (blk = 0; blk < s->num_blocks; blk++)
02256             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
02257     }
02258     /* LFE channel always has 7 coefs */
02259     if (s->lfe_on) {
02260         s->start_freq[s->lfe_channel] = 0;
02261         for (blk = 0; blk < s->num_blocks; blk++)
02262             s->blocks[blk].end_freq[ch] = 7;
02263     }
02264 
02265     /* initialize coupling strategy */
02266     if (s->cpl_enabled) {
02267         if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
02268             cpl_start = s->options.cpl_start;
02269         } else {
02270             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
02271             if (cpl_start < 0) {
02272                 if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
02273                     s->cpl_enabled = 0;
02274                 else
02275                     cpl_start = 15;
02276             }
02277         }
02278     }
02279     if (s->cpl_enabled) {
02280         int i, cpl_start_band, cpl_end_band;
02281         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
02282 
02283         cpl_end_band   = s->bandwidth_code / 4 + 3;
02284         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
02285 
02286         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
02287 
02288         s->num_cpl_bands = 1;
02289         *cpl_band_sizes  = 12;
02290         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
02291             if (ff_eac3_default_cpl_band_struct[i]) {
02292                 *cpl_band_sizes += 12;
02293             } else {
02294                 s->num_cpl_bands++;
02295                 cpl_band_sizes++;
02296                 *cpl_band_sizes = 12;
02297             }
02298         }
02299 
02300         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
02301         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
02302         for (blk = 0; blk < s->num_blocks; blk++)
02303             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
02304     }
02305 }
02306 
02307 
02308 static av_cold int allocate_buffers(AC3EncodeContext *s)
02309 {
02310     AVCodecContext *avctx = s->avctx;
02311     int blk, ch;
02312     int channels = s->channels + 1; /* includes coupling channel */
02313     int channel_blocks = channels * s->num_blocks;
02314     int total_coefs    = AC3_MAX_COEFS * channel_blocks;
02315 
02316     if (s->allocate_sample_buffers(s))
02317         goto alloc_fail;
02318 
02319     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
02320                      sizeof(*s->bap_buffer), alloc_fail);
02321     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
02322                      sizeof(*s->bap1_buffer), alloc_fail);
02323     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
02324                       sizeof(*s->mdct_coef_buffer), alloc_fail);
02325     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
02326                      sizeof(*s->exp_buffer), alloc_fail);
02327     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
02328                      sizeof(*s->grouped_exp_buffer), alloc_fail);
02329     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
02330                      sizeof(*s->psd_buffer), alloc_fail);
02331     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
02332                      sizeof(*s->band_psd_buffer), alloc_fail);
02333     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
02334                      sizeof(*s->mask_buffer), alloc_fail);
02335     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
02336                      sizeof(*s->qmant_buffer), alloc_fail);
02337     if (s->cpl_enabled) {
02338         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
02339                          sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
02340         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
02341                          sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
02342     }
02343     for (blk = 0; blk < s->num_blocks; blk++) {
02344         AC3Block *block = &s->blocks[blk];
02345         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
02346                           alloc_fail);
02347         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
02348                           alloc_fail);
02349         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
02350                           alloc_fail);
02351         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
02352                           alloc_fail);
02353         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
02354                           alloc_fail);
02355         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
02356                           alloc_fail);
02357         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
02358                           alloc_fail);
02359         if (s->cpl_enabled) {
02360             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
02361                               alloc_fail);
02362             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
02363                               alloc_fail);
02364         }
02365 
02366         for (ch = 0; ch < channels; ch++) {
02367             /* arrangement: block, channel, coeff */
02368             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
02369             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
02370             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
02371             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
02372             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
02373             if (s->cpl_enabled) {
02374                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
02375                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
02376             }
02377 
02378             /* arrangement: channel, block, coeff */
02379             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
02380             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
02381         }
02382     }
02383 
02384     if (!s->fixed_point) {
02385         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
02386                           sizeof(*s->fixed_coef_buffer), alloc_fail);
02387         for (blk = 0; blk < s->num_blocks; blk++) {
02388             AC3Block *block = &s->blocks[blk];
02389             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
02390                               sizeof(*block->fixed_coef), alloc_fail);
02391             for (ch = 0; ch < channels; ch++)
02392                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
02393         }
02394     } else {
02395         for (blk = 0; blk < s->num_blocks; blk++) {
02396             AC3Block *block = &s->blocks[blk];
02397             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
02398                               sizeof(*block->fixed_coef), alloc_fail);
02399             for (ch = 0; ch < channels; ch++)
02400                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
02401         }
02402     }
02403 
02404     return 0;
02405 alloc_fail:
02406     return AVERROR(ENOMEM);
02407 }
02408 
02409 
02410 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
02411 {
02412     AC3EncodeContext *s = avctx->priv_data;
02413     int ret, frame_size_58;
02414 
02415     s->avctx = avctx;
02416 
02417     s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
02418 
02419     ff_ac3_common_init();
02420 
02421     ret = validate_options(s);
02422     if (ret)
02423         return ret;
02424 
02425     avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
02426 
02427     s->bitstream_mode = avctx->audio_service_type;
02428     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
02429         s->bitstream_mode = 0x7;
02430 
02431     s->bits_written    = 0;
02432     s->samples_written = 0;
02433 
02434     /* calculate crc_inv for both possible frame sizes */
02435     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
02436     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
02437     if (s->bit_alloc.sr_code == 1) {
02438         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
02439         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
02440     }
02441 
02442     /* set function pointers */
02443     if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
02444         s->mdct_end                     = ff_ac3_fixed_mdct_end;
02445         s->mdct_init                    = ff_ac3_fixed_mdct_init;
02446         s->allocate_sample_buffers      = ff_ac3_fixed_allocate_sample_buffers;
02447     } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
02448         s->mdct_end                     = ff_ac3_float_mdct_end;
02449         s->mdct_init                    = ff_ac3_float_mdct_init;
02450         s->allocate_sample_buffers      = ff_ac3_float_allocate_sample_buffers;
02451     }
02452     if (CONFIG_EAC3_ENCODER && s->eac3)
02453         s->output_frame_header = ff_eac3_output_frame_header;
02454     else
02455         s->output_frame_header = ac3_output_frame_header;
02456 
02457     set_bandwidth(s);
02458 
02459     exponent_init(s);
02460 
02461     bit_alloc_init(s);
02462 
02463     ret = s->mdct_init(s);
02464     if (ret)
02465         goto init_fail;
02466 
02467     ret = allocate_buffers(s);
02468     if (ret)
02469         goto init_fail;
02470 
02471     avctx->coded_frame= avcodec_alloc_frame();
02472 
02473     dsputil_init(&s->dsp, avctx);
02474     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
02475 
02476     dprint_options(s);
02477 
02478     return 0;
02479 init_fail:
02480     ff_ac3_encode_close(avctx);
02481     return ret;
02482 }
Generated on Sun Apr 22 2012 21:53:59 for Libav by doxygen 1.7.1