libavcodec/ac3enc_template.c
Go to the documentation of this file.
00001 /*
00002  * AC-3 encoder float/fixed template
00003  * Copyright (c) 2000 Fabrice Bellard
00004  * Copyright (c) 2006-2011 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 #include <stdint.h>
00030 
00031 
00032 /* prototypes for static functions in ac3enc_fixed.c and ac3enc_float.c */
00033 
00034 static void scale_coefficients(AC3EncodeContext *s);
00035 
00036 static void apply_window(DSPContext *dsp, SampleType *output,
00037                          const SampleType *input, const SampleType *window,
00038                          unsigned int len);
00039 
00040 static int normalize_samples(AC3EncodeContext *s);
00041 
00042 static void clip_coefficients(DSPContext *dsp, CoefType *coef, unsigned int len);
00043 
00044 static CoefType calc_cpl_coord(CoefSumType energy_ch, CoefSumType energy_cpl);
00045 
00046 
00047 int AC3_NAME(allocate_sample_buffers)(AC3EncodeContext *s)
00048 {
00049     int ch;
00050 
00051     FF_ALLOC_OR_GOTO(s->avctx, s->windowed_samples, AC3_WINDOW_SIZE *
00052                      sizeof(*s->windowed_samples), alloc_fail);
00053     FF_ALLOC_OR_GOTO(s->avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
00054                      alloc_fail);
00055     for (ch = 0; ch < s->channels; ch++) {
00056         FF_ALLOCZ_OR_GOTO(s->avctx, s->planar_samples[ch],
00057                           (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
00058                           alloc_fail);
00059     }
00060 
00061     return 0;
00062 alloc_fail:
00063     return AVERROR(ENOMEM);
00064 }
00065 
00066 
00067 /*
00068  * Deinterleave input samples.
00069  * Channels are reordered from Libav's default order to AC-3 order.
00070  */
00071 static void deinterleave_input_samples(AC3EncodeContext *s,
00072                                        const SampleType *samples)
00073 {
00074     int ch, i;
00075 
00076     /* deinterleave and remap input samples */
00077     for (ch = 0; ch < s->channels; ch++) {
00078         const SampleType *sptr;
00079         int sinc;
00080 
00081         /* copy last 256 samples of previous frame to the start of the current frame */
00082         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_BLOCK_SIZE * s->num_blocks],
00083                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
00084 
00085         /* deinterleave */
00086         sinc = s->channels;
00087         sptr = samples + s->channel_map[ch];
00088         for (i = AC3_BLOCK_SIZE; i < AC3_BLOCK_SIZE * (s->num_blocks + 1); i++) {
00089             s->planar_samples[ch][i] = *sptr;
00090             sptr += sinc;
00091         }
00092     }
00093 }
00094 
00095 
00096 /*
00097  * Apply the MDCT to input samples to generate frequency coefficients.
00098  * This applies the KBD window and normalizes the input to reduce precision
00099  * loss due to fixed-point calculations.
00100  */
00101 static void apply_mdct(AC3EncodeContext *s)
00102 {
00103     int blk, ch;
00104 
00105     for (ch = 0; ch < s->channels; ch++) {
00106         for (blk = 0; blk < s->num_blocks; blk++) {
00107             AC3Block *block = &s->blocks[blk];
00108             const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
00109 
00110             apply_window(&s->dsp, s->windowed_samples, input_samples,
00111                          s->mdct_window, AC3_WINDOW_SIZE);
00112 
00113             if (s->fixed_point)
00114                 block->coeff_shift[ch+1] = normalize_samples(s);
00115 
00116             s->mdct.mdct_calcw(&s->mdct, block->mdct_coef[ch+1],
00117                                s->windowed_samples);
00118         }
00119     }
00120 }
00121 
00122 
00123 /*
00124  * Calculate coupling channel and coupling coordinates.
00125  */
00126 static void apply_channel_coupling(AC3EncodeContext *s)
00127 {
00128     LOCAL_ALIGNED_16(CoefType, cpl_coords,      [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
00129 #if CONFIG_AC3ENC_FLOAT
00130     LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
00131 #else
00132     int32_t (*fixed_cpl_coords)[AC3_MAX_CHANNELS][16] = cpl_coords;
00133 #endif
00134     int blk, ch, bnd, i, j;
00135     CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
00136     int cpl_start, num_cpl_coefs;
00137 
00138     memset(cpl_coords,       0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
00139 #if CONFIG_AC3ENC_FLOAT
00140     memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
00141 #endif
00142 
00143     /* align start to 16-byte boundary. align length to multiple of 32.
00144         note: coupling start bin % 4 will always be 1 */
00145     cpl_start     = s->start_freq[CPL_CH] - 1;
00146     num_cpl_coefs = FFALIGN(s->num_cpl_subbands * 12 + 1, 32);
00147     cpl_start     = FFMIN(256, cpl_start + num_cpl_coefs) - num_cpl_coefs;
00148 
00149     /* calculate coupling channel from fbw channels */
00150     for (blk = 0; blk < s->num_blocks; blk++) {
00151         AC3Block *block = &s->blocks[blk];
00152         CoefType *cpl_coef = &block->mdct_coef[CPL_CH][cpl_start];
00153         if (!block->cpl_in_use)
00154             continue;
00155         memset(cpl_coef, 0, num_cpl_coefs * sizeof(*cpl_coef));
00156         for (ch = 1; ch <= s->fbw_channels; ch++) {
00157             CoefType *ch_coef = &block->mdct_coef[ch][cpl_start];
00158             if (!block->channel_in_cpl[ch])
00159                 continue;
00160             for (i = 0; i < num_cpl_coefs; i++)
00161                 cpl_coef[i] += ch_coef[i];
00162         }
00163 
00164         /* coefficients must be clipped in order to be encoded */
00165         clip_coefficients(&s->dsp, cpl_coef, num_cpl_coefs);
00166     }
00167 
00168     /* calculate energy in each band in coupling channel and each fbw channel */
00169     /* TODO: possibly use SIMD to speed up energy calculation */
00170     bnd = 0;
00171     i = s->start_freq[CPL_CH];
00172     while (i < s->cpl_end_freq) {
00173         int band_size = s->cpl_band_sizes[bnd];
00174         for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
00175             for (blk = 0; blk < s->num_blocks; blk++) {
00176                 AC3Block *block = &s->blocks[blk];
00177                 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
00178                     continue;
00179                 for (j = 0; j < band_size; j++) {
00180                     CoefType v = block->mdct_coef[ch][i+j];
00181                     MAC_COEF(energy[blk][ch][bnd], v, v);
00182                 }
00183             }
00184         }
00185         i += band_size;
00186         bnd++;
00187     }
00188 
00189     /* calculate coupling coordinates for all blocks for all channels */
00190     for (blk = 0; blk < s->num_blocks; blk++) {
00191         AC3Block *block  = &s->blocks[blk];
00192         if (!block->cpl_in_use)
00193             continue;
00194         for (ch = 1; ch <= s->fbw_channels; ch++) {
00195             if (!block->channel_in_cpl[ch])
00196                 continue;
00197             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00198                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
00199                                                           energy[blk][CPL_CH][bnd]);
00200             }
00201         }
00202     }
00203 
00204     /* determine which blocks to send new coupling coordinates for */
00205     for (blk = 0; blk < s->num_blocks; blk++) {
00206         AC3Block *block  = &s->blocks[blk];
00207         AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
00208 
00209         memset(block->new_cpl_coords, 0, sizeof(block->new_cpl_coords));
00210 
00211         if (block->cpl_in_use) {
00212             /* send new coordinates if this is the first block, if previous
00213              * block did not use coupling but this block does, the channels
00214              * using coupling has changed from the previous block, or the
00215              * coordinate difference from the last block for any channel is
00216              * greater than a threshold value. */
00217             if (blk == 0 || !block0->cpl_in_use) {
00218                 for (ch = 1; ch <= s->fbw_channels; ch++)
00219                     block->new_cpl_coords[ch] = 1;
00220             } else {
00221                 for (ch = 1; ch <= s->fbw_channels; ch++) {
00222                     if (!block->channel_in_cpl[ch])
00223                         continue;
00224                     if (!block0->channel_in_cpl[ch]) {
00225                         block->new_cpl_coords[ch] = 1;
00226                     } else {
00227                         CoefSumType coord_diff = 0;
00228                         for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00229                             coord_diff += FFABS(cpl_coords[blk-1][ch][bnd] -
00230                                                 cpl_coords[blk  ][ch][bnd]);
00231                         }
00232                         coord_diff /= s->num_cpl_bands;
00233                         if (coord_diff > NEW_CPL_COORD_THRESHOLD)
00234                             block->new_cpl_coords[ch] = 1;
00235                     }
00236                 }
00237             }
00238         }
00239     }
00240 
00241     /* calculate final coupling coordinates, taking into account reusing of
00242        coordinates in successive blocks */
00243     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00244         blk = 0;
00245         while (blk < s->num_blocks) {
00246             int av_uninit(blk1);
00247             AC3Block *block  = &s->blocks[blk];
00248 
00249             if (!block->cpl_in_use) {
00250                 blk++;
00251                 continue;
00252             }
00253 
00254             for (ch = 1; ch <= s->fbw_channels; ch++) {
00255                 CoefSumType energy_ch, energy_cpl;
00256                 if (!block->channel_in_cpl[ch])
00257                     continue;
00258                 energy_cpl = energy[blk][CPL_CH][bnd];
00259                 energy_ch = energy[blk][ch][bnd];
00260                 blk1 = blk+1;
00261                 while (!s->blocks[blk1].new_cpl_coords[ch] && blk1 < s->num_blocks) {
00262                     if (s->blocks[blk1].cpl_in_use) {
00263                         energy_cpl += energy[blk1][CPL_CH][bnd];
00264                         energy_ch += energy[blk1][ch][bnd];
00265                     }
00266                     blk1++;
00267                 }
00268                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
00269             }
00270             blk = blk1;
00271         }
00272     }
00273 
00274     /* calculate exponents/mantissas for coupling coordinates */
00275     for (blk = 0; blk < s->num_blocks; blk++) {
00276         AC3Block *block = &s->blocks[blk];
00277         if (!block->cpl_in_use)
00278             continue;
00279 
00280 #if CONFIG_AC3ENC_FLOAT
00281         s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
00282                                    cpl_coords[blk][1],
00283                                    s->fbw_channels * 16);
00284 #endif
00285         s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
00286                                     fixed_cpl_coords[blk][1],
00287                                     s->fbw_channels * 16);
00288 
00289         for (ch = 1; ch <= s->fbw_channels; ch++) {
00290             int bnd, min_exp, max_exp, master_exp;
00291 
00292             if (!block->new_cpl_coords[ch])
00293                 continue;
00294 
00295             /* determine master exponent */
00296             min_exp = max_exp = block->cpl_coord_exp[ch][0];
00297             for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
00298                 int exp = block->cpl_coord_exp[ch][bnd];
00299                 min_exp = FFMIN(exp, min_exp);
00300                 max_exp = FFMAX(exp, max_exp);
00301             }
00302             master_exp = ((max_exp - 15) + 2) / 3;
00303             master_exp = FFMAX(master_exp, 0);
00304             while (min_exp < master_exp * 3)
00305                 master_exp--;
00306             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00307                 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
00308                                                         master_exp * 3, 0, 15);
00309             }
00310             block->cpl_master_exp[ch] = master_exp;
00311 
00312             /* quantize mantissas */
00313             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
00314                 int cpl_exp  = block->cpl_coord_exp[ch][bnd];
00315                 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
00316                 if (cpl_exp == 15)
00317                     cpl_mant >>= 1;
00318                 else
00319                     cpl_mant -= 16;
00320 
00321                 block->cpl_coord_mant[ch][bnd] = cpl_mant;
00322             }
00323         }
00324     }
00325 
00326     if (CONFIG_EAC3_ENCODER && s->eac3)
00327         ff_eac3_set_cpl_states(s);
00328 }
00329 
00330 
00331 /*
00332  * Determine rematrixing flags for each block and band.
00333  */
00334 static void compute_rematrixing_strategy(AC3EncodeContext *s)
00335 {
00336     int nb_coefs;
00337     int blk, bnd, i;
00338     AC3Block *block, *av_uninit(block0);
00339 
00340     if (s->channel_mode != AC3_CHMODE_STEREO)
00341         return;
00342 
00343     for (blk = 0; blk < s->num_blocks; blk++) {
00344         block = &s->blocks[blk];
00345         block->new_rematrixing_strategy = !blk;
00346 
00347         block->num_rematrixing_bands = 4;
00348         if (block->cpl_in_use) {
00349             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
00350             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
00351             if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
00352                 block->new_rematrixing_strategy = 1;
00353         }
00354         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
00355 
00356         if (!s->rematrixing_enabled) {
00357             block0 = block;
00358             continue;
00359         }
00360 
00361         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
00362             /* calculate calculate sum of squared coeffs for one band in one block */
00363             int start = ff_ac3_rematrix_band_tab[bnd];
00364             int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
00365             CoefSumType sum[4] = {0,};
00366             for (i = start; i < end; i++) {
00367                 CoefType lt = block->mdct_coef[1][i];
00368                 CoefType rt = block->mdct_coef[2][i];
00369                 CoefType md = lt + rt;
00370                 CoefType sd = lt - rt;
00371                 MAC_COEF(sum[0], lt, lt);
00372                 MAC_COEF(sum[1], rt, rt);
00373                 MAC_COEF(sum[2], md, md);
00374                 MAC_COEF(sum[3], sd, sd);
00375             }
00376 
00377             /* compare sums to determine if rematrixing will be used for this band */
00378             if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
00379                 block->rematrixing_flags[bnd] = 1;
00380             else
00381                 block->rematrixing_flags[bnd] = 0;
00382 
00383             /* determine if new rematrixing flags will be sent */
00384             if (blk &&
00385                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
00386                 block->new_rematrixing_strategy = 1;
00387             }
00388         }
00389         block0 = block;
00390     }
00391 }
00392 
00393 
00394 int AC3_NAME(encode_frame)(AVCodecContext *avctx, unsigned char *frame,
00395                            int buf_size, void *data)
00396 {
00397     AC3EncodeContext *s = avctx->priv_data;
00398     const SampleType *samples = data;
00399     int ret;
00400 
00401     if (s->options.allow_per_frame_metadata) {
00402         ret = ff_ac3_validate_metadata(s);
00403         if (ret)
00404             return ret;
00405     }
00406 
00407     if (s->bit_alloc.sr_code == 1 || s->eac3)
00408         ff_ac3_adjust_frame_size(s);
00409 
00410     deinterleave_input_samples(s, samples);
00411 
00412     apply_mdct(s);
00413 
00414     if (s->fixed_point)
00415         scale_coefficients(s);
00416 
00417     clip_coefficients(&s->dsp, s->blocks[0].mdct_coef[1],
00418                       AC3_MAX_COEFS * s->num_blocks * s->channels);
00419 
00420     s->cpl_on = s->cpl_enabled;
00421     ff_ac3_compute_coupling_strategy(s);
00422 
00423     if (s->cpl_on)
00424         apply_channel_coupling(s);
00425 
00426     compute_rematrixing_strategy(s);
00427 
00428     if (!s->fixed_point)
00429         scale_coefficients(s);
00430 
00431     ff_ac3_apply_rematrixing(s);
00432 
00433     ff_ac3_process_exponents(s);
00434 
00435     ret = ff_ac3_compute_bit_allocation(s);
00436     if (ret) {
00437         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
00438         return ret;
00439     }
00440 
00441     ff_ac3_group_exponents(s);
00442 
00443     ff_ac3_quantize_mantissas(s);
00444 
00445     ff_ac3_output_frame(s, frame);
00446 
00447     return s->frame_size;
00448 }