Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 9c84a72a

History | View | Annotate | Download (63 KB)

1
/*
2
 * The simplest AC-3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard
4
 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5
 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6
 *
7
 * This file is part of FFmpeg.
8
 *
9
 * FFmpeg is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * FFmpeg is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
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
22
 */
23

    
24
/**
25
 * @file
26
 * The simplest AC-3 encoder.
27
 */
28

    
29
//#define DEBUG
30

    
31
#include "libavcore/audioconvert.h"
32
#include "libavutil/crc.h"
33
#include "avcodec.h"
34
#include "put_bits.h"
35
#include "dsputil.h"
36
#include "ac3.h"
37
#include "audioconvert.h"
38

    
39

    
40
/** Maximum number of exponent groups. +1 for separate DC exponent. */
41
#define AC3_MAX_EXP_GROUPS 85
42

    
43
/** Scale a float value by 2^bits and convert to an integer. */
44
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
45

    
46
typedef int16_t SampleType;
47
typedef int32_t CoefType;
48

    
49
#define SCALE_COEF(a) (a)
50

    
51
/** Scale a float value by 2^15, convert to an integer, and clip to range -32767..32767. */
52
#define FIX15(a) av_clip(SCALE_FLOAT(a, 15), -32767, 32767)
53

    
54

    
55
/**
56
 * Compex number.
57
 * Used in fixed-point MDCT calculation.
58
 */
59
typedef struct IComplex {
60
    int16_t re,im;
61
} IComplex;
62

    
63
typedef struct AC3MDCTContext {
64
    const int16_t *window;                  ///< MDCT window function
65
    int nbits;                              ///< log2(transform size)
66
    int16_t *costab;                        ///< FFT cos table
67
    int16_t *sintab;                        ///< FFT sin table
68
    int16_t *xcos1;                         ///< MDCT cos table
69
    int16_t *xsin1;                         ///< MDCT sin table
70
    int16_t *rot_tmp;                       ///< temp buffer for pre-rotated samples
71
    IComplex *cplx_tmp;                     ///< temp buffer for complex pre-rotated samples
72
} AC3MDCTContext;
73

    
74
/**
75
 * Data for a single audio block.
76
 */
77
typedef struct AC3Block {
78
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
79
    CoefType **mdct_coef;                       ///< MDCT coefficients
80
    uint8_t  **exp;                             ///< original exponents
81
    uint8_t  **grouped_exp;                     ///< grouped exponents
82
    int16_t  **psd;                             ///< psd per frequency bin
83
    int16_t  **band_psd;                        ///< psd per critical band
84
    int16_t  **mask;                            ///< masking curve
85
    uint16_t **qmant;                           ///< quantized mantissas
86
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];    ///< exponent strategies
87
    int8_t   exp_shift[AC3_MAX_CHANNELS];       ///< exponent shift values
88
} AC3Block;
89

    
90
/**
91
 * AC-3 encoder private context.
92
 */
93
typedef struct AC3EncodeContext {
94
    PutBitContext pb;                       ///< bitstream writer context
95
    DSPContext dsp;
96
    AC3MDCTContext mdct;                    ///< MDCT context
97

    
98
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
99

    
100
    int bitstream_id;                       ///< bitstream id                           (bsid)
101
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
102

    
103
    int bit_rate;                           ///< target bit rate, in bits-per-second
104
    int sample_rate;                        ///< sampling frequency, in Hz
105

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

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

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

    
124
    /* bitrate allocation control */
125
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
126
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
127
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
128
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
129
    int floor_code;                         ///< floor code                             (floorcod)
130
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
131
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
132
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
133
    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
    int frame_bits;                         ///< all frame bits except exponents and mantissas
136
    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
    uint8_t *bap_buffer;
144
    uint8_t *bap1_buffer;
145
    CoefType *mdct_coef_buffer;
146
    uint8_t *exp_buffer;
147
    uint8_t *grouped_exp_buffer;
148
    int16_t *psd_buffer;
149
    int16_t *band_psd_buffer;
150
    int16_t *mask_buffer;
151
    uint16_t *qmant_buffer;
152

    
153
    DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
154
} AC3EncodeContext;
155

    
156

    
157
/**
158
 * LUT for number of exponent groups.
159
 * exponent_group_tab[exponent strategy-1][number of coefficients]
160
 */
161
static uint8_t exponent_group_tab[3][256];
162

    
163

    
164
/**
165
 * List of supported channel layouts.
166
 */
167
static const int64_t ac3_channel_layouts[] = {
168
     AV_CH_LAYOUT_MONO,
169
     AV_CH_LAYOUT_STEREO,
170
     AV_CH_LAYOUT_2_1,
171
     AV_CH_LAYOUT_SURROUND,
172
     AV_CH_LAYOUT_2_2,
173
     AV_CH_LAYOUT_QUAD,
174
     AV_CH_LAYOUT_4POINT0,
175
     AV_CH_LAYOUT_5POINT0,
176
     AV_CH_LAYOUT_5POINT0_BACK,
177
    (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
178
    (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
179
    (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
180
    (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
181
    (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
182
    (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
183
    (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
184
     AV_CH_LAYOUT_5POINT1,
185
     AV_CH_LAYOUT_5POINT1_BACK,
186
     0
187
};
188

    
189

    
190
/**
191
 * Adjust the frame size to make the average bit rate match the target bit rate.
192
 * This is only needed for 11025, 22050, and 44100 sample rates.
193
 */
194
static void adjust_frame_size(AC3EncodeContext *s)
195
{
196
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
197
        s->bits_written    -= s->bit_rate;
198
        s->samples_written -= s->sample_rate;
199
    }
200
    s->frame_size = s->frame_size_min +
201
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
202
    s->bits_written    += s->frame_size * 8;
203
    s->samples_written += AC3_FRAME_SIZE;
204
}
205

    
206

    
207
/**
208
 * Deinterleave input samples.
209
 * Channels are reordered from FFmpeg's default order to AC-3 order.
210
 */
211
static void deinterleave_input_samples(AC3EncodeContext *s,
212
                                       const SampleType *samples)
213
{
214
    int ch, i;
215

    
216
    /* deinterleave and remap input samples */
217
    for (ch = 0; ch < s->channels; ch++) {
218
        const SampleType *sptr;
219
        int sinc;
220

    
221
        /* copy last 256 samples of previous frame to the start of the current frame */
222
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
223
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
224

    
225
        /* deinterleave */
226
        sinc = s->channels;
227
        sptr = samples + s->channel_map[ch];
228
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
229
            s->planar_samples[ch][i] = *sptr;
230
            sptr += sinc;
231
        }
232
    }
233
}
234

    
235

    
236
/**
237
 * Finalize MDCT and free allocated memory.
238
 */
239
static av_cold void mdct_end(AC3MDCTContext *mdct)
240
{
241
    mdct->nbits = 0;
242
    av_freep(&mdct->costab);
243
    av_freep(&mdct->sintab);
244
    av_freep(&mdct->xcos1);
245
    av_freep(&mdct->xsin1);
246
    av_freep(&mdct->rot_tmp);
247
    av_freep(&mdct->cplx_tmp);
248
}
249

    
250

    
251
/**
252
 * Initialize FFT tables.
253
 * @param ln log2(FFT size)
254
 */
255
static av_cold int fft_init(AVCodecContext *avctx, AC3MDCTContext *mdct, int ln)
256
{
257
    int i, n, n2;
258
    float alpha;
259

    
260
    n  = 1 << ln;
261
    n2 = n >> 1;
262

    
263
    FF_ALLOC_OR_GOTO(avctx, mdct->costab, n2 * sizeof(*mdct->costab), fft_alloc_fail);
264
    FF_ALLOC_OR_GOTO(avctx, mdct->sintab, n2 * sizeof(*mdct->sintab), fft_alloc_fail);
265

    
266
    for (i = 0; i < n2; i++) {
267
        alpha     = 2.0 * M_PI * i / n;
268
        mdct->costab[i] = FIX15(cos(alpha));
269
        mdct->sintab[i] = FIX15(sin(alpha));
270
    }
271

    
272
    return 0;
273
fft_alloc_fail:
274
    mdct_end(mdct);
275
    return AVERROR(ENOMEM);
276
}
277

    
278

    
279
/**
280
 * Initialize MDCT tables.
281
 * @param nbits log2(MDCT size)
282
 */
283
static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
284
                             int nbits)
285
{
286
    int i, n, n4, ret;
287

    
288
    n  = 1 << nbits;
289
    n4 = n >> 2;
290

    
291
    mdct->nbits = nbits;
292

    
293
    ret = fft_init(avctx, mdct, nbits - 2);
294
    if (ret)
295
        return ret;
296

    
297
    mdct->window = ff_ac3_window;
298

    
299
    FF_ALLOC_OR_GOTO(avctx, mdct->xcos1,    n4 * sizeof(*mdct->xcos1),    mdct_alloc_fail);
300
    FF_ALLOC_OR_GOTO(avctx, mdct->xsin1,    n4 * sizeof(*mdct->xsin1),    mdct_alloc_fail);
301
    FF_ALLOC_OR_GOTO(avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),  mdct_alloc_fail);
302
    FF_ALLOC_OR_GOTO(avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp), mdct_alloc_fail);
303

    
304
    for (i = 0; i < n4; i++) {
305
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
306
        mdct->xcos1[i] = FIX15(-cos(alpha));
307
        mdct->xsin1[i] = FIX15(-sin(alpha));
308
    }
309

    
310
    return 0;
311
mdct_alloc_fail:
312
    mdct_end(mdct);
313
    return AVERROR(ENOMEM);
314
}
315

    
316

    
317
/** Butterfly op */
318
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
319
{                                                       \
320
  int ax, ay, bx, by;                                   \
321
  bx  = pre1;                                           \
322
  by  = pim1;                                           \
323
  ax  = qre1;                                           \
324
  ay  = qim1;                                           \
325
  pre = (bx + ax) >> 1;                                 \
326
  pim = (by + ay) >> 1;                                 \
327
  qre = (bx - ax) >> 1;                                 \
328
  qim = (by - ay) >> 1;                                 \
329
}
330

    
331

    
332
/** Complex multiply */
333
#define CMUL(pre, pim, are, aim, bre, bim)              \
334
{                                                       \
335
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
336
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
337
}
338

    
339

    
340
/**
341
 * Calculate a 2^n point complex FFT on 2^ln points.
342
 * @param z  complex input/output samples
343
 * @param ln log2(FFT size)
344
 */
345
static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)
346
{
347
    int j, l, np, np2;
348
    int nblocks, nloops;
349
    register IComplex *p,*q;
350
    int tmp_re, tmp_im;
351

    
352
    np = 1 << ln;
353

    
354
    /* reverse */
355
    for (j = 0; j < np; j++) {
356
        int k = av_reverse[j] >> (8 - ln);
357
        if (k < j)
358
            FFSWAP(IComplex, z[k], z[j]);
359
    }
360

    
361
    /* pass 0 */
362

    
363
    p = &z[0];
364
    j = np >> 1;
365
    do {
366
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
367
           p[0].re, p[0].im, p[1].re, p[1].im);
368
        p += 2;
369
    } while (--j);
370

    
371
    /* pass 1 */
372

    
373
    p = &z[0];
374
    j = np >> 2;
375
    do {
376
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
377
           p[0].re, p[0].im, p[2].re,  p[2].im);
378
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
379
           p[1].re, p[1].im, p[3].im, -p[3].re);
380
        p+=4;
381
    } while (--j);
382

    
383
    /* pass 2 .. ln-1 */
384

    
385
    nblocks = np >> 3;
386
    nloops  =  1 << 2;
387
    np2     = np >> 1;
388
    do {
389
        p = z;
390
        q = z + nloops;
391
        for (j = 0; j < nblocks; j++) {
392
            BF(p->re, p->im, q->re, q->im,
393
               p->re, p->im, q->re, q->im);
394
            p++;
395
            q++;
396
            for(l = nblocks; l < np2; l += nblocks) {
397
                CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);
398
                BF(p->re, p->im, q->re,  q->im,
399
                   p->re, p->im, tmp_re, tmp_im);
400
                p++;
401
                q++;
402
            }
403
            p += nloops;
404
            q += nloops;
405
        }
406
        nblocks = nblocks >> 1;
407
        nloops  = nloops  << 1;
408
    } while (nblocks);
409
}
410

    
411

    
412
/**
413
 * Calculate a 512-point MDCT
414
 * @param out 256 output frequency coefficients
415
 * @param in  512 windowed input audio samples
416
 */
417
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
418
{
419
    int i, re, im, n, n2, n4;
420
    int16_t *rot = mdct->rot_tmp;
421
    IComplex *x  = mdct->cplx_tmp;
422

    
423
    n  = 1 << mdct->nbits;
424
    n2 = n >> 1;
425
    n4 = n >> 2;
426

    
427
    /* shift to simplify computations */
428
    for (i = 0; i <n4; i++)
429
        rot[i] = -in[i + 3*n4];
430
    memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in));
431

    
432
    /* pre rotation */
433
    for (i = 0; i < n4; i++) {
434
        re =  ((int)rot[   2*i] - (int)rot[ n-1-2*i]) >> 1;
435
        im = -((int)rot[n2+2*i] - (int)rot[n2-1-2*i]) >> 1;
436
        CMUL(x[i].re, x[i].im, re, im, -mdct->xcos1[i], mdct->xsin1[i]);
437
    }
438

    
439
    fft(mdct, x, mdct->nbits - 2);
440

    
441
    /* post rotation */
442
    for (i = 0; i < n4; i++) {
443
        re = x[i].re;
444
        im = x[i].im;
445
        CMUL(out[n2-1-2*i], out[2*i], re, im, mdct->xsin1[i], mdct->xcos1[i]);
446
    }
447
}
448

    
449

    
450
/**
451
 * Apply KBD window to input samples prior to MDCT.
452
 */
453
static void apply_window(int16_t *output, const int16_t *input,
454
                         const int16_t *window, int n)
455
{
456
    int i;
457
    int n2 = n >> 1;
458

    
459
    for (i = 0; i < n2; i++) {
460
        output[i]     = MUL16(input[i],     window[i]) >> 15;
461
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
462
    }
463
}
464

    
465

    
466
/**
467
 * Calculate the log2() of the maximum absolute value in an array.
468
 * @param tab input array
469
 * @param n   number of values in the array
470
 * @return    log2(max(abs(tab[])))
471
 */
472
static int log2_tab(int16_t *tab, int n)
473
{
474
    int i, v;
475

    
476
    v = 0;
477
    for (i = 0; i < n; i++)
478
        v |= abs(tab[i]);
479

    
480
    return av_log2(v);
481
}
482

    
483

    
484
/**
485
 * Left-shift each value in an array by a specified amount.
486
 * @param tab    input array
487
 * @param n      number of values in the array
488
 * @param lshift left shift amount. a negative value means right shift.
489
 */
490
static void lshift_tab(int16_t *tab, int n, int lshift)
491
{
492
    int i;
493

    
494
    if (lshift > 0) {
495
        for (i = 0; i < n; i++)
496
            tab[i] <<= lshift;
497
    } else if (lshift < 0) {
498
        lshift = -lshift;
499
        for (i = 0; i < n; i++)
500
            tab[i] >>= lshift;
501
    }
502
}
503

    
504

    
505
/**
506
 * Normalize the input samples to use the maximum available precision.
507
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
508
 * match the 24-bit internal precision for MDCT coefficients.
509
 *
510
 * @return exponent shift
511
 */
512
static int normalize_samples(AC3EncodeContext *s)
513
{
514
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
515
    v = FFMAX(0, v);
516
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
517
    return v - 9;
518
}
519

    
520

    
521
/**
522
 * Apply the MDCT to input samples to generate frequency coefficients.
523
 * This applies the KBD window and normalizes the input to reduce precision
524
 * loss due to fixed-point calculations.
525
 */
526
static void apply_mdct(AC3EncodeContext *s)
527
{
528
    int blk, ch;
529

    
530
    for (ch = 0; ch < s->channels; ch++) {
531
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
532
            AC3Block *block = &s->blocks[blk];
533
            const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
534

    
535
            apply_window(s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
536

    
537
            block->exp_shift[ch] = normalize_samples(s);
538

    
539
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
540
        }
541
    }
542
}
543

    
544

    
545
/**
546
 * Initialize exponent tables.
547
 */
548
static av_cold void exponent_init(AC3EncodeContext *s)
549
{
550
    int i;
551
    for (i = 73; i < 256; i++) {
552
        exponent_group_tab[0][i] = (i - 1) /  3;
553
        exponent_group_tab[1][i] = (i + 2) /  6;
554
        exponent_group_tab[2][i] = (i + 8) / 12;
555
    }
556
    /* LFE */
557
    exponent_group_tab[0][7] = 2;
558
}
559

    
560

    
561
/**
562
 * Extract exponents from the MDCT coefficients.
563
 * This takes into account the normalization that was done to the input samples
564
 * by adjusting the exponents by the exponent shift values.
565
 */
566
static void extract_exponents(AC3EncodeContext *s)
567
{
568
    int blk, ch, i;
569

    
570
    for (ch = 0; ch < s->channels; ch++) {
571
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
572
            AC3Block *block = &s->blocks[blk];
573
            for (i = 0; i < AC3_MAX_COEFS; i++) {
574
                int e;
575
                int v = abs(SCALE_COEF(block->mdct_coef[ch][i]));
576
                if (v == 0)
577
                    e = 24;
578
                else {
579
                    e = 23 - av_log2(v) + block->exp_shift[ch];
580
                    if (e >= 24) {
581
                        e = 24;
582
                        block->mdct_coef[ch][i] = 0;
583
                    }
584
                }
585
                block->exp[ch][i] = e;
586
            }
587
        }
588
    }
589
}
590

    
591

    
592
/**
593
 * Exponent Difference Threshold.
594
 * New exponents are sent if their SAD exceed this number.
595
 */
596
#define EXP_DIFF_THRESHOLD 1000
597

    
598

    
599
/**
600
 * Calculate exponent strategies for all blocks in a single channel.
601
 */
602
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
603
                                    uint8_t **exp)
604
{
605
    int blk, blk1;
606
    int exp_diff;
607

    
608
    /* estimate if the exponent variation & decide if they should be
609
       reused in the next frame */
610
    exp_strategy[0] = EXP_NEW;
611
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
612
        exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
613
        if (exp_diff > EXP_DIFF_THRESHOLD)
614
            exp_strategy[blk] = EXP_NEW;
615
        else
616
            exp_strategy[blk] = EXP_REUSE;
617
    }
618
    emms_c();
619

    
620
    /* now select the encoding strategy type : if exponents are often
621
       recoded, we use a coarse encoding */
622
    blk = 0;
623
    while (blk < AC3_MAX_BLOCKS) {
624
        blk1 = blk + 1;
625
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
626
            blk1++;
627
        switch (blk1 - blk) {
628
        case 1:  exp_strategy[blk] = EXP_D45; break;
629
        case 2:
630
        case 3:  exp_strategy[blk] = EXP_D25; break;
631
        default: exp_strategy[blk] = EXP_D15; break;
632
        }
633
        blk = blk1;
634
    }
635
}
636

    
637

    
638
/**
639
 * Calculate exponent strategies for all channels.
640
 * Array arrangement is reversed to simplify the per-channel calculation.
641
 */
642
static void compute_exp_strategy(AC3EncodeContext *s)
643
{
644
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
645
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
646
    int ch, blk;
647

    
648
    for (ch = 0; ch < s->fbw_channels; ch++) {
649
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
650
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
651
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
652
        }
653

    
654
        compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
655

    
656
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
657
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
658
    }
659
    if (s->lfe_on) {
660
        ch = s->lfe_channel;
661
        s->blocks[0].exp_strategy[ch] = EXP_D15;
662
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
663
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
664
    }
665
}
666

    
667

    
668
/**
669
 * Set each encoded exponent in a block to the minimum of itself and the
670
 * exponent in the same frequency bin of a following block.
671
 * exp[i] = min(exp[i], exp1[i]
672
 */
673
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
674
{
675
    int i;
676
    for (i = 0; i < n; i++) {
677
        if (exp1[i] < exp[i])
678
            exp[i] = exp1[i];
679
    }
680
}
681

    
682

    
683
/**
684
 * Update the exponents so that they are the ones the decoder will decode.
685
 */
686
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
687
{
688
    int nb_groups, i, k;
689

    
690
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
691

    
692
    /* for each group, compute the minimum exponent */
693
    switch(exp_strategy) {
694
    case EXP_D25:
695
        for (i = 1, k = 1; i <= nb_groups; i++) {
696
            uint8_t exp_min = exp[k];
697
            if (exp[k+1] < exp_min)
698
                exp_min = exp[k+1];
699
            exp[i] = exp_min;
700
            k += 2;
701
        }
702
        break;
703
    case EXP_D45:
704
        for (i = 1, k = 1; i <= nb_groups; i++) {
705
            uint8_t exp_min = exp[k];
706
            if (exp[k+1] < exp_min)
707
                exp_min = exp[k+1];
708
            if (exp[k+2] < exp_min)
709
                exp_min = exp[k+2];
710
            if (exp[k+3] < exp_min)
711
                exp_min = exp[k+3];
712
            exp[i] = exp_min;
713
            k += 4;
714
        }
715
        break;
716
    }
717

    
718
    /* constraint for DC exponent */
719
    if (exp[0] > 15)
720
        exp[0] = 15;
721

    
722
    /* decrease the delta between each groups to within 2 so that they can be
723
       differentially encoded */
724
    for (i = 1; i <= nb_groups; i++)
725
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
726
    i--;
727
    while (--i >= 0)
728
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
729

    
730
    /* now we have the exponent values the decoder will see */
731
    switch (exp_strategy) {
732
    case EXP_D25:
733
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
734
            uint8_t exp1 = exp[i];
735
            exp[k--] = exp1;
736
            exp[k--] = exp1;
737
        }
738
        break;
739
    case EXP_D45:
740
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
741
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
742
            k -= 4;
743
        }
744
        break;
745
    }
746
}
747

    
748

    
749
/**
750
 * Encode exponents from original extracted form to what the decoder will see.
751
 * This copies and groups exponents based on exponent strategy and reduces
752
 * deltas between adjacent exponent groups so that they can be differentially
753
 * encoded.
754
 */
755
static void encode_exponents(AC3EncodeContext *s)
756
{
757
    int blk, blk1, blk2, ch;
758
    AC3Block *block, *block1, *block2;
759

    
760
    for (ch = 0; ch < s->channels; ch++) {
761
        blk = 0;
762
        block = &s->blocks[0];
763
        while (blk < AC3_MAX_BLOCKS) {
764
            blk1 = blk + 1;
765
            block1 = block + 1;
766
            /* for the EXP_REUSE case we select the min of the exponents */
767
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
768
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
769
                blk1++;
770
                block1++;
771
            }
772
            encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
773
                                    block->exp_strategy[ch]);
774
            /* copy encoded exponents for reuse case */
775
            block2 = block + 1;
776
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
777
                memcpy(block2->exp[ch], block->exp[ch],
778
                       s->nb_coefs[ch] * sizeof(uint8_t));
779
            }
780
            blk = blk1;
781
            block = block1;
782
        }
783
    }
784
}
785

    
786

    
787
/**
788
 * Group exponents.
789
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
790
 * varies depending on exponent strategy and bandwidth.
791
 */
792
static void group_exponents(AC3EncodeContext *s)
793
{
794
    int blk, ch, i;
795
    int group_size, nb_groups, bit_count;
796
    uint8_t *p;
797
    int delta0, delta1, delta2;
798
    int exp0, exp1;
799

    
800
    bit_count = 0;
801
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
802
        AC3Block *block = &s->blocks[blk];
803
        for (ch = 0; ch < s->channels; ch++) {
804
            if (block->exp_strategy[ch] == EXP_REUSE) {
805
                continue;
806
            }
807
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
808
            nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
809
            bit_count += 4 + (nb_groups * 7);
810
            p = block->exp[ch];
811

    
812
            /* DC exponent */
813
            exp1 = *p++;
814
            block->grouped_exp[ch][0] = exp1;
815

    
816
            /* remaining exponents are delta encoded */
817
            for (i = 1; i <= nb_groups; i++) {
818
                /* merge three delta in one code */
819
                exp0   = exp1;
820
                exp1   = p[0];
821
                p     += group_size;
822
                delta0 = exp1 - exp0 + 2;
823

    
824
                exp0   = exp1;
825
                exp1   = p[0];
826
                p     += group_size;
827
                delta1 = exp1 - exp0 + 2;
828

    
829
                exp0   = exp1;
830
                exp1   = p[0];
831
                p     += group_size;
832
                delta2 = exp1 - exp0 + 2;
833

    
834
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
835
            }
836
        }
837
    }
838

    
839
    s->exponent_bits = bit_count;
840
}
841

    
842

    
843
/**
844
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
845
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
846
 * and encode final exponents.
847
 */
848
static void process_exponents(AC3EncodeContext *s)
849
{
850
    extract_exponents(s);
851

    
852
    compute_exp_strategy(s);
853

    
854
    encode_exponents(s);
855

    
856
    group_exponents(s);
857
}
858

    
859

    
860
/**
861
 * Count frame bits that are based solely on fixed parameters.
862
 * This only has to be run once when the encoder is initialized.
863
 */
864
static void count_frame_bits_fixed(AC3EncodeContext *s)
865
{
866
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
867
    int blk;
868
    int frame_bits;
869

    
870
    /* assumptions:
871
     *   no dynamic range codes
872
     *   no channel coupling
873
     *   no rematrixing
874
     *   bit allocation parameters do not change between blocks
875
     *   SNR offsets do not change between blocks
876
     *   no delta bit allocation
877
     *   no skipped data
878
     *   no auxilliary data
879
     */
880

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

    
885
    /* audio blocks */
886
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
887
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
888
        if (s->channel_mode == AC3_CHMODE_STEREO) {
889
            frame_bits++; /* rematstr */
890
            if (!blk)
891
                frame_bits += 4;
892
        }
893
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
894
        if (s->lfe_on)
895
            frame_bits++; /* lfeexpstr */
896
        frame_bits++; /* baie */
897
        frame_bits++; /* snr */
898
        frame_bits += 2; /* delta / skip */
899
    }
900
    frame_bits++; /* cplinu for block 0 */
901
    /* bit alloc info */
902
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
903
    /* csnroffset[6] */
904
    /* (fsnoffset[4] + fgaincod[4]) * c */
905
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
906

    
907
    /* auxdatae, crcrsv */
908
    frame_bits += 2;
909

    
910
    /* CRC */
911
    frame_bits += 16;
912

    
913
    s->frame_bits_fixed = frame_bits;
914
}
915

    
916

    
917
/**
918
 * Initialize bit allocation.
919
 * Set default parameter codes and calculate parameter values.
920
 */
921
static void bit_alloc_init(AC3EncodeContext *s)
922
{
923
    int ch;
924

    
925
    /* init default parameters */
926
    s->slow_decay_code = 2;
927
    s->fast_decay_code = 1;
928
    s->slow_gain_code  = 1;
929
    s->db_per_bit_code = 3;
930
    s->floor_code      = 4;
931
    for (ch = 0; ch < s->channels; ch++)
932
        s->fast_gain_code[ch] = 4;
933

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

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

    
946
    count_frame_bits_fixed(s);
947
}
948

    
949

    
950
/**
951
 * Count the bits used to encode the frame, minus exponents and mantissas.
952
 * Bits based on fixed parameters have already been counted, so now we just
953
 * have to add the bits based on parameters that change during encoding.
954
 */
955
static void count_frame_bits(AC3EncodeContext *s)
956
{
957
    int blk, ch;
958
    int frame_bits = 0;
959

    
960
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
961
        uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
962
        for (ch = 0; ch < s->fbw_channels; ch++) {
963
            if (exp_strategy[ch] != EXP_REUSE)
964
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
965
        }
966
    }
967
    s->frame_bits = s->frame_bits_fixed + frame_bits;
968
}
969

    
970

    
971
/**
972
 * Calculate the number of bits needed to encode a set of mantissas.
973
 */
974
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
975
{
976
    int bits, b, i;
977

    
978
    bits = 0;
979
    for (i = 0; i < nb_coefs; i++) {
980
        b = bap[i];
981
        if (b <= 4) {
982
            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
983
            mant_cnt[b]++;
984
        } else if (b <= 13) {
985
            // bap=5 to bap=13 use (bap-1) bits
986
            bits += b - 1;
987
        } else {
988
            // bap=14 uses 14 bits and bap=15 uses 16 bits
989
            bits += (b == 14) ? 14 : 16;
990
        }
991
    }
992
    return bits;
993
}
994

    
995

    
996
/**
997
 * Finalize the mantissa bit count by adding in the grouped mantissas.
998
 */
999
static int compute_mantissa_size_final(int mant_cnt[5])
1000
{
1001
    // bap=1 : 3 mantissas in 5 bits
1002
    int bits = (mant_cnt[1] / 3) * 5;
1003
    // bap=2 : 3 mantissas in 7 bits
1004
    // bap=4 : 2 mantissas in 7 bits
1005
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
1006
    // bap=3 : each mantissa is 3 bits
1007
    bits += mant_cnt[3] * 3;
1008
    return bits;
1009
}
1010

    
1011

    
1012
/**
1013
 * Calculate masking curve based on the final exponents.
1014
 * Also calculate the power spectral densities to use in future calculations.
1015
 */
1016
static void bit_alloc_masking(AC3EncodeContext *s)
1017
{
1018
    int blk, ch;
1019

    
1020
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1021
        AC3Block *block = &s->blocks[blk];
1022
        for (ch = 0; ch < s->channels; ch++) {
1023
            /* We only need psd and mask for calculating bap.
1024
               Since we currently do not calculate bap when exponent
1025
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
1026
            if (block->exp_strategy[ch] != EXP_REUSE) {
1027
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
1028
                                          s->nb_coefs[ch],
1029
                                          block->psd[ch], block->band_psd[ch]);
1030
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1031
                                           0, s->nb_coefs[ch],
1032
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1033
                                           ch == s->lfe_channel,
1034
                                           DBA_NONE, 0, NULL, NULL, NULL,
1035
                                           block->mask[ch]);
1036
            }
1037
        }
1038
    }
1039
}
1040

    
1041

    
1042
/**
1043
 * Ensure that bap for each block and channel point to the current bap_buffer.
1044
 * They may have been switched during the bit allocation search.
1045
 */
1046
static void reset_block_bap(AC3EncodeContext *s)
1047
{
1048
    int blk, ch;
1049
    if (s->blocks[0].bap[0] == s->bap_buffer)
1050
        return;
1051
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1052
        for (ch = 0; ch < s->channels; ch++) {
1053
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1054
        }
1055
    }
1056
}
1057

    
1058

    
1059
/**
1060
 * Run the bit allocation with a given SNR offset.
1061
 * This calculates the bit allocation pointers that will be used to determine
1062
 * the quantization of each mantissa.
1063
 * @return the number of bits needed for mantissas if the given SNR offset is
1064
 *         is used.
1065
 */
1066
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1067
{
1068
    int blk, ch;
1069
    int mantissa_bits;
1070
    int mant_cnt[5];
1071

    
1072
    snr_offset = (snr_offset - 240) << 2;
1073

    
1074
    reset_block_bap(s);
1075
    mantissa_bits = 0;
1076
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1077
        AC3Block *block = &s->blocks[blk];
1078
        // initialize grouped mantissa counts. these are set so that they are
1079
        // padded to the next whole group size when bits are counted in
1080
        // compute_mantissa_size_final
1081
        mant_cnt[0] = mant_cnt[3] = 0;
1082
        mant_cnt[1] = mant_cnt[2] = 2;
1083
        mant_cnt[4] = 1;
1084
        for (ch = 0; ch < s->channels; ch++) {
1085
            /* Currently the only bit allocation parameters which vary across
1086
               blocks within a frame are the exponent values.  We can take
1087
               advantage of that by reusing the bit allocation pointers
1088
               whenever we reuse exponents. */
1089
            if (block->exp_strategy[ch] == EXP_REUSE) {
1090
                memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
1091
            } else {
1092
                ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1093
                                          s->nb_coefs[ch], snr_offset,
1094
                                          s->bit_alloc.floor, ff_ac3_bap_tab,
1095
                                          block->bap[ch]);
1096
            }
1097
            mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1098
        }
1099
        mantissa_bits += compute_mantissa_size_final(mant_cnt);
1100
    }
1101
    return mantissa_bits;
1102
}
1103

    
1104

    
1105
/**
1106
 * Constant bitrate bit allocation search.
1107
 * Find the largest SNR offset that will allow data to fit in the frame.
1108
 */
1109
static int cbr_bit_allocation(AC3EncodeContext *s)
1110
{
1111
    int ch;
1112
    int bits_left;
1113
    int snr_offset, snr_incr;
1114

    
1115
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1116

    
1117
    snr_offset = s->coarse_snr_offset << 4;
1118

    
1119
    /* if previous frame SNR offset was 1023, check if current frame can also
1120
       use SNR offset of 1023. if so, skip the search. */
1121
    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1122
        if (bit_alloc(s, 1023) <= bits_left)
1123
            return 0;
1124
    }
1125

    
1126
    while (snr_offset >= 0 &&
1127
           bit_alloc(s, snr_offset) > bits_left) {
1128
        snr_offset -= 64;
1129
    }
1130
    if (snr_offset < 0)
1131
        return AVERROR(EINVAL);
1132

    
1133
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1134
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1135
        while (snr_offset + snr_incr <= 1023 &&
1136
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1137
            snr_offset += snr_incr;
1138
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1139
        }
1140
    }
1141
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1142
    reset_block_bap(s);
1143

    
1144
    s->coarse_snr_offset = snr_offset >> 4;
1145
    for (ch = 0; ch < s->channels; ch++)
1146
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1147

    
1148
    return 0;
1149
}
1150

    
1151

    
1152
/**
1153
 * Downgrade exponent strategies to reduce the bits used by the exponents.
1154
 * This is a fallback for when bit allocation fails with the normal exponent
1155
 * strategies.  Each time this function is run it only downgrades the
1156
 * strategy in 1 channel of 1 block.
1157
 * @return non-zero if downgrade was unsuccessful
1158
 */
1159
static int downgrade_exponents(AC3EncodeContext *s)
1160
{
1161
    int ch, blk;
1162

    
1163
    for (ch = 0; ch < s->fbw_channels; ch++) {
1164
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1165
            if (s->blocks[blk].exp_strategy[ch] == EXP_D15) {
1166
                s->blocks[blk].exp_strategy[ch] = EXP_D25;
1167
                return 0;
1168
            }
1169
        }
1170
    }
1171
    for (ch = 0; ch < s->fbw_channels; ch++) {
1172
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1173
            if (s->blocks[blk].exp_strategy[ch] == EXP_D25) {
1174
                s->blocks[blk].exp_strategy[ch] = EXP_D45;
1175
                return 0;
1176
            }
1177
        }
1178
    }
1179
    for (ch = 0; ch < s->fbw_channels; ch++) {
1180
        /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1181
           the block number > 0 */
1182
        for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1183
            if (s->blocks[blk].exp_strategy[ch] > EXP_REUSE) {
1184
                s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
1185
                return 0;
1186
            }
1187
        }
1188
    }
1189
    return -1;
1190
}
1191

    
1192

    
1193
/**
1194
 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1195
 * This is a second fallback for when bit allocation still fails after exponents
1196
 * have been downgraded.
1197
 * @return non-zero if bandwidth reduction was unsuccessful
1198
 */
1199
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1200
{
1201
    int ch;
1202

    
1203
    if (s->bandwidth_code[0] > min_bw_code) {
1204
        for (ch = 0; ch < s->fbw_channels; ch++) {
1205
            s->bandwidth_code[ch]--;
1206
            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1207
        }
1208
        return 0;
1209
    }
1210
    return -1;
1211
}
1212

    
1213

    
1214
/**
1215
 * Perform bit allocation search.
1216
 * Finds the SNR offset value that maximizes quality and fits in the specified
1217
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1218
 * used to quantize the mantissas.
1219
 */
1220
static int compute_bit_allocation(AC3EncodeContext *s)
1221
{
1222
    int ret;
1223

    
1224
    count_frame_bits(s);
1225

    
1226
    bit_alloc_masking(s);
1227

    
1228
    ret = cbr_bit_allocation(s);
1229
    while (ret) {
1230
        /* fallback 1: downgrade exponents */
1231
        if (!downgrade_exponents(s)) {
1232
            extract_exponents(s);
1233
            encode_exponents(s);
1234
            group_exponents(s);
1235
            ret = compute_bit_allocation(s);
1236
            continue;
1237
        }
1238

    
1239
        /* fallback 2: reduce bandwidth */
1240
        /* only do this if the user has not specified a specific cutoff
1241
           frequency */
1242
        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1243
            process_exponents(s);
1244
            ret = compute_bit_allocation(s);
1245
            continue;
1246
        }
1247

    
1248
        /* fallbacks were not enough... */
1249
        break;
1250
    }
1251

    
1252
    return ret;
1253
}
1254

    
1255

    
1256
/**
1257
 * Symmetric quantization on 'levels' levels.
1258
 */
1259
static inline int sym_quant(int c, int e, int levels)
1260
{
1261
    int v;
1262

    
1263
    if (c >= 0) {
1264
        v = (levels * (c << e)) >> 24;
1265
        v = (v + 1) >> 1;
1266
        v = (levels >> 1) + v;
1267
    } else {
1268
        v = (levels * ((-c) << e)) >> 24;
1269
        v = (v + 1) >> 1;
1270
        v = (levels >> 1) - v;
1271
    }
1272
    assert(v >= 0 && v < levels);
1273
    return v;
1274
}
1275

    
1276

    
1277
/**
1278
 * Asymmetric quantization on 2^qbits levels.
1279
 */
1280
static inline int asym_quant(int c, int e, int qbits)
1281
{
1282
    int lshift, m, v;
1283

    
1284
    lshift = e + qbits - 24;
1285
    if (lshift >= 0)
1286
        v = c << lshift;
1287
    else
1288
        v = c >> (-lshift);
1289
    /* rounding */
1290
    v = (v + 1) >> 1;
1291
    m = (1 << (qbits-1));
1292
    if (v >= m)
1293
        v = m - 1;
1294
    assert(v >= -m);
1295
    return v & ((1 << qbits)-1);
1296
}
1297

    
1298

    
1299
/**
1300
 * Quantize a set of mantissas for a single channel in a single block.
1301
 */
1302
static void quantize_mantissas_blk_ch(AC3EncodeContext *s, CoefType *mdct_coef,
1303
                                      int8_t exp_shift, uint8_t *exp,
1304
                                      uint8_t *bap, uint16_t *qmant, int n)
1305
{
1306
    int i;
1307

    
1308
    for (i = 0; i < n; i++) {
1309
        int v;
1310
        int c = SCALE_COEF(mdct_coef[i]);
1311
        int e = exp[i] - exp_shift;
1312
        int b = bap[i];
1313
        switch (b) {
1314
        case 0:
1315
            v = 0;
1316
            break;
1317
        case 1:
1318
            v = sym_quant(c, e, 3);
1319
            switch (s->mant1_cnt) {
1320
            case 0:
1321
                s->qmant1_ptr = &qmant[i];
1322
                v = 9 * v;
1323
                s->mant1_cnt = 1;
1324
                break;
1325
            case 1:
1326
                *s->qmant1_ptr += 3 * v;
1327
                s->mant1_cnt = 2;
1328
                v = 128;
1329
                break;
1330
            default:
1331
                *s->qmant1_ptr += v;
1332
                s->mant1_cnt = 0;
1333
                v = 128;
1334
                break;
1335
            }
1336
            break;
1337
        case 2:
1338
            v = sym_quant(c, e, 5);
1339
            switch (s->mant2_cnt) {
1340
            case 0:
1341
                s->qmant2_ptr = &qmant[i];
1342
                v = 25 * v;
1343
                s->mant2_cnt = 1;
1344
                break;
1345
            case 1:
1346
                *s->qmant2_ptr += 5 * v;
1347
                s->mant2_cnt = 2;
1348
                v = 128;
1349
                break;
1350
            default:
1351
                *s->qmant2_ptr += v;
1352
                s->mant2_cnt = 0;
1353
                v = 128;
1354
                break;
1355
            }
1356
            break;
1357
        case 3:
1358
            v = sym_quant(c, e, 7);
1359
            break;
1360
        case 4:
1361
            v = sym_quant(c, e, 11);
1362
            switch (s->mant4_cnt) {
1363
            case 0:
1364
                s->qmant4_ptr = &qmant[i];
1365
                v = 11 * v;
1366
                s->mant4_cnt = 1;
1367
                break;
1368
            default:
1369
                *s->qmant4_ptr += v;
1370
                s->mant4_cnt = 0;
1371
                v = 128;
1372
                break;
1373
            }
1374
            break;
1375
        case 5:
1376
            v = sym_quant(c, e, 15);
1377
            break;
1378
        case 14:
1379
            v = asym_quant(c, e, 14);
1380
            break;
1381
        case 15:
1382
            v = asym_quant(c, e, 16);
1383
            break;
1384
        default:
1385
            v = asym_quant(c, e, b - 1);
1386
            break;
1387
        }
1388
        qmant[i] = v;
1389
    }
1390
}
1391

    
1392

    
1393
/**
1394
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1395
 */
1396
static void quantize_mantissas(AC3EncodeContext *s)
1397
{
1398
    int blk, ch;
1399

    
1400

    
1401
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1402
        AC3Block *block = &s->blocks[blk];
1403
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1404
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1405

    
1406
        for (ch = 0; ch < s->channels; ch++) {
1407
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1408
                                      block->exp[ch], block->bap[ch],
1409
                                      block->qmant[ch], s->nb_coefs[ch]);
1410
        }
1411
    }
1412
}
1413

    
1414

    
1415
/**
1416
 * Write the AC-3 frame header to the output bitstream.
1417
 */
1418
static void output_frame_header(AC3EncodeContext *s)
1419
{
1420
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1421
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1422
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1423
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1424
    put_bits(&s->pb, 5,  s->bitstream_id);
1425
    put_bits(&s->pb, 3,  s->bitstream_mode);
1426
    put_bits(&s->pb, 3,  s->channel_mode);
1427
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1428
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1429
    if (s->channel_mode & 0x04)
1430
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1431
    if (s->channel_mode == AC3_CHMODE_STEREO)
1432
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1433
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1434
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1435
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1436
    put_bits(&s->pb, 1, 0);         /* no lang code */
1437
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1438
    put_bits(&s->pb, 1, 0);         /* no copyright */
1439
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1440
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1441
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1442
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1443
}
1444

    
1445

    
1446
/**
1447
 * Write one audio block to the output bitstream.
1448
 */
1449
static void output_audio_block(AC3EncodeContext *s, int block_num)
1450
{
1451
    int ch, i, baie, rbnd;
1452
    AC3Block *block = &s->blocks[block_num];
1453

    
1454
    /* block switching */
1455
    for (ch = 0; ch < s->fbw_channels; ch++)
1456
        put_bits(&s->pb, 1, 0);
1457

    
1458
    /* dither flags */
1459
    for (ch = 0; ch < s->fbw_channels; ch++)
1460
        put_bits(&s->pb, 1, 1);
1461

    
1462
    /* dynamic range codes */
1463
    put_bits(&s->pb, 1, 0);
1464

    
1465
    /* channel coupling */
1466
    if (!block_num) {
1467
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1468
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1469
    } else {
1470
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1471
    }
1472

    
1473
    /* stereo rematrixing */
1474
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1475
        if (!block_num) {
1476
            /* first block must define rematrixing (rematstr) */
1477
            put_bits(&s->pb, 1, 1);
1478

    
1479
            /* dummy rematrixing rematflg(1:4)=0 */
1480
            for (rbnd = 0; rbnd < 4; rbnd++)
1481
                put_bits(&s->pb, 1, 0);
1482
        } else {
1483
            /* no matrixing (but should be used in the future) */
1484
            put_bits(&s->pb, 1, 0);
1485
        }
1486
    }
1487

    
1488
    /* exponent strategy */
1489
    for (ch = 0; ch < s->fbw_channels; ch++)
1490
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1491
    if (s->lfe_on)
1492
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1493

    
1494
    /* bandwidth */
1495
    for (ch = 0; ch < s->fbw_channels; ch++) {
1496
        if (block->exp_strategy[ch] != EXP_REUSE)
1497
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1498
    }
1499

    
1500
    /* exponents */
1501
    for (ch = 0; ch < s->channels; ch++) {
1502
        int nb_groups;
1503

    
1504
        if (block->exp_strategy[ch] == EXP_REUSE)
1505
            continue;
1506

    
1507
        /* DC exponent */
1508
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1509

    
1510
        /* exponent groups */
1511
        nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
1512
        for (i = 1; i <= nb_groups; i++)
1513
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1514

    
1515
        /* gain range info */
1516
        if (ch != s->lfe_channel)
1517
            put_bits(&s->pb, 2, 0);
1518
    }
1519

    
1520
    /* bit allocation info */
1521
    baie = (block_num == 0);
1522
    put_bits(&s->pb, 1, baie);
1523
    if (baie) {
1524
        put_bits(&s->pb, 2, s->slow_decay_code);
1525
        put_bits(&s->pb, 2, s->fast_decay_code);
1526
        put_bits(&s->pb, 2, s->slow_gain_code);
1527
        put_bits(&s->pb, 2, s->db_per_bit_code);
1528
        put_bits(&s->pb, 3, s->floor_code);
1529
    }
1530

    
1531
    /* snr offset */
1532
    put_bits(&s->pb, 1, baie);
1533
    if (baie) {
1534
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1535
        for (ch = 0; ch < s->channels; ch++) {
1536
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1537
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1538
        }
1539
    }
1540

    
1541
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1542
    put_bits(&s->pb, 1, 0); /* no data to skip */
1543

    
1544
    /* mantissas */
1545
    for (ch = 0; ch < s->channels; ch++) {
1546
        int b, q;
1547
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1548
            q = block->qmant[ch][i];
1549
            b = block->bap[ch][i];
1550
            switch (b) {
1551
            case 0:                                         break;
1552
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1553
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1554
            case 3:               put_bits(&s->pb,   3, q); break;
1555
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1556
            case 14:              put_bits(&s->pb,  14, q); break;
1557
            case 15:              put_bits(&s->pb,  16, q); break;
1558
            default:              put_bits(&s->pb, b-1, q); break;
1559
            }
1560
        }
1561
    }
1562
}
1563

    
1564

    
1565
/** CRC-16 Polynomial */
1566
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1567

    
1568

    
1569
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1570
{
1571
    unsigned int c;
1572

    
1573
    c = 0;
1574
    while (a) {
1575
        if (a & 1)
1576
            c ^= b;
1577
        a = a >> 1;
1578
        b = b << 1;
1579
        if (b & (1 << 16))
1580
            b ^= poly;
1581
    }
1582
    return c;
1583
}
1584

    
1585

    
1586
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1587
{
1588
    unsigned int r;
1589
    r = 1;
1590
    while (n) {
1591
        if (n & 1)
1592
            r = mul_poly(r, a, poly);
1593
        a = mul_poly(a, a, poly);
1594
        n >>= 1;
1595
    }
1596
    return r;
1597
}
1598

    
1599

    
1600
/**
1601
 * Fill the end of the frame with 0's and compute the two CRCs.
1602
 */
1603
static void output_frame_end(AC3EncodeContext *s)
1604
{
1605
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1606
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1607
    uint8_t *frame;
1608

    
1609
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1610

    
1611
    /* pad the remainder of the frame with zeros */
1612
    flush_put_bits(&s->pb);
1613
    frame = s->pb.buf;
1614
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1615
    assert(pad_bytes >= 0);
1616
    if (pad_bytes > 0)
1617
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1618

    
1619
    /* compute crc1 */
1620
    /* this is not so easy because it is at the beginning of the data... */
1621
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1622
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1623
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1624
    AV_WB16(frame + 2, crc1);
1625

    
1626
    /* compute crc2 */
1627
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1628
                          s->frame_size - frame_size_58 - 3);
1629
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1630
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1631
    if (crc2 == 0x770B) {
1632
        frame[s->frame_size - 3] ^= 0x1;
1633
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1634
    }
1635
    crc2 = av_bswap16(crc2);
1636
    AV_WB16(frame + s->frame_size - 2, crc2);
1637
}
1638

    
1639

    
1640
/**
1641
 * Write the frame to the output bitstream.
1642
 */
1643
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1644
{
1645
    int blk;
1646

    
1647
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1648

    
1649
    output_frame_header(s);
1650

    
1651
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1652
        output_audio_block(s, blk);
1653

    
1654
    output_frame_end(s);
1655
}
1656

    
1657

    
1658
/**
1659
 * Encode a single AC-3 frame.
1660
 */
1661
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1662
                            int buf_size, void *data)
1663
{
1664
    AC3EncodeContext *s = avctx->priv_data;
1665
    const SampleType *samples = data;
1666
    int ret;
1667

    
1668
    if (s->bit_alloc.sr_code == 1)
1669
        adjust_frame_size(s);
1670

    
1671
    deinterleave_input_samples(s, samples);
1672

    
1673
    apply_mdct(s);
1674

    
1675
    process_exponents(s);
1676

    
1677
    ret = compute_bit_allocation(s);
1678
    if (ret) {
1679
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1680
        return ret;
1681
    }
1682

    
1683
    quantize_mantissas(s);
1684

    
1685
    output_frame(s, frame);
1686

    
1687
    return s->frame_size;
1688
}
1689

    
1690

    
1691
/**
1692
 * Finalize encoding and free any memory allocated by the encoder.
1693
 */
1694
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1695
{
1696
    int blk, ch;
1697
    AC3EncodeContext *s = avctx->priv_data;
1698

    
1699
    for (ch = 0; ch < s->channels; ch++)
1700
        av_freep(&s->planar_samples[ch]);
1701
    av_freep(&s->planar_samples);
1702
    av_freep(&s->bap_buffer);
1703
    av_freep(&s->bap1_buffer);
1704
    av_freep(&s->mdct_coef_buffer);
1705
    av_freep(&s->exp_buffer);
1706
    av_freep(&s->grouped_exp_buffer);
1707
    av_freep(&s->psd_buffer);
1708
    av_freep(&s->band_psd_buffer);
1709
    av_freep(&s->mask_buffer);
1710
    av_freep(&s->qmant_buffer);
1711
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1712
        AC3Block *block = &s->blocks[blk];
1713
        av_freep(&block->bap);
1714
        av_freep(&block->mdct_coef);
1715
        av_freep(&block->exp);
1716
        av_freep(&block->grouped_exp);
1717
        av_freep(&block->psd);
1718
        av_freep(&block->band_psd);
1719
        av_freep(&block->mask);
1720
        av_freep(&block->qmant);
1721
    }
1722

    
1723
    mdct_end(&s->mdct);
1724

    
1725
    av_freep(&avctx->coded_frame);
1726
    return 0;
1727
}
1728

    
1729

    
1730
/**
1731
 * Set channel information during initialization.
1732
 */
1733
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1734
                                    int64_t *channel_layout)
1735
{
1736
    int ch_layout;
1737

    
1738
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1739
        return AVERROR(EINVAL);
1740
    if ((uint64_t)*channel_layout > 0x7FF)
1741
        return AVERROR(EINVAL);
1742
    ch_layout = *channel_layout;
1743
    if (!ch_layout)
1744
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1745
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1746
        return AVERROR(EINVAL);
1747

    
1748
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1749
    s->channels     = channels;
1750
    s->fbw_channels = channels - s->lfe_on;
1751
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1752
    if (s->lfe_on)
1753
        ch_layout -= AV_CH_LOW_FREQUENCY;
1754

    
1755
    switch (ch_layout) {
1756
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1757
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1758
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1759
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1760
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1761
    case AV_CH_LAYOUT_QUAD:
1762
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1763
    case AV_CH_LAYOUT_5POINT0:
1764
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1765
    default:
1766
        return AVERROR(EINVAL);
1767
    }
1768

    
1769
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1770
    *channel_layout = ch_layout;
1771
    if (s->lfe_on)
1772
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1773

    
1774
    return 0;
1775
}
1776

    
1777

    
1778
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1779
{
1780
    int i, ret;
1781

    
1782
    /* validate channel layout */
1783
    if (!avctx->channel_layout) {
1784
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1785
                                      "encoder will guess the layout, but it "
1786
                                      "might be incorrect.\n");
1787
    }
1788
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1789
    if (ret) {
1790
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1791
        return ret;
1792
    }
1793

    
1794
    /* validate sample rate */
1795
    for (i = 0; i < 9; i++) {
1796
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1797
            break;
1798
    }
1799
    if (i == 9) {
1800
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1801
        return AVERROR(EINVAL);
1802
    }
1803
    s->sample_rate        = avctx->sample_rate;
1804
    s->bit_alloc.sr_shift = i % 3;
1805
    s->bit_alloc.sr_code  = i / 3;
1806

    
1807
    /* validate bit rate */
1808
    for (i = 0; i < 19; i++) {
1809
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1810
            break;
1811
    }
1812
    if (i == 19) {
1813
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1814
        return AVERROR(EINVAL);
1815
    }
1816
    s->bit_rate        = avctx->bit_rate;
1817
    s->frame_size_code = i << 1;
1818

    
1819
    /* validate cutoff */
1820
    if (avctx->cutoff < 0) {
1821
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
1822
        return AVERROR(EINVAL);
1823
    }
1824
    s->cutoff = avctx->cutoff;
1825
    if (s->cutoff > (s->sample_rate >> 1))
1826
        s->cutoff = s->sample_rate >> 1;
1827

    
1828
    return 0;
1829
}
1830

    
1831

    
1832
/**
1833
 * Set bandwidth for all channels.
1834
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1835
 * default value will be used.
1836
 */
1837
static av_cold void set_bandwidth(AC3EncodeContext *s)
1838
{
1839
    int ch, bw_code;
1840

    
1841
    if (s->cutoff) {
1842
        /* calculate bandwidth based on user-specified cutoff frequency */
1843
        int fbw_coeffs;
1844
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1845
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1846
    } else {
1847
        /* use default bandwidth setting */
1848
        /* XXX: should compute the bandwidth according to the frame
1849
           size, so that we avoid annoying high frequency artifacts */
1850
        bw_code = 50;
1851
    }
1852

    
1853
    /* set number of coefficients for each channel */
1854
    for (ch = 0; ch < s->fbw_channels; ch++) {
1855
        s->bandwidth_code[ch] = bw_code;
1856
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1857
    }
1858
    if (s->lfe_on)
1859
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1860
}
1861

    
1862

    
1863
static av_cold int allocate_buffers(AVCodecContext *avctx)
1864
{
1865
    int blk, ch;
1866
    AC3EncodeContext *s = avctx->priv_data;
1867

    
1868
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1869
                     alloc_fail);
1870
    for (ch = 0; ch < s->channels; ch++) {
1871
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1872
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1873
                          alloc_fail);
1874
    }
1875
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1876
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1877
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1878
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1879
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1880
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1881
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1882
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1883
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1884
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1885
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1886
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1887
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1888
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1889
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1890
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1891
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1892
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1893
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1894
        AC3Block *block = &s->blocks[blk];
1895
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1896
                         alloc_fail);
1897
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1898
                          alloc_fail);
1899
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1900
                          alloc_fail);
1901
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1902
                          alloc_fail);
1903
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1904
                          alloc_fail);
1905
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1906
                          alloc_fail);
1907
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1908
                          alloc_fail);
1909
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1910
                          alloc_fail);
1911

    
1912
        for (ch = 0; ch < s->channels; ch++) {
1913
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1914
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1915
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1916
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1917
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1918
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1919
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1920
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1921
        }
1922
    }
1923

    
1924
    return 0;
1925
alloc_fail:
1926
    return AVERROR(ENOMEM);
1927
}
1928

    
1929

    
1930
/**
1931
 * Initialize the encoder.
1932
 */
1933
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1934
{
1935
    AC3EncodeContext *s = avctx->priv_data;
1936
    int ret, frame_size_58;
1937

    
1938
    avctx->frame_size = AC3_FRAME_SIZE;
1939

    
1940
    ac3_common_init();
1941

    
1942
    ret = validate_options(avctx, s);
1943
    if (ret)
1944
        return ret;
1945

    
1946
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1947
    s->bitstream_mode = 0; /* complete main audio service */
1948

    
1949
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1950
    s->bits_written    = 0;
1951
    s->samples_written = 0;
1952
    s->frame_size      = s->frame_size_min;
1953

    
1954
    /* calculate crc_inv for both possible frame sizes */
1955
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
1956
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1957
    if (s->bit_alloc.sr_code == 1) {
1958
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
1959
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1960
    }
1961

    
1962
    set_bandwidth(s);
1963

    
1964
    exponent_init(s);
1965

    
1966
    bit_alloc_init(s);
1967

    
1968
    ret = mdct_init(avctx, &s->mdct, 9);
1969
    if (ret)
1970
        goto init_fail;
1971

    
1972
    ret = allocate_buffers(avctx);
1973
    if (ret)
1974
        goto init_fail;
1975

    
1976
    avctx->coded_frame= avcodec_alloc_frame();
1977

    
1978
    dsputil_init(&s->dsp, avctx);
1979

    
1980
    return 0;
1981
init_fail:
1982
    ac3_encode_close(avctx);
1983
    return ret;
1984
}
1985

    
1986

    
1987
#ifdef TEST
1988
/*************************************************************************/
1989
/* TEST */
1990

    
1991
#include "libavutil/lfg.h"
1992

    
1993
#define MDCT_NBITS 9
1994
#define MDCT_SAMPLES (1 << MDCT_NBITS)
1995
#define FN (MDCT_SAMPLES/4)
1996

    
1997

    
1998
static void fft_test(AC3MDCTContext *mdct, AVLFG *lfg)
1999
{
2000
    IComplex in[FN], in1[FN];
2001
    int k, n, i;
2002
    float sum_re, sum_im, a;
2003

    
2004
    for (i = 0; i < FN; i++) {
2005
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
2006
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
2007
        in1[i]   = in[i];
2008
    }
2009
    fft(mdct, in, 7);
2010

    
2011
    /* do it by hand */
2012
    for (k = 0; k < FN; k++) {
2013
        sum_re = 0;
2014
        sum_im = 0;
2015
        for (n = 0; n < FN; n++) {
2016
            a = -2 * M_PI * (n * k) / FN;
2017
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
2018
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
2019
        }
2020
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
2021
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
2022
    }
2023
}
2024

    
2025

    
2026
static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg)
2027
{
2028
    int16_t input[MDCT_SAMPLES];
2029
    int32_t output[AC3_MAX_COEFS];
2030
    float input1[MDCT_SAMPLES];
2031
    float output1[AC3_MAX_COEFS];
2032
    float s, a, err, e, emax;
2033
    int i, k, n;
2034

    
2035
    for (i = 0; i < MDCT_SAMPLES; i++) {
2036
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
2037
        input1[i] = input[i];
2038
    }
2039

    
2040
    mdct512(mdct, output, input);
2041

    
2042
    /* do it by hand */
2043
    for (k = 0; k < AC3_MAX_COEFS; k++) {
2044
        s = 0;
2045
        for (n = 0; n < MDCT_SAMPLES; n++) {
2046
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
2047
            s += input1[n] * cos(a);
2048
        }
2049
        output1[k] = -2 * s / MDCT_SAMPLES;
2050
    }
2051

    
2052
    err  = 0;
2053
    emax = 0;
2054
    for (i = 0; i < AC3_MAX_COEFS; i++) {
2055
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
2056
        e = output[i] - output1[i];
2057
        if (e > emax)
2058
            emax = e;
2059
        err += e * e;
2060
    }
2061
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
2062
}
2063

    
2064

    
2065
int main(void)
2066
{
2067
    AVLFG lfg;
2068
    AC3MDCTContext mdct;
2069

    
2070
    mdct.avctx = NULL;
2071
    av_log_set_level(AV_LOG_DEBUG);
2072
    mdct_init(&mdct, 9);
2073

    
2074
    fft_test(&mdct, &lfg);
2075
    mdct_test(&mdct, &lfg);
2076

    
2077
    return 0;
2078
}
2079
#endif /* TEST */
2080

    
2081

    
2082
AVCodec ac3_encoder = {
2083
    "ac3",
2084
    AVMEDIA_TYPE_AUDIO,
2085
    CODEC_ID_AC3,
2086
    sizeof(AC3EncodeContext),
2087
    ac3_encode_init,
2088
    ac3_encode_frame,
2089
    ac3_encode_close,
2090
    NULL,
2091
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
2092
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
2093
    .channel_layouts = ac3_channel_layouts,
2094
};