Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 86c9673b

History | View | Annotate | Download (59.2 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
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
47
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
48

    
49

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

    
58
typedef struct AC3MDCTContext {
59
    AVCodecContext *avctx;                  ///< parent context for av_log()
60
    int nbits;                              ///< log2(transform size)
61
    int16_t *costab;                        ///< FFT cos table
62
    int16_t *sintab;                        ///< FFT sin table
63
    int16_t *xcos1;                         ///< MDCT cos table
64
    int16_t *xsin1;                         ///< MDCT sin table
65
    int16_t *rot_tmp;                       ///< temp buffer for pre-rotated samples
66
    IComplex *cplx_tmp;                     ///< temp buffer for complex pre-rotated samples
67
} AC3MDCTContext;
68

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

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

    
93
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
94

    
95
    int bitstream_id;                       ///< bitstream id                           (bsid)
96
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
97

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

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

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

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

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

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

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

    
146
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
147
} AC3EncodeContext;
148

    
149

    
150
/**
151
 * LUT for number of exponent groups.
152
 * exponent_group_tab[exponent strategy-1][number of coefficients]
153
 */
154
uint8_t exponent_group_tab[3][256];
155

    
156

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

    
173

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

    
183
    /* deinterleave and remap input samples */
184
    for (ch = 0; ch < s->channels; ch++) {
185
        const int16_t *sptr;
186
        int sinc;
187

    
188
        /* copy last 256 samples of previous frame to the start of the current frame */
189
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
190
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
191

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

    
202

    
203
/**
204
 * Finalize MDCT and free allocated memory.
205
 */
206
static av_cold void mdct_end(AC3MDCTContext *mdct)
207
{
208
    mdct->nbits = 0;
209
    av_freep(&mdct->costab);
210
    av_freep(&mdct->sintab);
211
    av_freep(&mdct->xcos1);
212
    av_freep(&mdct->xsin1);
213
    av_freep(&mdct->rot_tmp);
214
    av_freep(&mdct->cplx_tmp);
215
}
216

    
217

    
218

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

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

    
231
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->costab, n2 * sizeof(*mdct->costab),
232
                     fft_alloc_fail);
233
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->sintab, n2 * sizeof(*mdct->sintab),
234
                     fft_alloc_fail);
235

    
236
    for (i = 0; i < n2; i++) {
237
        alpha     = 2.0 * M_PI * i / n;
238
        mdct->costab[i] = FIX15(cos(alpha));
239
        mdct->sintab[i] = FIX15(sin(alpha));
240
    }
241

    
242
    return 0;
243
fft_alloc_fail:
244
    mdct_end(mdct);
245
    return AVERROR(ENOMEM);
246
}
247

    
248

    
249
/**
250
 * Initialize MDCT tables.
251
 * @param nbits log2(MDCT size)
252
 */
253
static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
254
{
255
    int i, n, n4, ret;
256

    
257
    n  = 1 << nbits;
258
    n4 = n >> 2;
259

    
260
    mdct->nbits = nbits;
261

    
262
    ret = fft_init(mdct, nbits - 2);
263
    if (ret)
264
        return ret;
265

    
266
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->xcos1,    n4 * sizeof(*mdct->xcos1),
267
                     mdct_alloc_fail);
268
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->xsin1 ,   n4 * sizeof(*mdct->xsin1),
269
                     mdct_alloc_fail);
270
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),
271
                     mdct_alloc_fail);
272
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
273
                     mdct_alloc_fail);
274

    
275
    for (i = 0; i < n4; i++) {
276
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
277
        mdct->xcos1[i] = FIX15(-cos(alpha));
278
        mdct->xsin1[i] = FIX15(-sin(alpha));
279
    }
280

    
281
    return 0;
282
mdct_alloc_fail:
283
    mdct_end(mdct);
284
    return AVERROR(ENOMEM);
285
}
286

    
287

    
288
/** Butterfly op */
289
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
290
{                                                       \
291
  int ax, ay, bx, by;                                   \
292
  bx  = pre1;                                           \
293
  by  = pim1;                                           \
294
  ax  = qre1;                                           \
295
  ay  = qim1;                                           \
296
  pre = (bx + ax) >> 1;                                 \
297
  pim = (by + ay) >> 1;                                 \
298
  qre = (bx - ax) >> 1;                                 \
299
  qim = (by - ay) >> 1;                                 \
300
}
301

    
302

    
303
/** Complex multiply */
304
#define CMUL(pre, pim, are, aim, bre, bim)              \
305
{                                                       \
306
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
307
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
308
}
309

    
310

    
311
/**
312
 * Calculate a 2^n point complex FFT on 2^ln points.
313
 * @param z  complex input/output samples
314
 * @param ln log2(FFT size)
315
 */
316
static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)
317
{
318
    int j, l, np, np2;
319
    int nblocks, nloops;
320
    register IComplex *p,*q;
321
    int tmp_re, tmp_im;
322

    
323
    np = 1 << ln;
324

    
325
    /* reverse */
326
    for (j = 0; j < np; j++) {
327
        int k = av_reverse[j] >> (8 - ln);
328
        if (k < j)
329
            FFSWAP(IComplex, z[k], z[j]);
330
    }
331

    
332
    /* pass 0 */
333

    
334
    p = &z[0];
335
    j = np >> 1;
336
    do {
337
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
338
           p[0].re, p[0].im, p[1].re, p[1].im);
339
        p += 2;
340
    } while (--j);
341

    
342
    /* pass 1 */
343

    
344
    p = &z[0];
345
    j = np >> 2;
346
    do {
347
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
348
           p[0].re, p[0].im, p[2].re,  p[2].im);
349
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
350
           p[1].re, p[1].im, p[3].im, -p[3].re);
351
        p+=4;
352
    } while (--j);
353

    
354
    /* pass 2 .. ln-1 */
355

    
356
    nblocks = np >> 3;
357
    nloops  =  1 << 2;
358
    np2     = np >> 1;
359
    do {
360
        p = z;
361
        q = z + nloops;
362
        for (j = 0; j < nblocks; j++) {
363
            BF(p->re, p->im, q->re, q->im,
364
               p->re, p->im, q->re, q->im);
365
            p++;
366
            q++;
367
            for(l = nblocks; l < np2; l += nblocks) {
368
                CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);
369
                BF(p->re, p->im, q->re,  q->im,
370
                   p->re, p->im, tmp_re, tmp_im);
371
                p++;
372
                q++;
373
            }
374
            p += nloops;
375
            q += nloops;
376
        }
377
        nblocks = nblocks >> 1;
378
        nloops  = nloops  << 1;
379
    } while (nblocks);
380
}
381

    
382

    
383
/**
384
 * Calculate a 512-point MDCT
385
 * @param out 256 output frequency coefficients
386
 * @param in  512 windowed input audio samples
387
 */
388
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
389
{
390
    int i, re, im, n, n2, n4;
391
    int16_t *rot = mdct->rot_tmp;
392
    IComplex *x  = mdct->cplx_tmp;
393

    
394
    n  = 1 << mdct->nbits;
395
    n2 = n >> 1;
396
    n4 = n >> 2;
397

    
398
    /* shift to simplify computations */
399
    for (i = 0; i <n4; i++)
400
        rot[i] = -in[i + 3*n4];
401
    memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in));
402

    
403
    /* pre rotation */
404
    for (i = 0; i < n4; i++) {
405
        re =  ((int)rot[   2*i] - (int)rot[ n-1-2*i]) >> 1;
406
        im = -((int)rot[n2+2*i] - (int)rot[n2-1-2*i]) >> 1;
407
        CMUL(x[i].re, x[i].im, re, im, -mdct->xcos1[i], mdct->xsin1[i]);
408
    }
409

    
410
    fft(mdct, x, mdct->nbits - 2);
411

    
412
    /* post rotation */
413
    for (i = 0; i < n4; i++) {
414
        re = x[i].re;
415
        im = x[i].im;
416
        CMUL(out[n2-1-2*i], out[2*i], re, im, mdct->xsin1[i], mdct->xcos1[i]);
417
    }
418
}
419

    
420

    
421
/**
422
 * Apply KBD window to input samples prior to MDCT.
423
 */
424
static void apply_window(int16_t *output, const int16_t *input,
425
                         const int16_t *window, int n)
426
{
427
    int i;
428
    int n2 = n >> 1;
429

    
430
    for (i = 0; i < n2; i++) {
431
        output[i]     = MUL16(input[i],     window[i]) >> 15;
432
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
433
    }
434
}
435

    
436

    
437
/**
438
 * Calculate the log2() of the maximum absolute value in an array.
439
 * @param tab input array
440
 * @param n   number of values in the array
441
 * @return    log2(max(abs(tab[])))
442
 */
443
static int log2_tab(int16_t *tab, int n)
444
{
445
    int i, v;
446

    
447
    v = 0;
448
    for (i = 0; i < n; i++)
449
        v |= abs(tab[i]);
450

    
451
    return av_log2(v);
452
}
453

    
454

    
455
/**
456
 * Left-shift each value in an array by a specified amount.
457
 * @param tab    input array
458
 * @param n      number of values in the array
459
 * @param lshift left shift amount. a negative value means right shift.
460
 */
461
static void lshift_tab(int16_t *tab, int n, int lshift)
462
{
463
    int i;
464

    
465
    if (lshift > 0) {
466
        for (i = 0; i < n; i++)
467
            tab[i] <<= lshift;
468
    } else if (lshift < 0) {
469
        lshift = -lshift;
470
        for (i = 0; i < n; i++)
471
            tab[i] >>= lshift;
472
    }
473
}
474

    
475

    
476
/**
477
 * Normalize the input samples to use the maximum available precision.
478
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
479
 * match the 24-bit internal precision for MDCT coefficients.
480
 *
481
 * @return exponent shift
482
 */
483
static int normalize_samples(AC3EncodeContext *s)
484
{
485
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
486
    v = FFMAX(0, v);
487
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
488
    return v - 9;
489
}
490

    
491

    
492
/**
493
 * Apply the MDCT to input samples to generate frequency coefficients.
494
 * This applies the KBD window and normalizes the input to reduce precision
495
 * loss due to fixed-point calculations.
496
 */
497
static void apply_mdct(AC3EncodeContext *s)
498
{
499
    int blk, ch;
500

    
501
    for (ch = 0; ch < s->channels; ch++) {
502
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
503
            AC3Block *block = &s->blocks[blk];
504
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
505

    
506
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
507

    
508
            block->exp_shift[ch] = normalize_samples(s);
509

    
510
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
511
        }
512
    }
513
}
514

    
515

    
516
/**
517
 * Initialize exponent tables.
518
 */
519
static av_cold void exponent_init(AC3EncodeContext *s)
520
{
521
    int i;
522
    for (i = 73; i < 256; i++) {
523
        exponent_group_tab[0][i] = (i - 1) /  3;
524
        exponent_group_tab[1][i] = (i + 2) /  6;
525
        exponent_group_tab[2][i] = (i + 8) / 12;
526
    }
527
}
528

    
529

    
530
/**
531
 * Extract exponents from the MDCT coefficients.
532
 * This takes into account the normalization that was done to the input samples
533
 * by adjusting the exponents by the exponent shift values.
534
 */
535
static void extract_exponents(AC3EncodeContext *s)
536
{
537
    int blk, ch, i;
538

    
539
    for (ch = 0; ch < s->channels; ch++) {
540
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
541
            AC3Block *block = &s->blocks[blk];
542
            for (i = 0; i < AC3_MAX_COEFS; i++) {
543
                int e;
544
                int v = abs(block->mdct_coef[ch][i]);
545
                if (v == 0)
546
                    e = 24;
547
                else {
548
                    e = 23 - av_log2(v) + block->exp_shift[ch];
549
                    if (e >= 24) {
550
                        e = 24;
551
                        block->mdct_coef[ch][i] = 0;
552
                    }
553
                }
554
                block->exp[ch][i] = e;
555
            }
556
        }
557
    }
558
}
559

    
560

    
561
/**
562
 * Exponent Difference Threshold.
563
 * New exponents are sent if their SAD exceed this number.
564
 */
565
#define EXP_DIFF_THRESHOLD 1000
566

    
567

    
568
/**
569
 * Calculate exponent strategies for all blocks in a single channel.
570
 */
571
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp)
572
{
573
    int blk, blk1;
574
    int exp_diff;
575

    
576
    /* estimate if the exponent variation & decide if they should be
577
       reused in the next frame */
578
    exp_strategy[0] = EXP_NEW;
579
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
580
        exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
581
        if (exp_diff > EXP_DIFF_THRESHOLD)
582
            exp_strategy[blk] = EXP_NEW;
583
        else
584
            exp_strategy[blk] = EXP_REUSE;
585
    }
586

    
587
    /* now select the encoding strategy type : if exponents are often
588
       recoded, we use a coarse encoding */
589
    blk = 0;
590
    while (blk < AC3_MAX_BLOCKS) {
591
        blk1 = blk + 1;
592
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
593
            blk1++;
594
        switch (blk1 - blk) {
595
        case 1:  exp_strategy[blk] = EXP_D45; break;
596
        case 2:
597
        case 3:  exp_strategy[blk] = EXP_D25; break;
598
        default: exp_strategy[blk] = EXP_D15; break;
599
        }
600
        blk = blk1;
601
    }
602
}
603

    
604

    
605
/**
606
 * Calculate exponent strategies for all channels.
607
 * Array arrangement is reversed to simplify the per-channel calculation.
608
 */
609
static void compute_exp_strategy(AC3EncodeContext *s)
610
{
611
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
612
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
613
    int ch, blk;
614

    
615
    for (ch = 0; ch < s->fbw_channels; ch++) {
616
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
617
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
618
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
619
        }
620

    
621
        compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
622

    
623
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
624
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
625
    }
626
    if (s->lfe_on) {
627
        ch = s->lfe_channel;
628
        s->blocks[0].exp_strategy[ch] = EXP_D15;
629
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
630
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
631
    }
632
}
633

    
634

    
635
/**
636
 * Set each encoded exponent in a block to the minimum of itself and the
637
 * exponent in the same frequency bin of a following block.
638
 * exp[i] = min(exp[i], exp1[i]
639
 */
640
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
641
{
642
    int i;
643
    for (i = 0; i < n; i++) {
644
        if (exp1[i] < exp[i])
645
            exp[i] = exp1[i];
646
    }
647
}
648

    
649

    
650
/**
651
 * Update the exponents so that they are the ones the decoder will decode.
652
 */
653
static void encode_exponents_blk_ch(uint8_t *exp,
654
                                    int nb_exps, int exp_strategy)
655
{
656
    int nb_groups, i, k;
657

    
658
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
659

    
660
    /* for each group, compute the minimum exponent */
661
    switch(exp_strategy) {
662
    case EXP_D25:
663
        for (i = 1, k = 1; i <= nb_groups; i++) {
664
            uint8_t exp_min = exp[k];
665
            if (exp[k+1] < exp_min)
666
                exp_min = exp[k+1];
667
            exp[i] = exp_min;
668
            k += 2;
669
        }
670
        break;
671
    case EXP_D45:
672
        for (i = 1, k = 1; i <= nb_groups; i++) {
673
            uint8_t exp_min = exp[k];
674
            if (exp[k+1] < exp_min)
675
                exp_min = exp[k+1];
676
            if (exp[k+2] < exp_min)
677
                exp_min = exp[k+2];
678
            if (exp[k+3] < exp_min)
679
                exp_min = exp[k+3];
680
            exp[i] = exp_min;
681
            k += 4;
682
        }
683
        break;
684
    }
685

    
686
    /* constraint for DC exponent */
687
    if (exp[0] > 15)
688
        exp[0] = 15;
689

    
690
    /* decrease the delta between each groups to within 2 so that they can be
691
       differentially encoded */
692
    for (i = 1; i <= nb_groups; i++)
693
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
694
    i--;
695
    while (--i >= 0)
696
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
697

    
698
    /* now we have the exponent values the decoder will see */
699
    switch (exp_strategy) {
700
    case EXP_D25:
701
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
702
            uint8_t exp1 = exp[i];
703
            exp[k--] = exp1;
704
            exp[k--] = exp1;
705
        }
706
        break;
707
    case EXP_D45:
708
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
709
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
710
            k -= 4;
711
        }
712
        break;
713
    }
714
}
715

    
716

    
717
/**
718
 * Encode exponents from original extracted form to what the decoder will see.
719
 * This copies and groups exponents based on exponent strategy and reduces
720
 * deltas between adjacent exponent groups so that they can be differentially
721
 * encoded.
722
 */
723
static void encode_exponents(AC3EncodeContext *s)
724
{
725
    int blk, blk1, blk2, ch;
726
    AC3Block *block, *block1, *block2;
727

    
728
    for (ch = 0; ch < s->channels; ch++) {
729
        blk = 0;
730
        block = &s->blocks[0];
731
        while (blk < AC3_MAX_BLOCKS) {
732
            blk1 = blk + 1;
733
            block1 = block + 1;
734
            /* for the EXP_REUSE case we select the min of the exponents */
735
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
736
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
737
                blk1++;
738
                block1++;
739
            }
740
            encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
741
                                    block->exp_strategy[ch]);
742
            /* copy encoded exponents for reuse case */
743
            block2 = block + 1;
744
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
745
                memcpy(block2->exp[ch], block->exp[ch],
746
                       s->nb_coefs[ch] * sizeof(uint8_t));
747
            }
748
            blk = blk1;
749
            block = block1;
750
        }
751
    }
752
}
753

    
754

    
755
/**
756
 * Group exponents.
757
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
758
 * varies depending on exponent strategy and bandwidth.
759
 */
760
static void group_exponents(AC3EncodeContext *s)
761
{
762
    int blk, ch, i;
763
    int group_size, nb_groups, bit_count;
764
    uint8_t *p;
765
    int delta0, delta1, delta2;
766
    int exp0, exp1;
767

    
768
    bit_count = 0;
769
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
770
        AC3Block *block = &s->blocks[blk];
771
        for (ch = 0; ch < s->channels; ch++) {
772
            if (block->exp_strategy[ch] == EXP_REUSE) {
773
                continue;
774
            }
775
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
776
            nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
777
            bit_count += 4 + (nb_groups * 7);
778
            p = block->exp[ch];
779

    
780
            /* DC exponent */
781
            exp1 = *p++;
782
            block->grouped_exp[ch][0] = exp1;
783

    
784
            /* remaining exponents are delta encoded */
785
            for (i = 1; i <= nb_groups; i++) {
786
                /* merge three delta in one code */
787
                exp0   = exp1;
788
                exp1   = p[0];
789
                p     += group_size;
790
                delta0 = exp1 - exp0 + 2;
791

    
792
                exp0   = exp1;
793
                exp1   = p[0];
794
                p     += group_size;
795
                delta1 = exp1 - exp0 + 2;
796

    
797
                exp0   = exp1;
798
                exp1   = p[0];
799
                p     += group_size;
800
                delta2 = exp1 - exp0 + 2;
801

    
802
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
803
            }
804
        }
805
    }
806

    
807
    s->exponent_bits = bit_count;
808
}
809

    
810

    
811
/**
812
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
813
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
814
 * and encode final exponents.
815
 */
816
static void process_exponents(AC3EncodeContext *s)
817
{
818
    extract_exponents(s);
819

    
820
    compute_exp_strategy(s);
821

    
822
    encode_exponents(s);
823

    
824
    group_exponents(s);
825
}
826

    
827

    
828
/**
829
 * Count frame bits that are based solely on fixed parameters.
830
 * This only has to be run once when the encoder is initialized.
831
 */
832
static void count_frame_bits_fixed(AC3EncodeContext *s)
833
{
834
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
835
    int blk;
836
    int frame_bits;
837

    
838
    /* assumptions:
839
     *   no dynamic range codes
840
     *   no channel coupling
841
     *   no rematrixing
842
     *   bit allocation parameters do not change between blocks
843
     *   SNR offsets do not change between blocks
844
     *   no delta bit allocation
845
     *   no skipped data
846
     *   no auxilliary data
847
     */
848

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

    
853
    /* audio blocks */
854
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
855
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
856
        if (s->channel_mode == AC3_CHMODE_STEREO) {
857
            frame_bits++; /* rematstr */
858
            if (!blk)
859
                frame_bits += 4;
860
        }
861
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
862
        if (s->lfe_on)
863
            frame_bits++; /* lfeexpstr */
864
        frame_bits++; /* baie */
865
        frame_bits++; /* snr */
866
        frame_bits += 2; /* delta / skip */
867
    }
868
    frame_bits++; /* cplinu for block 0 */
869
    /* bit alloc info */
870
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
871
    /* csnroffset[6] */
872
    /* (fsnoffset[4] + fgaincod[4]) * c */
873
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
874

    
875
    /* auxdatae, crcrsv */
876
    frame_bits += 2;
877

    
878
    /* CRC */
879
    frame_bits += 16;
880

    
881
    s->frame_bits_fixed = frame_bits;
882
}
883

    
884

    
885
/**
886
 * Initialize bit allocation.
887
 * Set default parameter codes and calculate parameter values.
888
 */
889
static void bit_alloc_init(AC3EncodeContext *s)
890
{
891
    int ch;
892

    
893
    /* init default parameters */
894
    s->slow_decay_code = 2;
895
    s->fast_decay_code = 1;
896
    s->slow_gain_code  = 1;
897
    s->db_per_bit_code = 2;
898
    s->floor_code      = 4;
899
    for (ch = 0; ch < s->channels; ch++)
900
        s->fast_gain_code[ch] = 4;
901

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

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

    
914
    count_frame_bits_fixed(s);
915
}
916

    
917

    
918
/**
919
 * Count the bits used to encode the frame, minus exponents and mantissas.
920
 * Bits based on fixed parameters have already been counted, so now we just
921
 * have to add the bits based on parameters that change during encoding.
922
 */
923
static void count_frame_bits(AC3EncodeContext *s)
924
{
925
    int blk, ch;
926
    int frame_bits = 0;
927

    
928
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
929
        uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
930
        for (ch = 0; ch < s->fbw_channels; ch++) {
931
            if (exp_strategy[ch] != EXP_REUSE)
932
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
933
        }
934
    }
935
    s->frame_bits = s->frame_bits_fixed + frame_bits;
936
}
937

    
938

    
939
/**
940
 * Calculate the number of bits needed to encode a set of mantissas.
941
 */
942
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
943
{
944
    int bits, b, i;
945

    
946
    bits = 0;
947
    for (i = 0; i < nb_coefs; i++) {
948
        b = bap[i];
949
        if (b <= 4) {
950
            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
951
            mant_cnt[b]++;
952
        } else if (b <= 13) {
953
            // bap=5 to bap=13 use (bap-1) bits
954
            bits += b - 1;
955
        } else {
956
            // bap=14 uses 14 bits and bap=15 uses 16 bits
957
            bits += (b == 14) ? 14 : 16;
958
        }
959
    }
960
    return bits;
961
}
962

    
963

    
964
/**
965
 * Finalize the mantissa bit count by adding in the grouped mantissas.
966
 */
967
static int compute_mantissa_size_final(int mant_cnt[5])
968
{
969
    // bap=1 : 3 mantissas in 5 bits
970
    int bits = (mant_cnt[1] / 3) * 5;
971
    // bap=2 : 3 mantissas in 7 bits
972
    // bap=4 : 2 mantissas in 7 bits
973
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
974
    // bap=3 : each mantissa is 3 bits
975
    bits += mant_cnt[3] * 3;
976
    return bits;
977
}
978

    
979

    
980
/**
981
 * Calculate masking curve based on the final exponents.
982
 * Also calculate the power spectral densities to use in future calculations.
983
 */
984
static void bit_alloc_masking(AC3EncodeContext *s)
985
{
986
    int blk, ch;
987

    
988
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
989
        AC3Block *block = &s->blocks[blk];
990
        for (ch = 0; ch < s->channels; ch++) {
991
            /* We only need psd and mask for calculating bap.
992
               Since we currently do not calculate bap when exponent
993
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
994
            if (block->exp_strategy[ch] != EXP_REUSE) {
995
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
996
                                          s->nb_coefs[ch],
997
                                          block->psd[ch], block->band_psd[ch]);
998
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
999
                                           0, s->nb_coefs[ch],
1000
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1001
                                           ch == s->lfe_channel,
1002
                                           DBA_NONE, 0, NULL, NULL, NULL,
1003
                                           block->mask[ch]);
1004
            }
1005
        }
1006
    }
1007
}
1008

    
1009

    
1010
/**
1011
 * Ensure that bap for each block and channel point to the current bap_buffer.
1012
 * They may have been switched during the bit allocation search.
1013
 */
1014
static void reset_block_bap(AC3EncodeContext *s)
1015
{
1016
    int blk, ch;
1017
    if (s->blocks[0].bap[0] == s->bap_buffer)
1018
        return;
1019
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1020
        for (ch = 0; ch < s->channels; ch++) {
1021
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1022
        }
1023
    }
1024
}
1025

    
1026

    
1027
/**
1028
 * Run the bit allocation with a given SNR offset.
1029
 * This calculates the bit allocation pointers that will be used to determine
1030
 * the quantization of each mantissa.
1031
 * @return the number of bits needed for mantissas if the given SNR offset is
1032
 *         is used.
1033
 */
1034
static int bit_alloc(AC3EncodeContext *s,
1035
                     int snr_offset)
1036
{
1037
    int blk, ch;
1038
    int mantissa_bits;
1039
    int mant_cnt[5];
1040

    
1041
    snr_offset = (snr_offset - 240) << 2;
1042

    
1043
    reset_block_bap(s);
1044
    mantissa_bits = 0;
1045
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1046
        AC3Block *block = &s->blocks[blk];
1047
        // initialize grouped mantissa counts. these are set so that they are
1048
        // padded to the next whole group size when bits are counted in
1049
        // compute_mantissa_size_final
1050
        mant_cnt[0] = mant_cnt[3] = 0;
1051
        mant_cnt[1] = mant_cnt[2] = 2;
1052
        mant_cnt[4] = 1;
1053
        for (ch = 0; ch < s->channels; ch++) {
1054
            /* Currently the only bit allocation parameters which vary across
1055
               blocks within a frame are the exponent values.  We can take
1056
               advantage of that by reusing the bit allocation pointers
1057
               whenever we reuse exponents. */
1058
            if (block->exp_strategy[ch] == EXP_REUSE) {
1059
                memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
1060
            } else {
1061
                ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1062
                                          s->nb_coefs[ch], snr_offset,
1063
                                          s->bit_alloc.floor, ff_ac3_bap_tab,
1064
                                          block->bap[ch]);
1065
            }
1066
            mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1067
        }
1068
        mantissa_bits += compute_mantissa_size_final(mant_cnt);
1069
    }
1070
    return mantissa_bits;
1071
}
1072

    
1073

    
1074
/**
1075
 * Constant bitrate bit allocation search.
1076
 * Find the largest SNR offset that will allow data to fit in the frame.
1077
 */
1078
static int cbr_bit_allocation(AC3EncodeContext *s)
1079
{
1080
    int ch;
1081
    int bits_left;
1082
    int snr_offset, snr_incr;
1083

    
1084
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1085

    
1086
    snr_offset = s->coarse_snr_offset << 4;
1087

    
1088
    while (snr_offset >= 0 &&
1089
           bit_alloc(s, snr_offset) > bits_left) {
1090
        snr_offset -= 64;
1091
    }
1092
    if (snr_offset < 0)
1093
        return AVERROR(EINVAL);
1094

    
1095
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1096
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1097
        while (snr_offset + 64 <= 1023 &&
1098
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1099
            snr_offset += snr_incr;
1100
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1101
        }
1102
    }
1103
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1104
    reset_block_bap(s);
1105

    
1106
    s->coarse_snr_offset = snr_offset >> 4;
1107
    for (ch = 0; ch < s->channels; ch++)
1108
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1109

    
1110
    return 0;
1111
}
1112

    
1113

    
1114
/**
1115
 * Perform bit allocation search.
1116
 * Finds the SNR offset value that maximizes quality and fits in the specified
1117
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1118
 * used to quantize the mantissas.
1119
 */
1120
static int compute_bit_allocation(AC3EncodeContext *s)
1121
{
1122
    count_frame_bits(s);
1123

    
1124
    bit_alloc_masking(s);
1125

    
1126
    return cbr_bit_allocation(s);
1127
}
1128

    
1129

    
1130
/**
1131
 * Symmetric quantization on 'levels' levels.
1132
 */
1133
static inline int sym_quant(int c, int e, int levels)
1134
{
1135
    int v;
1136

    
1137
    if (c >= 0) {
1138
        v = (levels * (c << e)) >> 24;
1139
        v = (v + 1) >> 1;
1140
        v = (levels >> 1) + v;
1141
    } else {
1142
        v = (levels * ((-c) << e)) >> 24;
1143
        v = (v + 1) >> 1;
1144
        v = (levels >> 1) - v;
1145
    }
1146
    assert(v >= 0 && v < levels);
1147
    return v;
1148
}
1149

    
1150

    
1151
/**
1152
 * Asymmetric quantization on 2^qbits levels.
1153
 */
1154
static inline int asym_quant(int c, int e, int qbits)
1155
{
1156
    int lshift, m, v;
1157

    
1158
    lshift = e + qbits - 24;
1159
    if (lshift >= 0)
1160
        v = c << lshift;
1161
    else
1162
        v = c >> (-lshift);
1163
    /* rounding */
1164
    v = (v + 1) >> 1;
1165
    m = (1 << (qbits-1));
1166
    if (v >= m)
1167
        v = m - 1;
1168
    assert(v >= -m);
1169
    return v & ((1 << qbits)-1);
1170
}
1171

    
1172

    
1173
/**
1174
 * Quantize a set of mantissas for a single channel in a single block.
1175
 */
1176
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1177
                                      int32_t *mdct_coef, int8_t exp_shift,
1178
                                      uint8_t *exp, uint8_t *bap,
1179
                                      uint16_t *qmant, int n)
1180
{
1181
    int i;
1182

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

    
1267

    
1268
/**
1269
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1270
 */
1271
static void quantize_mantissas(AC3EncodeContext *s)
1272
{
1273
    int blk, ch;
1274

    
1275

    
1276
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1277
        AC3Block *block = &s->blocks[blk];
1278
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1279
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1280

    
1281
        for (ch = 0; ch < s->channels; ch++) {
1282
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1283
                                      block->exp[ch], block->bap[ch],
1284
                                      block->qmant[ch], s->nb_coefs[ch]);
1285
        }
1286
    }
1287
}
1288

    
1289

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

    
1320

    
1321
/**
1322
 * Write one audio block to the output bitstream.
1323
 */
1324
static void output_audio_block(AC3EncodeContext *s,
1325
                               int block_num)
1326
{
1327
    int ch, i, baie, rbnd;
1328
    AC3Block *block = &s->blocks[block_num];
1329

    
1330
    /* block switching */
1331
    for (ch = 0; ch < s->fbw_channels; ch++)
1332
        put_bits(&s->pb, 1, 0);
1333

    
1334
    /* dither flags */
1335
    for (ch = 0; ch < s->fbw_channels; ch++)
1336
        put_bits(&s->pb, 1, 1);
1337

    
1338
    /* dynamic range codes */
1339
    put_bits(&s->pb, 1, 0);
1340

    
1341
    /* channel coupling */
1342
    if (!block_num) {
1343
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1344
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1345
    } else {
1346
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1347
    }
1348

    
1349
    /* stereo rematrixing */
1350
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1351
        if (!block_num) {
1352
            /* first block must define rematrixing (rematstr) */
1353
            put_bits(&s->pb, 1, 1);
1354

    
1355
            /* dummy rematrixing rematflg(1:4)=0 */
1356
            for (rbnd = 0; rbnd < 4; rbnd++)
1357
                put_bits(&s->pb, 1, 0);
1358
        } else {
1359
            /* no matrixing (but should be used in the future) */
1360
            put_bits(&s->pb, 1, 0);
1361
        }
1362
    }
1363

    
1364
    /* exponent strategy */
1365
    for (ch = 0; ch < s->fbw_channels; ch++)
1366
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1367
    if (s->lfe_on)
1368
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1369

    
1370
    /* bandwidth */
1371
    for (ch = 0; ch < s->fbw_channels; ch++) {
1372
        if (block->exp_strategy[ch] != EXP_REUSE)
1373
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1374
    }
1375

    
1376
    /* exponents */
1377
    for (ch = 0; ch < s->channels; ch++) {
1378
        int nb_groups;
1379

    
1380
        if (block->exp_strategy[ch] == EXP_REUSE)
1381
            continue;
1382

    
1383
        /* DC exponent */
1384
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1385

    
1386
        /* exponent groups */
1387
        nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
1388
        for (i = 1; i <= nb_groups; i++)
1389
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1390

    
1391
        /* gain range info */
1392
        if (ch != s->lfe_channel)
1393
            put_bits(&s->pb, 2, 0);
1394
    }
1395

    
1396
    /* bit allocation info */
1397
    baie = (block_num == 0);
1398
    put_bits(&s->pb, 1, baie);
1399
    if (baie) {
1400
        put_bits(&s->pb, 2, s->slow_decay_code);
1401
        put_bits(&s->pb, 2, s->fast_decay_code);
1402
        put_bits(&s->pb, 2, s->slow_gain_code);
1403
        put_bits(&s->pb, 2, s->db_per_bit_code);
1404
        put_bits(&s->pb, 3, s->floor_code);
1405
    }
1406

    
1407
    /* snr offset */
1408
    put_bits(&s->pb, 1, baie);
1409
    if (baie) {
1410
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1411
        for (ch = 0; ch < s->channels; ch++) {
1412
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1413
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1414
        }
1415
    }
1416

    
1417
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1418
    put_bits(&s->pb, 1, 0); /* no data to skip */
1419

    
1420
    /* mantissas */
1421
    for (ch = 0; ch < s->channels; ch++) {
1422
        int b, q;
1423
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1424
            q = block->qmant[ch][i];
1425
            b = block->bap[ch][i];
1426
            switch (b) {
1427
            case 0:                                         break;
1428
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1429
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1430
            case 3:               put_bits(&s->pb,   3, q); break;
1431
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1432
            case 14:              put_bits(&s->pb,  14, q); break;
1433
            case 15:              put_bits(&s->pb,  16, q); break;
1434
            default:              put_bits(&s->pb, b-1, q); break;
1435
            }
1436
        }
1437
    }
1438
}
1439

    
1440

    
1441
/** CRC-16 Polynomial */
1442
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1443

    
1444

    
1445
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1446
{
1447
    unsigned int c;
1448

    
1449
    c = 0;
1450
    while (a) {
1451
        if (a & 1)
1452
            c ^= b;
1453
        a = a >> 1;
1454
        b = b << 1;
1455
        if (b & (1 << 16))
1456
            b ^= poly;
1457
    }
1458
    return c;
1459
}
1460

    
1461

    
1462
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1463
{
1464
    unsigned int r;
1465
    r = 1;
1466
    while (n) {
1467
        if (n & 1)
1468
            r = mul_poly(r, a, poly);
1469
        a = mul_poly(a, a, poly);
1470
        n >>= 1;
1471
    }
1472
    return r;
1473
}
1474

    
1475

    
1476
/**
1477
 * Fill the end of the frame with 0's and compute the two CRCs.
1478
 */
1479
static void output_frame_end(AC3EncodeContext *s)
1480
{
1481
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1482
    uint8_t *frame;
1483

    
1484
    frame_size    = s->frame_size;
1485
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1486

    
1487
    /* pad the remainder of the frame with zeros */
1488
    flush_put_bits(&s->pb);
1489
    frame = s->pb.buf;
1490
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1491
    assert(pad_bytes >= 0);
1492
    if (pad_bytes > 0)
1493
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1494

    
1495
    /* compute crc1 */
1496
    /* this is not so easy because it is at the beginning of the data... */
1497
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1498
                             frame + 4, frame_size_58 - 4));
1499
    /* XXX: could precompute crc_inv */
1500
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1501
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1502
    AV_WB16(frame + 2, crc1);
1503

    
1504
    /* compute crc2 */
1505
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1506
                             frame + frame_size_58,
1507
                             frame_size - frame_size_58 - 2));
1508
    AV_WB16(frame + frame_size - 2, crc2);
1509
}
1510

    
1511

    
1512
/**
1513
 * Write the frame to the output bitstream.
1514
 */
1515
static void output_frame(AC3EncodeContext *s,
1516
                         unsigned char *frame)
1517
{
1518
    int blk;
1519

    
1520
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1521

    
1522
    output_frame_header(s);
1523

    
1524
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1525
        output_audio_block(s, blk);
1526

    
1527
    output_frame_end(s);
1528
}
1529

    
1530

    
1531
/**
1532
 * Encode a single AC-3 frame.
1533
 */
1534
static int ac3_encode_frame(AVCodecContext *avctx,
1535
                            unsigned char *frame, int buf_size, void *data)
1536
{
1537
    AC3EncodeContext *s = avctx->priv_data;
1538
    const int16_t *samples = data;
1539
    int ret;
1540

    
1541
    if (s->bit_alloc.sr_code == 1)
1542
        adjust_frame_size(s);
1543

    
1544
    deinterleave_input_samples(s, samples);
1545

    
1546
    apply_mdct(s);
1547

    
1548
    process_exponents(s);
1549

    
1550
    ret = compute_bit_allocation(s);
1551
    if (ret) {
1552
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1553
        return ret;
1554
    }
1555

    
1556
    quantize_mantissas(s);
1557

    
1558
    output_frame(s, frame);
1559

    
1560
    return s->frame_size;
1561
}
1562

    
1563

    
1564
/**
1565
 * Finalize encoding and free any memory allocated by the encoder.
1566
 */
1567
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1568
{
1569
    int blk, ch;
1570
    AC3EncodeContext *s = avctx->priv_data;
1571

    
1572
    for (ch = 0; ch < s->channels; ch++)
1573
        av_freep(&s->planar_samples[ch]);
1574
    av_freep(&s->planar_samples);
1575
    av_freep(&s->bap_buffer);
1576
    av_freep(&s->bap1_buffer);
1577
    av_freep(&s->mdct_coef_buffer);
1578
    av_freep(&s->exp_buffer);
1579
    av_freep(&s->grouped_exp_buffer);
1580
    av_freep(&s->psd_buffer);
1581
    av_freep(&s->band_psd_buffer);
1582
    av_freep(&s->mask_buffer);
1583
    av_freep(&s->qmant_buffer);
1584
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1585
        AC3Block *block = &s->blocks[blk];
1586
        av_freep(&block->bap);
1587
        av_freep(&block->mdct_coef);
1588
        av_freep(&block->exp);
1589
        av_freep(&block->grouped_exp);
1590
        av_freep(&block->psd);
1591
        av_freep(&block->band_psd);
1592
        av_freep(&block->mask);
1593
        av_freep(&block->qmant);
1594
    }
1595

    
1596
    mdct_end(&s->mdct);
1597

    
1598
    av_freep(&avctx->coded_frame);
1599
    return 0;
1600
}
1601

    
1602

    
1603
/**
1604
 * Set channel information during initialization.
1605
 */
1606
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1607
                                    int64_t *channel_layout)
1608
{
1609
    int ch_layout;
1610

    
1611
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1612
        return AVERROR(EINVAL);
1613
    if ((uint64_t)*channel_layout > 0x7FF)
1614
        return AVERROR(EINVAL);
1615
    ch_layout = *channel_layout;
1616
    if (!ch_layout)
1617
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1618
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1619
        return AVERROR(EINVAL);
1620

    
1621
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1622
    s->channels     = channels;
1623
    s->fbw_channels = channels - s->lfe_on;
1624
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1625
    if (s->lfe_on)
1626
        ch_layout -= AV_CH_LOW_FREQUENCY;
1627

    
1628
    switch (ch_layout) {
1629
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1630
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1631
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1632
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1633
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1634
    case AV_CH_LAYOUT_QUAD:
1635
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1636
    case AV_CH_LAYOUT_5POINT0:
1637
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1638
    default:
1639
        return AVERROR(EINVAL);
1640
    }
1641

    
1642
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1643
    *channel_layout = ch_layout;
1644
    if (s->lfe_on)
1645
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1646

    
1647
    return 0;
1648
}
1649

    
1650

    
1651
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1652
{
1653
    int i, ret;
1654

    
1655
    /* validate channel layout */
1656
    if (!avctx->channel_layout) {
1657
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1658
                                      "encoder will guess the layout, but it "
1659
                                      "might be incorrect.\n");
1660
    }
1661
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1662
    if (ret) {
1663
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1664
        return ret;
1665
    }
1666

    
1667
    /* validate sample rate */
1668
    for (i = 0; i < 9; i++) {
1669
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1670
            break;
1671
    }
1672
    if (i == 9) {
1673
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1674
        return AVERROR(EINVAL);
1675
    }
1676
    s->sample_rate        = avctx->sample_rate;
1677
    s->bit_alloc.sr_shift = i % 3;
1678
    s->bit_alloc.sr_code  = i / 3;
1679

    
1680
    /* validate bit rate */
1681
    for (i = 0; i < 19; i++) {
1682
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1683
            break;
1684
    }
1685
    if (i == 19) {
1686
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1687
        return AVERROR(EINVAL);
1688
    }
1689
    s->bit_rate        = avctx->bit_rate;
1690
    s->frame_size_code = i << 1;
1691

    
1692
    return 0;
1693
}
1694

    
1695

    
1696
/**
1697
 * Set bandwidth for all channels.
1698
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1699
 * default value will be used.
1700
 */
1701
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1702
{
1703
    int ch, bw_code;
1704

    
1705
    if (cutoff) {
1706
        /* calculate bandwidth based on user-specified cutoff frequency */
1707
        int fbw_coeffs;
1708
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1709
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1710
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1711
    } else {
1712
        /* use default bandwidth setting */
1713
        /* XXX: should compute the bandwidth according to the frame
1714
           size, so that we avoid annoying high frequency artifacts */
1715
        bw_code = 50;
1716
    }
1717

    
1718
    /* set number of coefficients for each channel */
1719
    for (ch = 0; ch < s->fbw_channels; ch++) {
1720
        s->bandwidth_code[ch] = bw_code;
1721
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1722
    }
1723
    if (s->lfe_on)
1724
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1725
}
1726

    
1727

    
1728
static av_cold int allocate_buffers(AVCodecContext *avctx)
1729
{
1730
    int blk, ch;
1731
    AC3EncodeContext *s = avctx->priv_data;
1732

    
1733
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1734
                     alloc_fail);
1735
    for (ch = 0; ch < s->channels; ch++) {
1736
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1737
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1738
                          alloc_fail);
1739
    }
1740
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1741
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1742
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1743
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1744
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1745
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1746
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1747
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1748
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1749
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1750
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1751
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1752
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1753
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1754
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1755
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1756
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1757
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1758
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1759
        AC3Block *block = &s->blocks[blk];
1760
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1761
                         alloc_fail);
1762
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1763
                          alloc_fail);
1764
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1765
                          alloc_fail);
1766
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1767
                          alloc_fail);
1768
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1769
                          alloc_fail);
1770
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1771
                          alloc_fail);
1772
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1773
                          alloc_fail);
1774
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1775
                          alloc_fail);
1776

    
1777
        for (ch = 0; ch < s->channels; ch++) {
1778
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1779
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1780
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1781
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1782
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1783
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1784
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1785
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1786
        }
1787
    }
1788

    
1789
    return 0;
1790
alloc_fail:
1791
    return AVERROR(ENOMEM);
1792
}
1793

    
1794

    
1795
/**
1796
 * Initialize the encoder.
1797
 */
1798
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1799
{
1800
    AC3EncodeContext *s = avctx->priv_data;
1801
    int ret;
1802

    
1803
    avctx->frame_size = AC3_FRAME_SIZE;
1804

    
1805
    ac3_common_init();
1806

    
1807
    ret = validate_options(avctx, s);
1808
    if (ret)
1809
        return ret;
1810

    
1811
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1812
    s->bitstream_mode = 0; /* complete main audio service */
1813

    
1814
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1815
    s->bits_written    = 0;
1816
    s->samples_written = 0;
1817
    s->frame_size      = s->frame_size_min;
1818

    
1819
    set_bandwidth(s, avctx->cutoff);
1820

    
1821
    exponent_init(s);
1822

    
1823
    bit_alloc_init(s);
1824

    
1825
    s->mdct.avctx = avctx;
1826
    ret = mdct_init(&s->mdct, 9);
1827
    if (ret)
1828
        goto init_fail;
1829

    
1830
    ret = allocate_buffers(avctx);
1831
    if (ret)
1832
        goto init_fail;
1833

    
1834
    avctx->coded_frame= avcodec_alloc_frame();
1835

    
1836
    dsputil_init(&s->dsp, avctx);
1837

    
1838
    return 0;
1839
init_fail:
1840
    ac3_encode_close(avctx);
1841
    return ret;
1842
}
1843

    
1844

    
1845
#ifdef TEST
1846
/*************************************************************************/
1847
/* TEST */
1848

    
1849
#include "libavutil/lfg.h"
1850

    
1851
#define MDCT_NBITS 9
1852
#define MDCT_SAMPLES (1 << MDCT_NBITS)
1853
#define FN (MDCT_SAMPLES/4)
1854

    
1855

    
1856
static void fft_test(AC3MDCTContext *mdct, AVLFG *lfg)
1857
{
1858
    IComplex in[FN], in1[FN];
1859
    int k, n, i;
1860
    float sum_re, sum_im, a;
1861

    
1862
    for (i = 0; i < FN; i++) {
1863
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1864
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1865
        in1[i]   = in[i];
1866
    }
1867
    fft(mdct, in, 7);
1868

    
1869
    /* do it by hand */
1870
    for (k = 0; k < FN; k++) {
1871
        sum_re = 0;
1872
        sum_im = 0;
1873
        for (n = 0; n < FN; n++) {
1874
            a = -2 * M_PI * (n * k) / FN;
1875
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1876
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1877
        }
1878
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1879
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1880
    }
1881
}
1882

    
1883

    
1884
static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg)
1885
{
1886
    int16_t input[MDCT_SAMPLES];
1887
    int32_t output[AC3_MAX_COEFS];
1888
    float input1[MDCT_SAMPLES];
1889
    float output1[AC3_MAX_COEFS];
1890
    float s, a, err, e, emax;
1891
    int i, k, n;
1892

    
1893
    for (i = 0; i < MDCT_SAMPLES; i++) {
1894
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1895
        input1[i] = input[i];
1896
    }
1897

    
1898
    mdct512(mdct, output, input);
1899

    
1900
    /* do it by hand */
1901
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1902
        s = 0;
1903
        for (n = 0; n < MDCT_SAMPLES; n++) {
1904
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1905
            s += input1[n] * cos(a);
1906
        }
1907
        output1[k] = -2 * s / MDCT_SAMPLES;
1908
    }
1909

    
1910
    err  = 0;
1911
    emax = 0;
1912
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1913
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1914
        e = output[i] - output1[i];
1915
        if (e > emax)
1916
            emax = e;
1917
        err += e * e;
1918
    }
1919
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1920
}
1921

    
1922

    
1923
int main(void)
1924
{
1925
    AVLFG lfg;
1926
    AC3MDCTContext mdct;
1927

    
1928
    mdct.avctx = NULL;
1929
    av_log_set_level(AV_LOG_DEBUG);
1930
    mdct_init(&mdct, 9);
1931

    
1932
    fft_test(&mdct, &lfg);
1933
    mdct_test(&mdct, &lfg);
1934

    
1935
    return 0;
1936
}
1937
#endif /* TEST */
1938

    
1939

    
1940
AVCodec ac3_encoder = {
1941
    "ac3",
1942
    AVMEDIA_TYPE_AUDIO,
1943
    CODEC_ID_AC3,
1944
    sizeof(AC3EncodeContext),
1945
    ac3_encode_init,
1946
    ac3_encode_frame,
1947
    ac3_encode_close,
1948
    NULL,
1949
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1950
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1951
    .channel_layouts = (const int64_t[]){
1952
        AV_CH_LAYOUT_MONO,
1953
        AV_CH_LAYOUT_STEREO,
1954
        AV_CH_LAYOUT_2_1,
1955
        AV_CH_LAYOUT_SURROUND,
1956
        AV_CH_LAYOUT_2_2,
1957
        AV_CH_LAYOUT_QUAD,
1958
        AV_CH_LAYOUT_4POINT0,
1959
        AV_CH_LAYOUT_5POINT0,
1960
        AV_CH_LAYOUT_5POINT0_BACK,
1961
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1962
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1963
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1964
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1965
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1966
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1967
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1968
        AV_CH_LAYOUT_5POINT1,
1969
        AV_CH_LAYOUT_5POINT1_BACK,
1970
        0 },
1971
};