ac3enc.c 58.3 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * The simplest AC-3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard
4 5
 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
Fabrice Bellard's avatar
Fabrice Bellard committed
6
 *
7 8 9
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
10 11
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 *
14
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
16 17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
18
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
19
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with FFmpeg; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
22
 */
Michael Niedermayer's avatar
Michael Niedermayer committed
23 24

/**
25
 * @file
26
 * The simplest AC-3 encoder.
Michael Niedermayer's avatar
Michael Niedermayer committed
27
 */
28

Fabrice Bellard's avatar
Fabrice Bellard committed
29
//#define DEBUG
30
//#define ASSERT_LEVEL 2
31

32
#include "libavutil/audioconvert.h"
33
#include "libavutil/avassert.h"
34
#include "libavutil/crc.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
35
#include "avcodec.h"
36
#include "put_bits.h"
37
#include "dsputil.h"
38
#include "ac3dsp.h"
39
#include "ac3.h"
40
#include "audioconvert.h"
41

42

43 44 45 46 47
#ifndef CONFIG_AC3ENC_FLOAT
#define CONFIG_AC3ENC_FLOAT 0
#endif


48 49 50
/** Maximum number of exponent groups. +1 for separate DC exponent. */
#define AC3_MAX_EXP_GROUPS 85

51 52 53 54 55 56
/* stereo rematrixing algorithms */
#define AC3_REMATRIXING_IS_STATIC 0x1
#define AC3_REMATRIXING_SUMS    0
#define AC3_REMATRIXING_NONE    1
#define AC3_REMATRIXING_ALWAYS  3

57
/** Scale a float value by 2^bits and convert to an integer. */
Justin Ruggles's avatar
Justin Ruggles committed
58 59
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))

60

61 62 63
#if CONFIG_AC3ENC_FLOAT
#include "ac3enc_float.h"
#else
64
#include "ac3enc_fixed.h"
65
#endif
66

67

68 69 70 71
/**
 * Data for a single audio block.
 */
typedef struct AC3Block {
72
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
73
    CoefType **mdct_coef;                       ///< MDCT coefficients
74
    int32_t  **fixed_coef;                      ///< fixed-point MDCT coefficients
75 76 77 78 79 80
    uint8_t  **exp;                             ///< original exponents
    uint8_t  **grouped_exp;                     ///< grouped exponents
    int16_t  **psd;                             ///< psd per frequency bin
    int16_t  **band_psd;                        ///< psd per critical band
    int16_t  **mask;                            ///< masking curve
    uint16_t **qmant;                           ///< quantized mantissas
81
    uint8_t  coeff_shift[AC3_MAX_CHANNELS];     ///< fixed-point coefficient shift values
82 83
    uint8_t  new_rematrixing_strategy;          ///< send new rematrixing flags in this block
    uint8_t  rematrixing_flags[4];              ///< rematrixing flags
84 85
} AC3Block;

86 87 88
/**
 * AC-3 encoder private context.
 */
89
typedef struct AC3EncodeContext {
90
    PutBitContext pb;                       ///< bitstream writer context
91
    DSPContext dsp;
92
    AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
93
    AC3MDCTContext mdct;                    ///< MDCT context
94

95 96
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info

97 98
    int bitstream_id;                       ///< bitstream id                           (bsid)
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
99

100 101
    int bit_rate;                           ///< target bit rate, in bits-per-second
    int sample_rate;                        ///< sampling frequency, in Hz
102

103
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
104
    int frame_size;                         ///< current frame size in bytes
105
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
106
    uint16_t crc_inv[2];
107 108
    int bits_written;                       ///< bit count    (used to avg. bitrate)
    int samples_written;                    ///< sample count (used to avg. bitrate)
109

110 111 112 113 114 115
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
    int channels;                           ///< total number of channels               (nchans)
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
    int lfe_channel;                        ///< channel index of the LFE channel
    int channel_mode;                       ///< channel mode                           (acmod)
    const uint8_t *channel_map;             ///< channel map used to reorder channels
116

117
    int cutoff;                             ///< user-specified cutoff frequency, in Hz
118
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
119
    int nb_coefs[AC3_MAX_CHANNELS];
120

121
    int rematrixing;                        ///< determines how rematrixing strategy is calculated
122
    int num_rematrixing_bands;              ///< number of rematrixing bands
123

124
    /* bitrate allocation control */
125 126 127 128 129 130 131 132 133
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
    int floor_code;                         ///< floor code                             (floorcod)
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
134
    int frame_bits_fixed;                   ///< number of non-coefficient bits for fixed parameters
135 136
    int frame_bits;                         ///< all frame bits except exponents and mantissas
    int exponent_bits;                      ///< number of bits used for exponents
137

138
    /* mantissa encoding */
139
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
140
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
141

142
    SampleType **planar_samples;
143 144
    uint8_t *bap_buffer;
    uint8_t *bap1_buffer;
145
    CoefType *mdct_coef_buffer;
146
    int32_t *fixed_coef_buffer;
147 148 149 150 151 152
    uint8_t *exp_buffer;
    uint8_t *grouped_exp_buffer;
    int16_t *psd_buffer;
    int16_t *band_psd_buffer;
    int16_t *mask_buffer;
    uint16_t *qmant_buffer;
153

154 155
    uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies

156
    DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
157
} AC3EncodeContext;
Fabrice Bellard's avatar
Fabrice Bellard committed
158

159

160
/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
161 162 163 164 165 166 167 168

static av_cold void mdct_end(AC3MDCTContext *mdct);

static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
                             int nbits);

static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);

169
static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
170 171 172 173
                         const SampleType *window, int n);

static int normalize_samples(AC3EncodeContext *s);

174 175
static void scale_coefficients(AC3EncodeContext *s);

176

177 178 179 180
/**
 * LUT for number of exponent groups.
 * exponent_group_tab[exponent strategy-1][number of coefficients]
 */
181
static uint8_t exponent_group_tab[3][256];
182

183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/**
 * List of supported channel layouts.
 */
static const int64_t ac3_channel_layouts[] = {
     AV_CH_LAYOUT_MONO,
     AV_CH_LAYOUT_STEREO,
     AV_CH_LAYOUT_2_1,
     AV_CH_LAYOUT_SURROUND,
     AV_CH_LAYOUT_2_2,
     AV_CH_LAYOUT_QUAD,
     AV_CH_LAYOUT_4POINT0,
     AV_CH_LAYOUT_5POINT0,
     AV_CH_LAYOUT_5POINT0_BACK,
    (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
    (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
     AV_CH_LAYOUT_5POINT1,
     AV_CH_LAYOUT_5POINT1_BACK,
     0
};


210 211 212 213 214 215 216 217 218 219
/**
 * Adjust the frame size to make the average bit rate match the target bit rate.
 * This is only needed for 11025, 22050, and 44100 sample rates.
 */
static void adjust_frame_size(AC3EncodeContext *s)
{
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
        s->bits_written    -= s->bit_rate;
        s->samples_written -= s->sample_rate;
    }
220 221
    s->frame_size = s->frame_size_min +
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
222 223 224 225 226
    s->bits_written    += s->frame_size * 8;
    s->samples_written += AC3_FRAME_SIZE;
}


227 228 229 230 231
/**
 * Deinterleave input samples.
 * Channels are reordered from FFmpeg's default order to AC-3 order.
 */
static void deinterleave_input_samples(AC3EncodeContext *s,
232
                                       const SampleType *samples)
233 234 235 236 237
{
    int ch, i;

    /* deinterleave and remap input samples */
    for (ch = 0; ch < s->channels; ch++) {
238
        const SampleType *sptr;
239 240 241
        int sinc;

        /* copy last 256 samples of previous frame to the start of the current frame */
242
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
243
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
244 245 246 247 248

        /* deinterleave */
        sinc = s->channels;
        sptr = samples + s->channel_map[ch];
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
249
            s->planar_samples[ch][i] = *sptr;
250 251 252 253 254 255
            sptr += sinc;
        }
    }
}


256 257 258 259 260
/**
 * Apply the MDCT to input samples to generate frequency coefficients.
 * This applies the KBD window and normalizes the input to reduce precision
 * loss due to fixed-point calculations.
 */
261
static void apply_mdct(AC3EncodeContext *s)
262 263 264 265 266
{
    int blk, ch;

    for (ch = 0; ch < s->channels; ch++) {
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
267
            AC3Block *block = &s->blocks[blk];
268
            const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
269

270
            apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
271

272
            block->coeff_shift[ch] = normalize_samples(s);
273

274
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
275 276 277 278 279
        }
    }
}


280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
/**
 * Initialize stereo rematrixing.
 * If the strategy does not change for each frame, set the rematrixing flags.
 */
static void rematrixing_init(AC3EncodeContext *s)
{
    if (s->channel_mode == AC3_CHMODE_STEREO)
        s->rematrixing = AC3_REMATRIXING_SUMS;
    else
        s->rematrixing = AC3_REMATRIXING_NONE;
    /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
             the future in conjunction with channel coupling. */

    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
        int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
        s->blocks[0].new_rematrixing_strategy = 1;
        memset(s->blocks[0].rematrixing_flags, flag,
               sizeof(s->blocks[0].rematrixing_flags));
    }
}


/**
 * Determine rematrixing flags for each block and band.
 */
static void compute_rematrixing_strategy(AC3EncodeContext *s)
{
    int nb_coefs;
    int blk, bnd, i;
    AC3Block *block, *block0;

311 312
    s->num_rematrixing_bands = 4;

313 314 315 316 317 318 319
    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
        return;

    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
        block = &s->blocks[blk];
320
        block->new_rematrixing_strategy = !blk;
321
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
322 323 324 325 326 327 328 329 330
            /* calculate calculate sum of squared coeffs for one band in one block */
            int start = ff_ac3_rematrix_band_tab[bnd];
            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
            CoefSumType sum[4] = {0,};
            for (i = start; i < end; i++) {
                CoefType lt = block->mdct_coef[0][i];
                CoefType rt = block->mdct_coef[1][i];
                CoefType md = lt + rt;
                CoefType sd = lt - rt;
331 332 333 334
                MAC_COEF(sum[0], lt, lt);
                MAC_COEF(sum[1], rt, rt);
                MAC_COEF(sum[2], md, md);
                MAC_COEF(sum[3], sd, sd);
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
            }

            /* compare sums to determine if rematrixing will be used for this band */
            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
                block->rematrixing_flags[bnd] = 1;
            else
                block->rematrixing_flags[bnd] = 0;

            /* determine if new rematrixing flags will be sent */
            if (blk &&
                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
                block->new_rematrixing_strategy = 1;
            }
        }
        block0 = block;
    }
}


/**
 * Apply stereo rematrixing to coefficients based on rematrixing flags.
 */
static void apply_rematrixing(AC3EncodeContext *s)
{
    int nb_coefs;
    int blk, bnd, i;
    int start, end;
    uint8_t *flags;

    if (s->rematrixing == AC3_REMATRIXING_NONE)
        return;

    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
        AC3Block *block = &s->blocks[blk];
        if (block->new_rematrixing_strategy)
            flags = block->rematrixing_flags;
373
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            if (flags[bnd]) {
                start = ff_ac3_rematrix_band_tab[bnd];
                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
                for (i = start; i < end; i++) {
                    int32_t lt = block->fixed_coef[0][i];
                    int32_t rt = block->fixed_coef[1][i];
                    block->fixed_coef[0][i] = (lt + rt) >> 1;
                    block->fixed_coef[1][i] = (lt - rt) >> 1;
                }
            }
        }
    }
}


389 390 391 392 393 394 395 396 397 398 399
/**
 * Initialize exponent tables.
 */
static av_cold void exponent_init(AC3EncodeContext *s)
{
    int i;
    for (i = 73; i < 256; i++) {
        exponent_group_tab[0][i] = (i - 1) /  3;
        exponent_group_tab[1][i] = (i + 2) /  6;
        exponent_group_tab[2][i] = (i + 8) / 12;
    }
400 401
    /* LFE */
    exponent_group_tab[0][7] = 2;
402 403 404
}


405 406 407 408 409
/**
 * Extract exponents from the MDCT coefficients.
 * This takes into account the normalization that was done to the input samples
 * by adjusting the exponents by the exponent shift values.
 */
410
static void extract_exponents(AC3EncodeContext *s)
411 412 413 414 415
{
    int blk, ch, i;

    for (ch = 0; ch < s->channels; ch++) {
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
416
            AC3Block *block = &s->blocks[blk];
417
            uint8_t *exp   = block->exp[ch];
418
            int32_t *coef = block->fixed_coef[ch];
419 420
            for (i = 0; i < AC3_MAX_COEFS; i++) {
                int e;
421
                int v = abs(coef[i]);
422 423 424
                if (v == 0)
                    e = 24;
                else {
425
                    e = 23 - av_log2(v);
426 427
                    if (e >= 24) {
                        e = 24;
428
                        coef[i] = 0;
429
                    }
Justin Ruggles's avatar
Justin Ruggles committed
430
                    av_assert2(e >= 0);
431
                }
432
                exp[i] = e;
433 434 435 436 437 438
            }
        }
    }
}


439 440 441 442
/**
 * Exponent Difference Threshold.
 * New exponents are sent if their SAD exceed this number.
 */
443
#define EXP_DIFF_THRESHOLD 500
444

445

446 447 448
/**
 * Calculate exponent strategies for all blocks in a single channel.
 */
449
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
450
                                    uint8_t *exp)
Fabrice Bellard's avatar
Fabrice Bellard committed
451
{
452
    int blk, blk1;
Fabrice Bellard's avatar
Fabrice Bellard committed
453
    int exp_diff;
454

Fabrice Bellard's avatar
Fabrice Bellard committed
455 456
    /* estimate if the exponent variation & decide if they should be
       reused in the next frame */
457
    exp_strategy[0] = EXP_NEW;
458
    exp += AC3_MAX_COEFS;
459
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
460
        exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
Fabrice Bellard's avatar
Fabrice Bellard committed
461
        if (exp_diff > EXP_DIFF_THRESHOLD)
462
            exp_strategy[blk] = EXP_NEW;
Fabrice Bellard's avatar
Fabrice Bellard committed
463
        else
464
            exp_strategy[blk] = EXP_REUSE;
465
        exp += AC3_MAX_COEFS;
Fabrice Bellard's avatar
Fabrice Bellard committed
466
    }
467

Fabrice Bellard's avatar
Fabrice Bellard committed
468 469
    /* now select the encoding strategy type : if exponents are often
       recoded, we use a coarse encoding */
470 471 472
    blk = 0;
    while (blk < AC3_MAX_BLOCKS) {
        blk1 = blk + 1;
473
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
474 475
            blk1++;
        switch (blk1 - blk) {
476
        case 1:  exp_strategy[blk] = EXP_D45; break;
Fabrice Bellard's avatar
Fabrice Bellard committed
477
        case 2:
478 479
        case 3:  exp_strategy[blk] = EXP_D25; break;
        default: exp_strategy[blk] = EXP_D15; break;
Fabrice Bellard's avatar
Fabrice Bellard committed
480
        }
481
        blk = blk1;
Fabrice Bellard's avatar
Fabrice Bellard committed
482 483 484
    }
}

485

486 487
/**
 * Calculate exponent strategies for all channels.
488
 * Array arrangement is reversed to simplify the per-channel calculation.
489
 */
490
static void compute_exp_strategy(AC3EncodeContext *s)
491
{
492
    int ch, blk;
493

494
    for (ch = 0; ch < s->fbw_channels; ch++) {
495
        compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
496 497 498
    }
    if (s->lfe_on) {
        ch = s->lfe_channel;
499
        s->exp_strategy[ch][0] = EXP_D15;
500
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
501
            s->exp_strategy[ch][blk] = EXP_REUSE;
502 503 504 505
    }
}


506 507 508
/**
 * Update the exponents so that they are the ones the decoder will decode.
 */
509
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
Fabrice Bellard's avatar
Fabrice Bellard committed
510
{
511
    int nb_groups, i, k;
Fabrice Bellard's avatar
Fabrice Bellard committed
512

513
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
Fabrice Bellard's avatar
Fabrice Bellard committed
514 515

    /* for each group, compute the minimum exponent */
516 517 518 519 520 521 522 523
    switch(exp_strategy) {
    case EXP_D25:
        for (i = 1, k = 1; i <= nb_groups; i++) {
            uint8_t exp_min = exp[k];
            if (exp[k+1] < exp_min)
                exp_min = exp[k+1];
            exp[i] = exp_min;
            k += 2;
Fabrice Bellard's avatar
Fabrice Bellard committed
524
        }
525 526 527 528 529 530 531 532 533 534 535 536 537 538
        break;
    case EXP_D45:
        for (i = 1, k = 1; i <= nb_groups; i++) {
            uint8_t exp_min = exp[k];
            if (exp[k+1] < exp_min)
                exp_min = exp[k+1];
            if (exp[k+2] < exp_min)
                exp_min = exp[k+2];
            if (exp[k+3] < exp_min)
                exp_min = exp[k+3];
            exp[i] = exp_min;
            k += 4;
        }
        break;
539
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
540 541

    /* constraint for DC exponent */
542 543
    if (exp[0] > 15)
        exp[0] = 15;
Fabrice Bellard's avatar
Fabrice Bellard committed
544

545 546 547
    /* decrease the delta between each groups to within 2 so that they can be
       differentially encoded */
    for (i = 1; i <= nb_groups; i++)
548
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
549 550
    i--;
    while (--i >= 0)
551
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
552

Fabrice Bellard's avatar
Fabrice Bellard committed
553
    /* now we have the exponent values the decoder will see */
554 555 556 557 558 559 560 561 562 563 564 565 566 567
    switch (exp_strategy) {
    case EXP_D25:
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
            uint8_t exp1 = exp[i];
            exp[k--] = exp1;
            exp[k--] = exp1;
        }
        break;
    case EXP_D45:
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
            k -= 4;
        }
        break;
Fabrice Bellard's avatar
Fabrice Bellard committed
568 569 570
    }
}

571

572 573 574 575 576 577
/**
 * Encode exponents from original extracted form to what the decoder will see.
 * This copies and groups exponents based on exponent strategy and reduces
 * deltas between adjacent exponent groups so that they can be differentially
 * encoded.
 */
578
static void encode_exponents(AC3EncodeContext *s)
579
{
580 581
    int blk, blk1, ch;
    uint8_t *exp, *exp1, *exp_strategy;
582
    int nb_coefs, num_reuse_blocks;
583 584

    for (ch = 0; ch < s->channels; ch++) {
585 586 587 588
        exp          = s->blocks[0].exp[ch];
        exp_strategy = s->exp_strategy[ch];
        nb_coefs     = s->nb_coefs[ch];

589 590 591
        blk = 0;
        while (blk < AC3_MAX_BLOCKS) {
            blk1 = blk + 1;
592 593

            /* count the number of EXP_REUSE blocks after the current block */
594
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
595
                blk1++;
596 597 598
            num_reuse_blocks = blk1 - blk - 1;

            /* for the EXP_REUSE case we select the min of the exponents */
599
            s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
600

601 602
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);

603
            /* copy encoded exponents for reuse case */
604 605 606 607 608
            exp1 = exp + AC3_MAX_COEFS;
            while (blk < blk1-1) {
                memcpy(exp1, exp, nb_coefs * sizeof(*exp));
                exp1 += AC3_MAX_COEFS;
                blk++;
609 610
            }
            blk = blk1;
611
            exp = exp1;
612 613
        }
    }
614 615 616 617 618 619 620 621
}


/**
 * Group exponents.
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
 * varies depending on exponent strategy and bandwidth.
 */
622
static void group_exponents(AC3EncodeContext *s)
623 624
{
    int blk, ch, i;
625
    int group_size, nb_groups, bit_count;
626 627 628 629 630 631
    uint8_t *p;
    int delta0, delta1, delta2;
    int exp0, exp1;

    bit_count = 0;
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
632
        AC3Block *block = &s->blocks[blk];
633
        for (ch = 0; ch < s->channels; ch++) {
634 635
            int exp_strategy = s->exp_strategy[ch][blk];
            if (exp_strategy == EXP_REUSE)
636
                continue;
637 638
            group_size = exp_strategy + (exp_strategy == EXP_D45);
            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
639
            bit_count += 4 + (nb_groups * 7);
640
            p = block->exp[ch];
641 642 643

            /* DC exponent */
            exp1 = *p++;
644
            block->grouped_exp[ch][0] = exp1;
645 646

            /* remaining exponents are delta encoded */
647
            for (i = 1; i <= nb_groups; i++) {
648 649 650 651 652
                /* merge three delta in one code */
                exp0   = exp1;
                exp1   = p[0];
                p     += group_size;
                delta0 = exp1 - exp0 + 2;
Justin Ruggles's avatar
Justin Ruggles committed
653
                av_assert2(delta0 >= 0 && delta0 <= 4);
654 655 656 657 658

                exp0   = exp1;
                exp1   = p[0];
                p     += group_size;
                delta1 = exp1 - exp0 + 2;
Justin Ruggles's avatar
Justin Ruggles committed
659
                av_assert2(delta1 >= 0 && delta1 <= 4);
660 661 662 663 664

                exp0   = exp1;
                exp1   = p[0];
                p     += group_size;
                delta2 = exp1 - exp0 + 2;
Justin Ruggles's avatar
Justin Ruggles committed
665
                av_assert2(delta2 >= 0 && delta2 <= 4);
666

667
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
668 669 670
            }
        }
    }
671

672
    s->exponent_bits = bit_count;
673 674 675 676 677 678 679 680
}


/**
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
 * and encode final exponents.
 */
681
static void process_exponents(AC3EncodeContext *s)
682
{
683
    extract_exponents(s);
684

685
    compute_exp_strategy(s);
686

687
    encode_exponents(s);
688

689
    group_exponents(s);
690 691

    emms_c();
692 693 694
}


695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
/**
 * Count frame bits that are based solely on fixed parameters.
 * This only has to be run once when the encoder is initialized.
 */
static void count_frame_bits_fixed(AC3EncodeContext *s)
{
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
    int blk;
    int frame_bits;

    /* assumptions:
     *   no dynamic range codes
     *   no channel coupling
     *   bit allocation parameters do not change between blocks
     *   SNR offsets do not change between blocks
     *   no delta bit allocation
     *   no skipped data
     *   no auxilliary data
     */

    /* header size */
    frame_bits = 65;
    frame_bits += frame_bits_inc[s->channel_mode];

    /* audio blocks */
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
        if (s->channel_mode == AC3_CHMODE_STEREO) {
            frame_bits++; /* rematstr */
        }
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
        if (s->lfe_on)
            frame_bits++; /* lfeexpstr */
        frame_bits++; /* baie */
        frame_bits++; /* snr */
        frame_bits += 2; /* delta / skip */
    }
    frame_bits++; /* cplinu for block 0 */
    /* bit alloc info */
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
    /* csnroffset[6] */
    /* (fsnoffset[4] + fgaincod[4]) * c */
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);

    /* auxdatae, crcrsv */
    frame_bits += 2;

    /* CRC */
    frame_bits += 16;

    s->frame_bits_fixed = frame_bits;
}


749 750 751 752 753 754 755 756 757 758 759 760
/**
 * Initialize bit allocation.
 * Set default parameter codes and calculate parameter values.
 */
static void bit_alloc_init(AC3EncodeContext *s)
{
    int ch;

    /* init default parameters */
    s->slow_decay_code = 2;
    s->fast_decay_code = 1;
    s->slow_gain_code  = 1;
761
    s->db_per_bit_code = 3;
762
    s->floor_code      = 7;
763 764 765 766 767 768 769 770 771 772 773 774 775 776
    for (ch = 0; ch < s->channels; ch++)
        s->fast_gain_code[ch] = 4;

    /* initial snr offset */
    s->coarse_snr_offset = 40;

    /* compute real values */
    /* currently none of these values change during encoding, so we can just
       set them once at initialization */
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
777 778

    count_frame_bits_fixed(s);
779 780 781
}


782 783
/**
 * Count the bits used to encode the frame, minus exponents and mantissas.
784 785
 * Bits based on fixed parameters have already been counted, so now we just
 * have to add the bits based on parameters that change during encoding.
786
 */
787
static void count_frame_bits(AC3EncodeContext *s)
788 789
{
    int blk, ch;
790
    int frame_bits = 0;
791 792

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
793 794 795
        /* stereo rematrixing */
        if (s->channel_mode == AC3_CHMODE_STEREO &&
            s->blocks[blk].new_rematrixing_strategy) {
796
            frame_bits += s->num_rematrixing_bands;
797 798
        }

799
        for (ch = 0; ch < s->fbw_channels; ch++) {
800
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
801 802 803
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
        }
    }
804
    s->frame_bits = s->frame_bits_fixed + frame_bits;
805 806 807
}


808 809 810
/**
 * Calculate the number of bits needed to encode a set of mantissas.
 */
811
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
Fabrice Bellard's avatar
Fabrice Bellard committed
812
{
813
    int bits, b, i;
Fabrice Bellard's avatar
Fabrice Bellard committed
814 815

    bits = 0;
816
    for (i = 0; i < nb_coefs; i++) {
817
        b = bap[i];
818 819 820 821 822
        if (b <= 4) {
            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
            mant_cnt[b]++;
        } else if (b <= 13) {
            // bap=5 to bap=13 use (bap-1) bits
823
            bits += b - 1;
824 825 826
        } else {
            // bap=14 uses 14 bits and bap=15 uses 16 bits
            bits += (b == 14) ? 14 : 16;
Fabrice Bellard's avatar
Fabrice Bellard committed
827 828 829 830 831 832
        }
    }
    return bits;
}


833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
/**
 * Finalize the mantissa bit count by adding in the grouped mantissas.
 */
static int compute_mantissa_size_final(int mant_cnt[5])
{
    // bap=1 : 3 mantissas in 5 bits
    int bits = (mant_cnt[1] / 3) * 5;
    // bap=2 : 3 mantissas in 7 bits
    // bap=4 : 2 mantissas in 7 bits
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
    // bap=3 : each mantissa is 3 bits
    bits += mant_cnt[3] * 3;
    return bits;
}


849 850 851 852
/**
 * Calculate masking curve based on the final exponents.
 * Also calculate the power spectral densities to use in future calculations.
 */
853
static void bit_alloc_masking(AC3EncodeContext *s)
854 855 856
{
    int blk, ch;

857
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
858
        AC3Block *block = &s->blocks[blk];
859
        for (ch = 0; ch < s->channels; ch++) {
860 861 862
            /* We only need psd and mask for calculating bap.
               Since we currently do not calculate bap when exponent
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
863
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
864
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
865
                                          s->nb_coefs[ch],
866 867
                                          block->psd[ch], block->band_psd[ch]);
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
868
                                           0, s->nb_coefs[ch],
869
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
870
                                           ch == s->lfe_channel,
871
                                           DBA_NONE, 0, NULL, NULL, NULL,
872
                                           block->mask[ch]);
873 874 875 876 877
            }
        }
    }
}

878

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
/**
 * Ensure that bap for each block and channel point to the current bap_buffer.
 * They may have been switched during the bit allocation search.
 */
static void reset_block_bap(AC3EncodeContext *s)
{
    int blk, ch;
    if (s->blocks[0].bap[0] == s->bap_buffer)
        return;
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
        for (ch = 0; ch < s->channels; ch++) {
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
        }
    }
}


896 897 898 899
/**
 * Run the bit allocation with a given SNR offset.
 * This calculates the bit allocation pointers that will be used to determine
 * the quantization of each mantissa.
900 901
 * @return the number of bits needed for mantissas if the given SNR offset is
 *         is used.
902
 */
903
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
Fabrice Bellard's avatar
Fabrice Bellard committed
904
{
905
    int blk, ch;
906
    int mantissa_bits;
907
    int mant_cnt[5];
Justin Ruggles's avatar
Justin Ruggles committed
908

Justin Ruggles's avatar