Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ cf7c961b

History | View | Annotate | Download (58.5 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
#define MDCT_NBITS 9
41
#define MDCT_SAMPLES (1 << MDCT_NBITS)
42

    
43
/** Maximum number of exponent groups. +1 for separate DC exponent. */
44
#define AC3_MAX_EXP_GROUPS 85
45

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

    
49
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
50
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
51

    
52

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

    
61
typedef struct AC3MDCTContext {
62
    AVCodecContext *avctx;                  ///< parent context for av_log()
63
    int16_t *rot_tmp;                       ///< temp buffer for pre-rotated samples
64
    IComplex *cplx_tmp;                     ///< temp buffer for complex pre-rotated samples
65
} AC3MDCTContext;
66

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

    
83
/**
84
 * AC-3 encoder private context.
85
 */
86
typedef struct AC3EncodeContext {
87
    PutBitContext pb;                       ///< bitstream writer context
88
    DSPContext dsp;
89
    AC3MDCTContext mdct;                    ///< MDCT context
90

    
91
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
92

    
93
    int bitstream_id;                       ///< bitstream id                           (bsid)
94
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
95

    
96
    int bit_rate;                           ///< target bit rate, in bits-per-second
97
    int sample_rate;                        ///< sampling frequency, in Hz
98

    
99
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
100
    int frame_size;                         ///< current frame size in bytes
101
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
102
    int bits_written;                       ///< bit count    (used to avg. bitrate)
103
    int samples_written;                    ///< sample count (used to avg. bitrate)
104

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

    
112
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
113
    int nb_coefs[AC3_MAX_CHANNELS];
114

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

    
129
    /* mantissa encoding */
130
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
131
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
132

    
133
    int16_t **planar_samples;
134
    uint8_t *bap_buffer;
135
    uint8_t *bap1_buffer;
136
    int32_t *mdct_coef_buffer;
137
    uint8_t *exp_buffer;
138
    uint8_t *grouped_exp_buffer;
139
    int16_t *psd_buffer;
140
    int16_t *band_psd_buffer;
141
    int16_t *mask_buffer;
142
    uint16_t *qmant_buffer;
143

    
144
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
145
} AC3EncodeContext;
146

    
147

    
148
/** MDCT and FFT tables */
149
static int16_t costab[64];
150
static int16_t sintab[64];
151
static int16_t xcos1[128];
152
static int16_t xsin1[128];
153

    
154
/**
155
 * LUT for number of exponent groups.
156
 * exponent_group_tab[exponent strategy-1][number of coefficients]
157
 */
158
uint8_t exponent_group_tab[3][256];
159

    
160

    
161
/**
162
 * Adjust the frame size to make the average bit rate match the target bit rate.
163
 * This is only needed for 11025, 22050, and 44100 sample rates.
164
 */
165
static void adjust_frame_size(AC3EncodeContext *s)
166
{
167
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
168
        s->bits_written    -= s->bit_rate;
169
        s->samples_written -= s->sample_rate;
170
    }
171
    s->frame_size = s->frame_size_min +
172
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
173
    s->bits_written    += s->frame_size * 8;
174
    s->samples_written += AC3_FRAME_SIZE;
175
}
176

    
177

    
178
/**
179
 * Deinterleave input samples.
180
 * Channels are reordered from FFmpeg's default order to AC-3 order.
181
 */
182
static void deinterleave_input_samples(AC3EncodeContext *s,
183
                                       const int16_t *samples)
184
{
185
    int ch, i;
186

    
187
    /* deinterleave and remap input samples */
188
    for (ch = 0; ch < s->channels; ch++) {
189
        const int16_t *sptr;
190
        int sinc;
191

    
192
        /* copy last 256 samples of previous frame to the start of the current frame */
193
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
194
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
195

    
196
        /* deinterleave */
197
        sinc = s->channels;
198
        sptr = samples + s->channel_map[ch];
199
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
200
            s->planar_samples[ch][i] = *sptr;
201
            sptr += sinc;
202
        }
203
    }
204
}
205

    
206

    
207
/**
208
 * Finalize MDCT and free allocated memory.
209
 */
210
static av_cold void mdct_end(AC3MDCTContext *mdct)
211
{
212
    av_freep(&mdct->rot_tmp);
213
    av_freep(&mdct->cplx_tmp);
214
}
215

    
216

    
217

    
218
/**
219
 * Initialize FFT tables.
220
 * @param ln log2(FFT size)
221
 */
222
static av_cold void fft_init(int ln)
223
{
224
    int i, n, n2;
225
    float alpha;
226

    
227
    n  = 1 << ln;
228
    n2 = n >> 1;
229

    
230
    for (i = 0; i < n2; i++) {
231
        alpha     = 2.0 * M_PI * i / n;
232
        costab[i] = FIX15(cos(alpha));
233
        sintab[i] = FIX15(sin(alpha));
234
    }
235
}
236

    
237

    
238
/**
239
 * Initialize MDCT tables.
240
 * @param nbits log2(MDCT size)
241
 */
242
static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
243
{
244
    int i, n, n4;
245

    
246
    n  = 1 << nbits;
247
    n4 = n >> 2;
248

    
249
    fft_init(nbits - 2);
250

    
251
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),
252
                     mdct_alloc_fail);
253
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
254
                     mdct_alloc_fail);
255

    
256
    for (i = 0; i < n4; i++) {
257
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
258
        xcos1[i] = FIX15(-cos(alpha));
259
        xsin1[i] = FIX15(-sin(alpha));
260
    }
261

    
262
    return 0;
263
mdct_alloc_fail:
264
    return AVERROR(ENOMEM);
265
}
266

    
267

    
268
/** Butterfly op */
269
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
270
{                                                       \
271
  int ax, ay, bx, by;                                   \
272
  bx  = pre1;                                           \
273
  by  = pim1;                                           \
274
  ax  = qre1;                                           \
275
  ay  = qim1;                                           \
276
  pre = (bx + ax) >> 1;                                 \
277
  pim = (by + ay) >> 1;                                 \
278
  qre = (bx - ax) >> 1;                                 \
279
  qim = (by - ay) >> 1;                                 \
280
}
281

    
282

    
283
/** Complex multiply */
284
#define CMUL(pre, pim, are, aim, bre, bim)              \
285
{                                                       \
286
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
287
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
288
}
289

    
290

    
291
/**
292
 * Calculate a 2^n point complex FFT on 2^ln points.
293
 * @param z  complex input/output samples
294
 * @param ln log2(FFT size)
295
 */
296
static void fft(IComplex *z, int ln)
297
{
298
    int j, l, np, np2;
299
    int nblocks, nloops;
300
    register IComplex *p,*q;
301
    int tmp_re, tmp_im;
302

    
303
    np = 1 << ln;
304

    
305
    /* reverse */
306
    for (j = 0; j < np; j++) {
307
        int k = av_reverse[j] >> (8 - ln);
308
        if (k < j)
309
            FFSWAP(IComplex, z[k], z[j]);
310
    }
311

    
312
    /* pass 0 */
313

    
314
    p = &z[0];
315
    j = np >> 1;
316
    do {
317
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
318
           p[0].re, p[0].im, p[1].re, p[1].im);
319
        p += 2;
320
    } while (--j);
321

    
322
    /* pass 1 */
323

    
324
    p = &z[0];
325
    j = np >> 2;
326
    do {
327
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
328
           p[0].re, p[0].im, p[2].re,  p[2].im);
329
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
330
           p[1].re, p[1].im, p[3].im, -p[3].re);
331
        p+=4;
332
    } while (--j);
333

    
334
    /* pass 2 .. ln-1 */
335

    
336
    nblocks = np >> 3;
337
    nloops  =  1 << 2;
338
    np2     = np >> 1;
339
    do {
340
        p = z;
341
        q = z + nloops;
342
        for (j = 0; j < nblocks; j++) {
343
            BF(p->re, p->im, q->re, q->im,
344
               p->re, p->im, q->re, q->im);
345
            p++;
346
            q++;
347
            for(l = nblocks; l < np2; l += nblocks) {
348
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
349
                BF(p->re, p->im, q->re,  q->im,
350
                   p->re, p->im, tmp_re, tmp_im);
351
                p++;
352
                q++;
353
            }
354
            p += nloops;
355
            q += nloops;
356
        }
357
        nblocks = nblocks >> 1;
358
        nloops  = nloops  << 1;
359
    } while (nblocks);
360
}
361

    
362

    
363
/**
364
 * Calculate a 512-point MDCT
365
 * @param out 256 output frequency coefficients
366
 * @param in  512 windowed input audio samples
367
 */
368
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
369
{
370
    int i, re, im;
371
    int16_t *rot = mdct->rot_tmp;
372
    IComplex *x  = mdct->cplx_tmp;
373

    
374
    /* shift to simplify computations */
375
    for (i = 0; i < MDCT_SAMPLES/4; i++)
376
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
377
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
378

    
379
    /* pre rotation */
380
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
381
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
382
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
383
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
384
    }
385

    
386
    fft(x, MDCT_NBITS - 2);
387

    
388
    /* post rotation */
389
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
390
        re = x[i].re;
391
        im = x[i].im;
392
        CMUL(out[MDCT_SAMPLES/2-1-2*i], out[2*i], re, im, xsin1[i], xcos1[i]);
393
    }
394
}
395

    
396

    
397
/**
398
 * Apply KBD window to input samples prior to MDCT.
399
 */
400
static void apply_window(int16_t *output, const int16_t *input,
401
                         const int16_t *window, int n)
402
{
403
    int i;
404
    int n2 = n >> 1;
405

    
406
    for (i = 0; i < n2; i++) {
407
        output[i]     = MUL16(input[i],     window[i]) >> 15;
408
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
409
    }
410
}
411

    
412

    
413
/**
414
 * Calculate the log2() of the maximum absolute value in an array.
415
 * @param tab input array
416
 * @param n   number of values in the array
417
 * @return    log2(max(abs(tab[])))
418
 */
419
static int log2_tab(int16_t *tab, int n)
420
{
421
    int i, v;
422

    
423
    v = 0;
424
    for (i = 0; i < n; i++)
425
        v |= abs(tab[i]);
426

    
427
    return av_log2(v);
428
}
429

    
430

    
431
/**
432
 * Left-shift each value in an array by a specified amount.
433
 * @param tab    input array
434
 * @param n      number of values in the array
435
 * @param lshift left shift amount. a negative value means right shift.
436
 */
437
static void lshift_tab(int16_t *tab, int n, int lshift)
438
{
439
    int i;
440

    
441
    if (lshift > 0) {
442
        for (i = 0; i < n; i++)
443
            tab[i] <<= lshift;
444
    } else if (lshift < 0) {
445
        lshift = -lshift;
446
        for (i = 0; i < n; i++)
447
            tab[i] >>= lshift;
448
    }
449
}
450

    
451

    
452
/**
453
 * Normalize the input samples to use the maximum available precision.
454
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
455
 * match the 24-bit internal precision for MDCT coefficients.
456
 *
457
 * @return exponent shift
458
 */
459
static int normalize_samples(AC3EncodeContext *s)
460
{
461
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
462
    v = FFMAX(0, v);
463
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
464
    return v - 9;
465
}
466

    
467

    
468
/**
469
 * Apply the MDCT to input samples to generate frequency coefficients.
470
 * This applies the KBD window and normalizes the input to reduce precision
471
 * loss due to fixed-point calculations.
472
 */
473
static void apply_mdct(AC3EncodeContext *s)
474
{
475
    int blk, ch;
476

    
477
    for (ch = 0; ch < s->channels; ch++) {
478
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
479
            AC3Block *block = &s->blocks[blk];
480
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
481

    
482
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
483

    
484
            block->exp_shift[ch] = normalize_samples(s);
485

    
486
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
487
        }
488
    }
489
}
490

    
491

    
492
/**
493
 * Initialize exponent tables.
494
 */
495
static av_cold void exponent_init(AC3EncodeContext *s)
496
{
497
    int i;
498
    for (i = 73; i < 256; i++) {
499
        exponent_group_tab[0][i] = (i - 1) /  3;
500
        exponent_group_tab[1][i] = (i + 2) /  6;
501
        exponent_group_tab[2][i] = (i + 8) / 12;
502
    }
503
}
504

    
505

    
506
/**
507
 * Extract exponents from the MDCT coefficients.
508
 * This takes into account the normalization that was done to the input samples
509
 * by adjusting the exponents by the exponent shift values.
510
 */
511
static void extract_exponents(AC3EncodeContext *s)
512
{
513
    int blk, ch, i;
514

    
515
    for (ch = 0; ch < s->channels; ch++) {
516
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
517
            AC3Block *block = &s->blocks[blk];
518
            for (i = 0; i < AC3_MAX_COEFS; i++) {
519
                int e;
520
                int v = abs(block->mdct_coef[ch][i]);
521
                if (v == 0)
522
                    e = 24;
523
                else {
524
                    e = 23 - av_log2(v) + block->exp_shift[ch];
525
                    if (e >= 24) {
526
                        e = 24;
527
                        block->mdct_coef[ch][i] = 0;
528
                    }
529
                }
530
                block->exp[ch][i] = e;
531
            }
532
        }
533
    }
534
}
535

    
536

    
537
/**
538
 * Exponent Difference Threshold.
539
 * New exponents are sent if their SAD exceed this number.
540
 */
541
#define EXP_DIFF_THRESHOLD 1000
542

    
543

    
544
/**
545
 * Calculate exponent strategies for all blocks in a single channel.
546
 */
547
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp)
548
{
549
    int blk, blk1;
550
    int exp_diff;
551

    
552
    /* estimate if the exponent variation & decide if they should be
553
       reused in the next frame */
554
    exp_strategy[0] = EXP_NEW;
555
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
556
        exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
557
        if (exp_diff > EXP_DIFF_THRESHOLD)
558
            exp_strategy[blk] = EXP_NEW;
559
        else
560
            exp_strategy[blk] = EXP_REUSE;
561
    }
562

    
563
    /* now select the encoding strategy type : if exponents are often
564
       recoded, we use a coarse encoding */
565
    blk = 0;
566
    while (blk < AC3_MAX_BLOCKS) {
567
        blk1 = blk + 1;
568
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
569
            blk1++;
570
        switch (blk1 - blk) {
571
        case 1:  exp_strategy[blk] = EXP_D45; break;
572
        case 2:
573
        case 3:  exp_strategy[blk] = EXP_D25; break;
574
        default: exp_strategy[blk] = EXP_D15; break;
575
        }
576
        blk = blk1;
577
    }
578
}
579

    
580

    
581
/**
582
 * Calculate exponent strategies for all channels.
583
 * Array arrangement is reversed to simplify the per-channel calculation.
584
 */
585
static void compute_exp_strategy(AC3EncodeContext *s)
586
{
587
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
588
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
589
    int ch, blk;
590

    
591
    for (ch = 0; ch < s->fbw_channels; ch++) {
592
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
593
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
594
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
595
        }
596

    
597
        compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
598

    
599
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
600
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
601
    }
602
    if (s->lfe_on) {
603
        ch = s->lfe_channel;
604
        s->blocks[0].exp_strategy[ch] = EXP_D15;
605
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
606
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
607
    }
608
}
609

    
610

    
611
/**
612
 * Set each encoded exponent in a block to the minimum of itself and the
613
 * exponent in the same frequency bin of a following block.
614
 * exp[i] = min(exp[i], exp1[i]
615
 */
616
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
617
{
618
    int i;
619
    for (i = 0; i < n; i++) {
620
        if (exp1[i] < exp[i])
621
            exp[i] = exp1[i];
622
    }
623
}
624

    
625

    
626
/**
627
 * Update the exponents so that they are the ones the decoder will decode.
628
 */
629
static void encode_exponents_blk_ch(uint8_t *exp,
630
                                    int nb_exps, int exp_strategy)
631
{
632
    int nb_groups, i, k;
633

    
634
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
635

    
636
    /* for each group, compute the minimum exponent */
637
    switch(exp_strategy) {
638
    case EXP_D25:
639
        for (i = 1, k = 1; i <= nb_groups; i++) {
640
            uint8_t exp_min = exp[k];
641
            if (exp[k+1] < exp_min)
642
                exp_min = exp[k+1];
643
            exp[i] = exp_min;
644
            k += 2;
645
        }
646
        break;
647
    case EXP_D45:
648
        for (i = 1, k = 1; i <= nb_groups; i++) {
649
            uint8_t exp_min = exp[k];
650
            if (exp[k+1] < exp_min)
651
                exp_min = exp[k+1];
652
            if (exp[k+2] < exp_min)
653
                exp_min = exp[k+2];
654
            if (exp[k+3] < exp_min)
655
                exp_min = exp[k+3];
656
            exp[i] = exp_min;
657
            k += 4;
658
        }
659
        break;
660
    }
661

    
662
    /* constraint for DC exponent */
663
    if (exp[0] > 15)
664
        exp[0] = 15;
665

    
666
    /* decrease the delta between each groups to within 2 so that they can be
667
       differentially encoded */
668
    for (i = 1; i <= nb_groups; i++)
669
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
670
    i--;
671
    while (--i >= 0)
672
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
673

    
674
    /* now we have the exponent values the decoder will see */
675
    switch (exp_strategy) {
676
    case EXP_D25:
677
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
678
            uint8_t exp1 = exp[i];
679
            exp[k--] = exp1;
680
            exp[k--] = exp1;
681
        }
682
        break;
683
    case EXP_D45:
684
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
685
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
686
            k -= 4;
687
        }
688
        break;
689
    }
690
}
691

    
692

    
693
/**
694
 * Encode exponents from original extracted form to what the decoder will see.
695
 * This copies and groups exponents based on exponent strategy and reduces
696
 * deltas between adjacent exponent groups so that they can be differentially
697
 * encoded.
698
 */
699
static void encode_exponents(AC3EncodeContext *s)
700
{
701
    int blk, blk1, blk2, ch;
702
    AC3Block *block, *block1, *block2;
703

    
704
    for (ch = 0; ch < s->channels; ch++) {
705
        blk = 0;
706
        block = &s->blocks[0];
707
        while (blk < AC3_MAX_BLOCKS) {
708
            blk1 = blk + 1;
709
            block1 = block + 1;
710
            /* for the EXP_REUSE case we select the min of the exponents */
711
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
712
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
713
                blk1++;
714
                block1++;
715
            }
716
            encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
717
                                    block->exp_strategy[ch]);
718
            /* copy encoded exponents for reuse case */
719
            block2 = block + 1;
720
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
721
                memcpy(block2->exp[ch], block->exp[ch],
722
                       s->nb_coefs[ch] * sizeof(uint8_t));
723
            }
724
            blk = blk1;
725
            block = block1;
726
        }
727
    }
728
}
729

    
730

    
731
/**
732
 * Group exponents.
733
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
734
 * varies depending on exponent strategy and bandwidth.
735
 */
736
static void group_exponents(AC3EncodeContext *s)
737
{
738
    int blk, ch, i;
739
    int group_size, nb_groups, bit_count;
740
    uint8_t *p;
741
    int delta0, delta1, delta2;
742
    int exp0, exp1;
743

    
744
    bit_count = 0;
745
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
746
        AC3Block *block = &s->blocks[blk];
747
        for (ch = 0; ch < s->channels; ch++) {
748
            if (block->exp_strategy[ch] == EXP_REUSE) {
749
                continue;
750
            }
751
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
752
            nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
753
            bit_count += 4 + (nb_groups * 7);
754
            p = block->exp[ch];
755

    
756
            /* DC exponent */
757
            exp1 = *p++;
758
            block->grouped_exp[ch][0] = exp1;
759

    
760
            /* remaining exponents are delta encoded */
761
            for (i = 1; i <= nb_groups; i++) {
762
                /* merge three delta in one code */
763
                exp0   = exp1;
764
                exp1   = p[0];
765
                p     += group_size;
766
                delta0 = exp1 - exp0 + 2;
767

    
768
                exp0   = exp1;
769
                exp1   = p[0];
770
                p     += group_size;
771
                delta1 = exp1 - exp0 + 2;
772

    
773
                exp0   = exp1;
774
                exp1   = p[0];
775
                p     += group_size;
776
                delta2 = exp1 - exp0 + 2;
777

    
778
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
779
            }
780
        }
781
    }
782

    
783
    s->exponent_bits = bit_count;
784
}
785

    
786

    
787
/**
788
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
789
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
790
 * and encode final exponents.
791
 */
792
static void process_exponents(AC3EncodeContext *s)
793
{
794
    extract_exponents(s);
795

    
796
    compute_exp_strategy(s);
797

    
798
    encode_exponents(s);
799

    
800
    group_exponents(s);
801
}
802

    
803

    
804
/**
805
 * Count frame bits that are based solely on fixed parameters.
806
 * This only has to be run once when the encoder is initialized.
807
 */
808
static void count_frame_bits_fixed(AC3EncodeContext *s)
809
{
810
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
811
    int blk;
812
    int frame_bits;
813

    
814
    /* assumptions:
815
     *   no dynamic range codes
816
     *   no channel coupling
817
     *   no rematrixing
818
     *   bit allocation parameters do not change between blocks
819
     *   SNR offsets do not change between blocks
820
     *   no delta bit allocation
821
     *   no skipped data
822
     *   no auxilliary data
823
     */
824

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

    
829
    /* audio blocks */
830
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
831
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
832
        if (s->channel_mode == AC3_CHMODE_STEREO) {
833
            frame_bits++; /* rematstr */
834
            if (!blk)
835
                frame_bits += 4;
836
        }
837
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
838
        if (s->lfe_on)
839
            frame_bits++; /* lfeexpstr */
840
        frame_bits++; /* baie */
841
        frame_bits++; /* snr */
842
        frame_bits += 2; /* delta / skip */
843
    }
844
    frame_bits++; /* cplinu for block 0 */
845
    /* bit alloc info */
846
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
847
    /* csnroffset[6] */
848
    /* (fsnoffset[4] + fgaincod[4]) * c */
849
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
850

    
851
    /* auxdatae, crcrsv */
852
    frame_bits += 2;
853

    
854
    /* CRC */
855
    frame_bits += 16;
856

    
857
    s->frame_bits_fixed = frame_bits;
858
}
859

    
860

    
861
/**
862
 * Initialize bit allocation.
863
 * Set default parameter codes and calculate parameter values.
864
 */
865
static void bit_alloc_init(AC3EncodeContext *s)
866
{
867
    int ch;
868

    
869
    /* init default parameters */
870
    s->slow_decay_code = 2;
871
    s->fast_decay_code = 1;
872
    s->slow_gain_code  = 1;
873
    s->db_per_bit_code = 2;
874
    s->floor_code      = 4;
875
    for (ch = 0; ch < s->channels; ch++)
876
        s->fast_gain_code[ch] = 4;
877

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

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

    
890
    count_frame_bits_fixed(s);
891
}
892

    
893

    
894
/**
895
 * Count the bits used to encode the frame, minus exponents and mantissas.
896
 * Bits based on fixed parameters have already been counted, so now we just
897
 * have to add the bits based on parameters that change during encoding.
898
 */
899
static void count_frame_bits(AC3EncodeContext *s)
900
{
901
    int blk, ch;
902
    int frame_bits = 0;
903

    
904
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
905
        uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
906
        for (ch = 0; ch < s->fbw_channels; ch++) {
907
            if (exp_strategy[ch] != EXP_REUSE)
908
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
909
        }
910
    }
911
    s->frame_bits = s->frame_bits_fixed + frame_bits;
912
}
913

    
914

    
915
/**
916
 * Calculate the number of bits needed to encode a set of mantissas.
917
 */
918
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
919
{
920
    int bits, b, i;
921

    
922
    bits = 0;
923
    for (i = 0; i < nb_coefs; i++) {
924
        b = bap[i];
925
        if (b <= 4) {
926
            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
927
            mant_cnt[b]++;
928
        } else if (b <= 13) {
929
            // bap=5 to bap=13 use (bap-1) bits
930
            bits += b - 1;
931
        } else {
932
            // bap=14 uses 14 bits and bap=15 uses 16 bits
933
            bits += (b == 14) ? 14 : 16;
934
        }
935
    }
936
    return bits;
937
}
938

    
939

    
940
/**
941
 * Finalize the mantissa bit count by adding in the grouped mantissas.
942
 */
943
static int compute_mantissa_size_final(int mant_cnt[5])
944
{
945
    // bap=1 : 3 mantissas in 5 bits
946
    int bits = (mant_cnt[1] / 3) * 5;
947
    // bap=2 : 3 mantissas in 7 bits
948
    // bap=4 : 2 mantissas in 7 bits
949
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
950
    // bap=3 : each mantissa is 3 bits
951
    bits += mant_cnt[3] * 3;
952
    return bits;
953
}
954

    
955

    
956
/**
957
 * Calculate masking curve based on the final exponents.
958
 * Also calculate the power spectral densities to use in future calculations.
959
 */
960
static void bit_alloc_masking(AC3EncodeContext *s)
961
{
962
    int blk, ch;
963

    
964
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
965
        AC3Block *block = &s->blocks[blk];
966
        for (ch = 0; ch < s->channels; ch++) {
967
            /* We only need psd and mask for calculating bap.
968
               Since we currently do not calculate bap when exponent
969
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
970
            if (block->exp_strategy[ch] != EXP_REUSE) {
971
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
972
                                          s->nb_coefs[ch],
973
                                          block->psd[ch], block->band_psd[ch]);
974
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
975
                                           0, s->nb_coefs[ch],
976
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
977
                                           ch == s->lfe_channel,
978
                                           DBA_NONE, 0, NULL, NULL, NULL,
979
                                           block->mask[ch]);
980
            }
981
        }
982
    }
983
}
984

    
985

    
986
/**
987
 * Ensure that bap for each block and channel point to the current bap_buffer.
988
 * They may have been switched during the bit allocation search.
989
 */
990
static void reset_block_bap(AC3EncodeContext *s)
991
{
992
    int blk, ch;
993
    if (s->blocks[0].bap[0] == s->bap_buffer)
994
        return;
995
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
996
        for (ch = 0; ch < s->channels; ch++) {
997
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
998
        }
999
    }
1000
}
1001

    
1002

    
1003
/**
1004
 * Run the bit allocation with a given SNR offset.
1005
 * This calculates the bit allocation pointers that will be used to determine
1006
 * the quantization of each mantissa.
1007
 * @return the number of bits needed for mantissas if the given SNR offset is
1008
 *         is used.
1009
 */
1010
static int bit_alloc(AC3EncodeContext *s,
1011
                     int snr_offset)
1012
{
1013
    int blk, ch;
1014
    int mantissa_bits;
1015
    int mant_cnt[5];
1016

    
1017
    snr_offset = (snr_offset - 240) << 2;
1018

    
1019
    reset_block_bap(s);
1020
    mantissa_bits = 0;
1021
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1022
        AC3Block *block = &s->blocks[blk];
1023
        // initialize grouped mantissa counts. these are set so that they are
1024
        // padded to the next whole group size when bits are counted in
1025
        // compute_mantissa_size_final
1026
        mant_cnt[0] = mant_cnt[3] = 0;
1027
        mant_cnt[1] = mant_cnt[2] = 2;
1028
        mant_cnt[4] = 1;
1029
        for (ch = 0; ch < s->channels; ch++) {
1030
            /* Currently the only bit allocation parameters which vary across
1031
               blocks within a frame are the exponent values.  We can take
1032
               advantage of that by reusing the bit allocation pointers
1033
               whenever we reuse exponents. */
1034
            if (block->exp_strategy[ch] == EXP_REUSE) {
1035
                memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
1036
            } else {
1037
                ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1038
                                          s->nb_coefs[ch], snr_offset,
1039
                                          s->bit_alloc.floor, ff_ac3_bap_tab,
1040
                                          block->bap[ch]);
1041
            }
1042
            mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1043
        }
1044
        mantissa_bits += compute_mantissa_size_final(mant_cnt);
1045
    }
1046
    return mantissa_bits;
1047
}
1048

    
1049

    
1050
/**
1051
 * Constant bitrate bit allocation search.
1052
 * Find the largest SNR offset that will allow data to fit in the frame.
1053
 */
1054
static int cbr_bit_allocation(AC3EncodeContext *s)
1055
{
1056
    int ch;
1057
    int bits_left;
1058
    int snr_offset;
1059

    
1060
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1061

    
1062
    snr_offset = s->coarse_snr_offset << 4;
1063

    
1064
    while (snr_offset >= 0 &&
1065
           bit_alloc(s, snr_offset) > bits_left) {
1066
        snr_offset -= 64;
1067
    }
1068
    if (snr_offset < 0)
1069
        return AVERROR(EINVAL);
1070

    
1071
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1072
    while (snr_offset + 64 <= 1023 &&
1073
           bit_alloc(s, snr_offset + 64) <= bits_left) {
1074
        snr_offset += 64;
1075
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1076
    }
1077
    while (snr_offset + 16 <= 1023 &&
1078
           bit_alloc(s, snr_offset + 16) <= bits_left) {
1079
        snr_offset += 16;
1080
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1081
    }
1082
    while (snr_offset + 4 <= 1023 &&
1083
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1084
        snr_offset += 4;
1085
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1086
    }
1087
    while (snr_offset + 1 <= 1023 &&
1088
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1089
        snr_offset++;
1090
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1091
    }
1092
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1093
    reset_block_bap(s);
1094

    
1095
    s->coarse_snr_offset = snr_offset >> 4;
1096
    for (ch = 0; ch < s->channels; ch++)
1097
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1098

    
1099
    return 0;
1100
}
1101

    
1102

    
1103
/**
1104
 * Perform bit allocation search.
1105
 * Finds the SNR offset value that maximizes quality and fits in the specified
1106
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1107
 * used to quantize the mantissas.
1108
 */
1109
static int compute_bit_allocation(AC3EncodeContext *s)
1110
{
1111
    count_frame_bits(s);
1112

    
1113
    bit_alloc_masking(s);
1114

    
1115
    return cbr_bit_allocation(s);
1116
}
1117

    
1118

    
1119
/**
1120
 * Symmetric quantization on 'levels' levels.
1121
 */
1122
static inline int sym_quant(int c, int e, int levels)
1123
{
1124
    int v;
1125

    
1126
    if (c >= 0) {
1127
        v = (levels * (c << e)) >> 24;
1128
        v = (v + 1) >> 1;
1129
        v = (levels >> 1) + v;
1130
    } else {
1131
        v = (levels * ((-c) << e)) >> 24;
1132
        v = (v + 1) >> 1;
1133
        v = (levels >> 1) - v;
1134
    }
1135
    assert(v >= 0 && v < levels);
1136
    return v;
1137
}
1138

    
1139

    
1140
/**
1141
 * Asymmetric quantization on 2^qbits levels.
1142
 */
1143
static inline int asym_quant(int c, int e, int qbits)
1144
{
1145
    int lshift, m, v;
1146

    
1147
    lshift = e + qbits - 24;
1148
    if (lshift >= 0)
1149
        v = c << lshift;
1150
    else
1151
        v = c >> (-lshift);
1152
    /* rounding */
1153
    v = (v + 1) >> 1;
1154
    m = (1 << (qbits-1));
1155
    if (v >= m)
1156
        v = m - 1;
1157
    assert(v >= -m);
1158
    return v & ((1 << qbits)-1);
1159
}
1160

    
1161

    
1162
/**
1163
 * Quantize a set of mantissas for a single channel in a single block.
1164
 */
1165
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1166
                                      int32_t *mdct_coef, int8_t exp_shift,
1167
                                      uint8_t *exp, uint8_t *bap,
1168
                                      uint16_t *qmant, int n)
1169
{
1170
    int i;
1171

    
1172
    for (i = 0; i < n; i++) {
1173
        int v;
1174
        int c = mdct_coef[i];
1175
        int e = exp[i] - exp_shift;
1176
        int b = bap[i];
1177
        switch (b) {
1178
        case 0:
1179
            v = 0;
1180
            break;
1181
        case 1:
1182
            v = sym_quant(c, e, 3);
1183
            switch (s->mant1_cnt) {
1184
            case 0:
1185
                s->qmant1_ptr = &qmant[i];
1186
                v = 9 * v;
1187
                s->mant1_cnt = 1;
1188
                break;
1189
            case 1:
1190
                *s->qmant1_ptr += 3 * v;
1191
                s->mant1_cnt = 2;
1192
                v = 128;
1193
                break;
1194
            default:
1195
                *s->qmant1_ptr += v;
1196
                s->mant1_cnt = 0;
1197
                v = 128;
1198
                break;
1199
            }
1200
            break;
1201
        case 2:
1202
            v = sym_quant(c, e, 5);
1203
            switch (s->mant2_cnt) {
1204
            case 0:
1205
                s->qmant2_ptr = &qmant[i];
1206
                v = 25 * v;
1207
                s->mant2_cnt = 1;
1208
                break;
1209
            case 1:
1210
                *s->qmant2_ptr += 5 * v;
1211
                s->mant2_cnt = 2;
1212
                v = 128;
1213
                break;
1214
            default:
1215
                *s->qmant2_ptr += v;
1216
                s->mant2_cnt = 0;
1217
                v = 128;
1218
                break;
1219
            }
1220
            break;
1221
        case 3:
1222
            v = sym_quant(c, e, 7);
1223
            break;
1224
        case 4:
1225
            v = sym_quant(c, e, 11);
1226
            switch (s->mant4_cnt) {
1227
            case 0:
1228
                s->qmant4_ptr = &qmant[i];
1229
                v = 11 * v;
1230
                s->mant4_cnt = 1;
1231
                break;
1232
            default:
1233
                *s->qmant4_ptr += v;
1234
                s->mant4_cnt = 0;
1235
                v = 128;
1236
                break;
1237
            }
1238
            break;
1239
        case 5:
1240
            v = sym_quant(c, e, 15);
1241
            break;
1242
        case 14:
1243
            v = asym_quant(c, e, 14);
1244
            break;
1245
        case 15:
1246
            v = asym_quant(c, e, 16);
1247
            break;
1248
        default:
1249
            v = asym_quant(c, e, b - 1);
1250
            break;
1251
        }
1252
        qmant[i] = v;
1253
    }
1254
}
1255

    
1256

    
1257
/**
1258
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1259
 */
1260
static void quantize_mantissas(AC3EncodeContext *s)
1261
{
1262
    int blk, ch;
1263

    
1264

    
1265
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1266
        AC3Block *block = &s->blocks[blk];
1267
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1268
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1269

    
1270
        for (ch = 0; ch < s->channels; ch++) {
1271
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1272
                                      block->exp[ch], block->bap[ch],
1273
                                      block->qmant[ch], s->nb_coefs[ch]);
1274
        }
1275
    }
1276
}
1277

    
1278

    
1279
/**
1280
 * Write the AC-3 frame header to the output bitstream.
1281
 */
1282
static void output_frame_header(AC3EncodeContext *s)
1283
{
1284
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1285
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1286
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1287
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1288
    put_bits(&s->pb, 5,  s->bitstream_id);
1289
    put_bits(&s->pb, 3,  s->bitstream_mode);
1290
    put_bits(&s->pb, 3,  s->channel_mode);
1291
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1292
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1293
    if (s->channel_mode & 0x04)
1294
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1295
    if (s->channel_mode == AC3_CHMODE_STEREO)
1296
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1297
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1298
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1299
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1300
    put_bits(&s->pb, 1, 0);         /* no lang code */
1301
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1302
    put_bits(&s->pb, 1, 0);         /* no copyright */
1303
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1304
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1305
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1306
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1307
}
1308

    
1309

    
1310
/**
1311
 * Write one audio block to the output bitstream.
1312
 */
1313
static void output_audio_block(AC3EncodeContext *s,
1314
                               int block_num)
1315
{
1316
    int ch, i, baie, rbnd;
1317
    AC3Block *block = &s->blocks[block_num];
1318

    
1319
    /* block switching */
1320
    for (ch = 0; ch < s->fbw_channels; ch++)
1321
        put_bits(&s->pb, 1, 0);
1322

    
1323
    /* dither flags */
1324
    for (ch = 0; ch < s->fbw_channels; ch++)
1325
        put_bits(&s->pb, 1, 1);
1326

    
1327
    /* dynamic range codes */
1328
    put_bits(&s->pb, 1, 0);
1329

    
1330
    /* channel coupling */
1331
    if (!block_num) {
1332
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1333
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1334
    } else {
1335
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1336
    }
1337

    
1338
    /* stereo rematrixing */
1339
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1340
        if (!block_num) {
1341
            /* first block must define rematrixing (rematstr) */
1342
            put_bits(&s->pb, 1, 1);
1343

    
1344
            /* dummy rematrixing rematflg(1:4)=0 */
1345
            for (rbnd = 0; rbnd < 4; rbnd++)
1346
                put_bits(&s->pb, 1, 0);
1347
        } else {
1348
            /* no matrixing (but should be used in the future) */
1349
            put_bits(&s->pb, 1, 0);
1350
        }
1351
    }
1352

    
1353
    /* exponent strategy */
1354
    for (ch = 0; ch < s->fbw_channels; ch++)
1355
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1356
    if (s->lfe_on)
1357
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1358

    
1359
    /* bandwidth */
1360
    for (ch = 0; ch < s->fbw_channels; ch++) {
1361
        if (block->exp_strategy[ch] != EXP_REUSE)
1362
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1363
    }
1364

    
1365
    /* exponents */
1366
    for (ch = 0; ch < s->channels; ch++) {
1367
        int nb_groups;
1368

    
1369
        if (block->exp_strategy[ch] == EXP_REUSE)
1370
            continue;
1371

    
1372
        /* DC exponent */
1373
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1374

    
1375
        /* exponent groups */
1376
        nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
1377
        for (i = 1; i <= nb_groups; i++)
1378
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1379

    
1380
        /* gain range info */
1381
        if (ch != s->lfe_channel)
1382
            put_bits(&s->pb, 2, 0);
1383
    }
1384

    
1385
    /* bit allocation info */
1386
    baie = (block_num == 0);
1387
    put_bits(&s->pb, 1, baie);
1388
    if (baie) {
1389
        put_bits(&s->pb, 2, s->slow_decay_code);
1390
        put_bits(&s->pb, 2, s->fast_decay_code);
1391
        put_bits(&s->pb, 2, s->slow_gain_code);
1392
        put_bits(&s->pb, 2, s->db_per_bit_code);
1393
        put_bits(&s->pb, 3, s->floor_code);
1394
    }
1395

    
1396
    /* snr offset */
1397
    put_bits(&s->pb, 1, baie);
1398
    if (baie) {
1399
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1400
        for (ch = 0; ch < s->channels; ch++) {
1401
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1402
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1403
        }
1404
    }
1405

    
1406
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1407
    put_bits(&s->pb, 1, 0); /* no data to skip */
1408

    
1409
    /* mantissas */
1410
    for (ch = 0; ch < s->channels; ch++) {
1411
        int b, q;
1412
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1413
            q = block->qmant[ch][i];
1414
            b = block->bap[ch][i];
1415
            switch (b) {
1416
            case 0:                                         break;
1417
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1418
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1419
            case 3:               put_bits(&s->pb,   3, q); break;
1420
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1421
            case 14:              put_bits(&s->pb,  14, q); break;
1422
            case 15:              put_bits(&s->pb,  16, q); break;
1423
            default:              put_bits(&s->pb, b-1, q); break;
1424
            }
1425
        }
1426
    }
1427
}
1428

    
1429

    
1430
/** CRC-16 Polynomial */
1431
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1432

    
1433

    
1434
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1435
{
1436
    unsigned int c;
1437

    
1438
    c = 0;
1439
    while (a) {
1440
        if (a & 1)
1441
            c ^= b;
1442
        a = a >> 1;
1443
        b = b << 1;
1444
        if (b & (1 << 16))
1445
            b ^= poly;
1446
    }
1447
    return c;
1448
}
1449

    
1450

    
1451
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1452
{
1453
    unsigned int r;
1454
    r = 1;
1455
    while (n) {
1456
        if (n & 1)
1457
            r = mul_poly(r, a, poly);
1458
        a = mul_poly(a, a, poly);
1459
        n >>= 1;
1460
    }
1461
    return r;
1462
}
1463

    
1464

    
1465
/**
1466
 * Fill the end of the frame with 0's and compute the two CRCs.
1467
 */
1468
static void output_frame_end(AC3EncodeContext *s)
1469
{
1470
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1471
    uint8_t *frame;
1472

    
1473
    frame_size    = s->frame_size;
1474
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1475

    
1476
    /* pad the remainder of the frame with zeros */
1477
    flush_put_bits(&s->pb);
1478
    frame = s->pb.buf;
1479
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1480
    assert(pad_bytes >= 0);
1481
    if (pad_bytes > 0)
1482
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1483

    
1484
    /* compute crc1 */
1485
    /* this is not so easy because it is at the beginning of the data... */
1486
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1487
                             frame + 4, frame_size_58 - 4));
1488
    /* XXX: could precompute crc_inv */
1489
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1490
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1491
    AV_WB16(frame + 2, crc1);
1492

    
1493
    /* compute crc2 */
1494
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1495
                             frame + frame_size_58,
1496
                             frame_size - frame_size_58 - 2));
1497
    AV_WB16(frame + frame_size - 2, crc2);
1498
}
1499

    
1500

    
1501
/**
1502
 * Write the frame to the output bitstream.
1503
 */
1504
static void output_frame(AC3EncodeContext *s,
1505
                         unsigned char *frame)
1506
{
1507
    int blk;
1508

    
1509
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1510

    
1511
    output_frame_header(s);
1512

    
1513
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1514
        output_audio_block(s, blk);
1515

    
1516
    output_frame_end(s);
1517
}
1518

    
1519

    
1520
/**
1521
 * Encode a single AC-3 frame.
1522
 */
1523
static int ac3_encode_frame(AVCodecContext *avctx,
1524
                            unsigned char *frame, int buf_size, void *data)
1525
{
1526
    AC3EncodeContext *s = avctx->priv_data;
1527
    const int16_t *samples = data;
1528
    int ret;
1529

    
1530
    if (s->bit_alloc.sr_code == 1)
1531
        adjust_frame_size(s);
1532

    
1533
    deinterleave_input_samples(s, samples);
1534

    
1535
    apply_mdct(s);
1536

    
1537
    process_exponents(s);
1538

    
1539
    ret = compute_bit_allocation(s);
1540
    if (ret) {
1541
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1542
        return ret;
1543
    }
1544

    
1545
    quantize_mantissas(s);
1546

    
1547
    output_frame(s, frame);
1548

    
1549
    return s->frame_size;
1550
}
1551

    
1552

    
1553
/**
1554
 * Finalize encoding and free any memory allocated by the encoder.
1555
 */
1556
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1557
{
1558
    int blk, ch;
1559
    AC3EncodeContext *s = avctx->priv_data;
1560

    
1561
    for (ch = 0; ch < s->channels; ch++)
1562
        av_freep(&s->planar_samples[ch]);
1563
    av_freep(&s->planar_samples);
1564
    av_freep(&s->bap_buffer);
1565
    av_freep(&s->bap1_buffer);
1566
    av_freep(&s->mdct_coef_buffer);
1567
    av_freep(&s->exp_buffer);
1568
    av_freep(&s->grouped_exp_buffer);
1569
    av_freep(&s->psd_buffer);
1570
    av_freep(&s->band_psd_buffer);
1571
    av_freep(&s->mask_buffer);
1572
    av_freep(&s->qmant_buffer);
1573
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1574
        AC3Block *block = &s->blocks[blk];
1575
        av_freep(&block->bap);
1576
        av_freep(&block->mdct_coef);
1577
        av_freep(&block->exp);
1578
        av_freep(&block->grouped_exp);
1579
        av_freep(&block->psd);
1580
        av_freep(&block->band_psd);
1581
        av_freep(&block->mask);
1582
        av_freep(&block->qmant);
1583
    }
1584

    
1585
    mdct_end(&s->mdct);
1586

    
1587
    av_freep(&avctx->coded_frame);
1588
    return 0;
1589
}
1590

    
1591

    
1592
/**
1593
 * Set channel information during initialization.
1594
 */
1595
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1596
                                    int64_t *channel_layout)
1597
{
1598
    int ch_layout;
1599

    
1600
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1601
        return AVERROR(EINVAL);
1602
    if ((uint64_t)*channel_layout > 0x7FF)
1603
        return AVERROR(EINVAL);
1604
    ch_layout = *channel_layout;
1605
    if (!ch_layout)
1606
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1607
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1608
        return AVERROR(EINVAL);
1609

    
1610
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1611
    s->channels     = channels;
1612
    s->fbw_channels = channels - s->lfe_on;
1613
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1614
    if (s->lfe_on)
1615
        ch_layout -= AV_CH_LOW_FREQUENCY;
1616

    
1617
    switch (ch_layout) {
1618
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1619
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1620
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1621
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1622
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1623
    case AV_CH_LAYOUT_QUAD:
1624
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1625
    case AV_CH_LAYOUT_5POINT0:
1626
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1627
    default:
1628
        return AVERROR(EINVAL);
1629
    }
1630

    
1631
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1632
    *channel_layout = ch_layout;
1633
    if (s->lfe_on)
1634
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1635

    
1636
    return 0;
1637
}
1638

    
1639

    
1640
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1641
{
1642
    int i, ret;
1643

    
1644
    /* validate channel layout */
1645
    if (!avctx->channel_layout) {
1646
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1647
                                      "encoder will guess the layout, but it "
1648
                                      "might be incorrect.\n");
1649
    }
1650
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1651
    if (ret) {
1652
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1653
        return ret;
1654
    }
1655

    
1656
    /* validate sample rate */
1657
    for (i = 0; i < 9; i++) {
1658
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1659
            break;
1660
    }
1661
    if (i == 9) {
1662
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1663
        return AVERROR(EINVAL);
1664
    }
1665
    s->sample_rate        = avctx->sample_rate;
1666
    s->bit_alloc.sr_shift = i % 3;
1667
    s->bit_alloc.sr_code  = i / 3;
1668

    
1669
    /* validate bit rate */
1670
    for (i = 0; i < 19; i++) {
1671
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1672
            break;
1673
    }
1674
    if (i == 19) {
1675
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1676
        return AVERROR(EINVAL);
1677
    }
1678
    s->bit_rate        = avctx->bit_rate;
1679
    s->frame_size_code = i << 1;
1680

    
1681
    return 0;
1682
}
1683

    
1684

    
1685
/**
1686
 * Set bandwidth for all channels.
1687
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1688
 * default value will be used.
1689
 */
1690
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1691
{
1692
    int ch, bw_code;
1693

    
1694
    if (cutoff) {
1695
        /* calculate bandwidth based on user-specified cutoff frequency */
1696
        int fbw_coeffs;
1697
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1698
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1699
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1700
    } else {
1701
        /* use default bandwidth setting */
1702
        /* XXX: should compute the bandwidth according to the frame
1703
           size, so that we avoid annoying high frequency artifacts */
1704
        bw_code = 50;
1705
    }
1706

    
1707
    /* set number of coefficients for each channel */
1708
    for (ch = 0; ch < s->fbw_channels; ch++) {
1709
        s->bandwidth_code[ch] = bw_code;
1710
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1711
    }
1712
    if (s->lfe_on)
1713
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1714
}
1715

    
1716

    
1717
static av_cold int allocate_buffers(AVCodecContext *avctx)
1718
{
1719
    int blk, ch;
1720
    AC3EncodeContext *s = avctx->priv_data;
1721

    
1722
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1723
                     alloc_fail);
1724
    for (ch = 0; ch < s->channels; ch++) {
1725
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1726
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1727
                          alloc_fail);
1728
    }
1729
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1730
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1731
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1732
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1733
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1734
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1735
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1736
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1737
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1738
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1739
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1740
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1741
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1742
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1743
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1744
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1745
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1746
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1747
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1748
        AC3Block *block = &s->blocks[blk];
1749
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1750
                         alloc_fail);
1751
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1752
                          alloc_fail);
1753
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1754
                          alloc_fail);
1755
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1756
                          alloc_fail);
1757
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1758
                          alloc_fail);
1759
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1760
                          alloc_fail);
1761
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1762
                          alloc_fail);
1763
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1764
                          alloc_fail);
1765

    
1766
        for (ch = 0; ch < s->channels; ch++) {
1767
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1768
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1769
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1770
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1771
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1772
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1773
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1774
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1775
        }
1776
    }
1777

    
1778
    return 0;
1779
alloc_fail:
1780
    return AVERROR(ENOMEM);
1781
}
1782

    
1783

    
1784
/**
1785
 * Initialize the encoder.
1786
 */
1787
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1788
{
1789
    AC3EncodeContext *s = avctx->priv_data;
1790
    int ret;
1791

    
1792
    avctx->frame_size = AC3_FRAME_SIZE;
1793

    
1794
    ac3_common_init();
1795

    
1796
    ret = validate_options(avctx, s);
1797
    if (ret)
1798
        return ret;
1799

    
1800
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1801
    s->bitstream_mode = 0; /* complete main audio service */
1802

    
1803
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1804
    s->bits_written    = 0;
1805
    s->samples_written = 0;
1806
    s->frame_size      = s->frame_size_min;
1807

    
1808
    set_bandwidth(s, avctx->cutoff);
1809

    
1810
    exponent_init(s);
1811

    
1812
    bit_alloc_init(s);
1813

    
1814
    s->mdct.avctx = avctx;
1815
    ret = mdct_init(&s->mdct, 9);
1816
    if (ret)
1817
        goto init_fail;
1818

    
1819
    ret = allocate_buffers(avctx);
1820
    if (ret)
1821
        goto init_fail;
1822

    
1823
    avctx->coded_frame= avcodec_alloc_frame();
1824

    
1825
    dsputil_init(&s->dsp, avctx);
1826

    
1827
    return 0;
1828
init_fail:
1829
    ac3_encode_close(avctx);
1830
    return ret;
1831
}
1832

    
1833

    
1834
#ifdef TEST
1835
/*************************************************************************/
1836
/* TEST */
1837

    
1838
#include "libavutil/lfg.h"
1839

    
1840
#define FN (MDCT_SAMPLES/4)
1841

    
1842

    
1843
static void fft_test(AVLFG *lfg)
1844
{
1845
    IComplex in[FN], in1[FN];
1846
    int k, n, i;
1847
    float sum_re, sum_im, a;
1848

    
1849
    for (i = 0; i < FN; i++) {
1850
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1851
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1852
        in1[i]   = in[i];
1853
    }
1854
    fft(in, 7);
1855

    
1856
    /* do it by hand */
1857
    for (k = 0; k < FN; k++) {
1858
        sum_re = 0;
1859
        sum_im = 0;
1860
        for (n = 0; n < FN; n++) {
1861
            a = -2 * M_PI * (n * k) / FN;
1862
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1863
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1864
        }
1865
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1866
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1867
    }
1868
}
1869

    
1870

    
1871
static void mdct_test(AVLFG *lfg)
1872
{
1873
    int16_t input[MDCT_SAMPLES];
1874
    int32_t output[AC3_MAX_COEFS];
1875
    float input1[MDCT_SAMPLES];
1876
    float output1[AC3_MAX_COEFS];
1877
    float s, a, err, e, emax;
1878
    int i, k, n;
1879

    
1880
    for (i = 0; i < MDCT_SAMPLES; i++) {
1881
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1882
        input1[i] = input[i];
1883
    }
1884

    
1885
    mdct512(output, input);
1886

    
1887
    /* do it by hand */
1888
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1889
        s = 0;
1890
        for (n = 0; n < MDCT_SAMPLES; n++) {
1891
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1892
            s += input1[n] * cos(a);
1893
        }
1894
        output1[k] = -2 * s / MDCT_SAMPLES;
1895
    }
1896

    
1897
    err  = 0;
1898
    emax = 0;
1899
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1900
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1901
        e = output[i] - output1[i];
1902
        if (e > emax)
1903
            emax = e;
1904
        err += e * e;
1905
    }
1906
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1907
}
1908

    
1909

    
1910
int main(void)
1911
{
1912
    AVLFG lfg;
1913

    
1914
    av_log_set_level(AV_LOG_DEBUG);
1915
    mdct_init(9);
1916

    
1917
    fft_test(&lfg);
1918
    mdct_test(&lfg);
1919

    
1920
    return 0;
1921
}
1922
#endif /* TEST */
1923

    
1924

    
1925
AVCodec ac3_encoder = {
1926
    "ac3",
1927
    AVMEDIA_TYPE_AUDIO,
1928
    CODEC_ID_AC3,
1929
    sizeof(AC3EncodeContext),
1930
    ac3_encode_init,
1931
    ac3_encode_frame,
1932
    ac3_encode_close,
1933
    NULL,
1934
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1935
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1936
    .channel_layouts = (const int64_t[]){
1937
        AV_CH_LAYOUT_MONO,
1938
        AV_CH_LAYOUT_STEREO,
1939
        AV_CH_LAYOUT_2_1,
1940
        AV_CH_LAYOUT_SURROUND,
1941
        AV_CH_LAYOUT_2_2,
1942
        AV_CH_LAYOUT_QUAD,
1943
        AV_CH_LAYOUT_4POINT0,
1944
        AV_CH_LAYOUT_5POINT0,
1945
        AV_CH_LAYOUT_5POINT0_BACK,
1946
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1947
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1948
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1949
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1950
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1951
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1952
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1953
        AV_CH_LAYOUT_5POINT1,
1954
        AV_CH_LAYOUT_5POINT1_BACK,
1955
        0 },
1956
};