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