Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 171bc51c

History | View | Annotate | Download (51.7 KB)

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

    
22
/**
23
 * @file
24
 * The simplest AC-3 encoder.
25
 */
26

    
27
//#define DEBUG
28

    
29
#include "libavcore/audioconvert.h"
30
#include "libavutil/crc.h"
31
#include "avcodec.h"
32
#include "put_bits.h"
33
#include "ac3.h"
34
#include "audioconvert.h"
35

    
36

    
37
#define MDCT_NBITS 9
38
#define MDCT_SAMPLES (1 << MDCT_NBITS)
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
/**
59
 * Data for a single audio block.
60
 */
61
typedef struct AC3Block {
62
    uint8_t  **bap;                             ///< bap for each channel in this block
63
    int32_t  mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
64
    uint8_t  exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
65
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];
66
    uint8_t  encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
67
    uint8_t  num_exp_groups[AC3_MAX_CHANNELS];
68
    uint8_t  grouped_exp[AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
69
    int16_t  psd[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
70
    int16_t  band_psd[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
71
    int16_t  mask[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
72
    int8_t   exp_shift[AC3_MAX_CHANNELS];
73
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
74
} AC3Block;
75

    
76
/**
77
 * AC-3 encoder private context.
78
 */
79
typedef struct AC3EncodeContext {
80
    PutBitContext pb;                       ///< bitstream writer context
81

    
82
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
83

    
84
    int bitstream_id;                       ///< bitstream id                           (bsid)
85
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
86

    
87
    int bit_rate;                           ///< target bit rate, in bits-per-second
88
    int sample_rate;                        ///< sampling frequency, in Hz
89

    
90
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
91
    int frame_size;                         ///< current frame size in bytes
92
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
93
    int bits_written;                       ///< bit count    (used to avg. bitrate)
94
    int samples_written;                    ///< sample count (used to avg. bitrate)
95

    
96
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
97
    int channels;                           ///< total number of channels               (nchans)
98
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
99
    int lfe_channel;                        ///< channel index of the LFE channel
100
    int channel_mode;                       ///< channel mode                           (acmod)
101
    const uint8_t *channel_map;             ///< channel map used to reorder channels
102

    
103
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
104
    int nb_coefs[AC3_MAX_CHANNELS];
105

    
106
    /* bitrate allocation control */
107
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
108
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
109
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
110
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
111
    int floor_code;                         ///< floor code                             (floorcod)
112
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
113
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
114
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
115
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
116
    int frame_bits;                         ///< all frame bits except exponents and mantissas
117
    int exponent_bits;                      ///< number of bits used for exponents
118

    
119
    /* mantissa encoding */
120
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
121
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
122

    
123
    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
124
    int16_t windowed_samples[AC3_WINDOW_SIZE];
125
    uint8_t *bap_buffer;
126
    uint8_t *bap1_buffer;
127
} AC3EncodeContext;
128

    
129

    
130
/** MDCT and FFT tables */
131
static int16_t costab[64];
132
static int16_t sintab[64];
133
static int16_t xcos1[128];
134
static int16_t xsin1[128];
135

    
136

    
137
/**
138
 * Adjust the frame size to make the average bit rate match the target bit rate.
139
 * This is only needed for 11025, 22050, and 44100 sample rates.
140
 */
141
static void adjust_frame_size(AC3EncodeContext *s)
142
{
143
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
144
        s->bits_written    -= s->bit_rate;
145
        s->samples_written -= s->sample_rate;
146
    }
147
    s->frame_size = s->frame_size_min +
148
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
149
    s->bits_written    += s->frame_size * 8;
150
    s->samples_written += AC3_FRAME_SIZE;
151
}
152

    
153

    
154
/**
155
 * Deinterleave input samples.
156
 * Channels are reordered from FFmpeg's default order to AC-3 order.
157
 */
158
static void deinterleave_input_samples(AC3EncodeContext *s,
159
                                       const int16_t *samples)
160
{
161
    int ch, i;
162

    
163
    /* deinterleave and remap input samples */
164
    for (ch = 0; ch < s->channels; ch++) {
165
        const int16_t *sptr;
166
        int sinc;
167

    
168
        /* copy last 256 samples of previous frame to the start of the current frame */
169
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
170
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
171

    
172
        /* deinterleave */
173
        sinc = s->channels;
174
        sptr = samples + s->channel_map[ch];
175
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
176
            s->planar_samples[ch][i] = *sptr;
177
            sptr += sinc;
178
        }
179
    }
180
}
181

    
182

    
183
/**
184
 * Initialize FFT tables.
185
 * @param ln log2(FFT size)
186
 */
187
static av_cold void fft_init(int ln)
188
{
189
    int i, n, n2;
190
    float alpha;
191

    
192
    n  = 1 << ln;
193
    n2 = n >> 1;
194

    
195
    for (i = 0; i < n2; i++) {
196
        alpha     = 2.0 * M_PI * i / n;
197
        costab[i] = FIX15(cos(alpha));
198
        sintab[i] = FIX15(sin(alpha));
199
    }
200
}
201

    
202

    
203
/**
204
 * Initialize MDCT tables.
205
 * @param nbits log2(MDCT size)
206
 */
207
static av_cold void mdct_init(int nbits)
208
{
209
    int i, n, n4;
210

    
211
    n  = 1 << nbits;
212
    n4 = n >> 2;
213

    
214
    fft_init(nbits - 2);
215

    
216
    for (i = 0; i < n4; i++) {
217
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
218
        xcos1[i] = FIX15(-cos(alpha));
219
        xsin1[i] = FIX15(-sin(alpha));
220
    }
221
}
222

    
223

    
224
/** Butterfly op */
225
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
226
{                                                       \
227
  int ax, ay, bx, by;                                   \
228
  bx  = pre1;                                           \
229
  by  = pim1;                                           \
230
  ax  = qre1;                                           \
231
  ay  = qim1;                                           \
232
  pre = (bx + ax) >> 1;                                 \
233
  pim = (by + ay) >> 1;                                 \
234
  qre = (bx - ax) >> 1;                                 \
235
  qim = (by - ay) >> 1;                                 \
236
}
237

    
238

    
239
/** Complex multiply */
240
#define CMUL(pre, pim, are, aim, bre, bim)              \
241
{                                                       \
242
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
243
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
244
}
245

    
246

    
247
/**
248
 * Calculate a 2^n point complex FFT on 2^ln points.
249
 * @param z  complex input/output samples
250
 * @param ln log2(FFT size)
251
 */
252
static void fft(IComplex *z, int ln)
253
{
254
    int j, l, np, np2;
255
    int nblocks, nloops;
256
    register IComplex *p,*q;
257
    int tmp_re, tmp_im;
258

    
259
    np = 1 << ln;
260

    
261
    /* reverse */
262
    for (j = 0; j < np; j++) {
263
        int k = av_reverse[j] >> (8 - ln);
264
        if (k < j)
265
            FFSWAP(IComplex, z[k], z[j]);
266
    }
267

    
268
    /* pass 0 */
269

    
270
    p = &z[0];
271
    j = np >> 1;
272
    do {
273
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
274
           p[0].re, p[0].im, p[1].re, p[1].im);
275
        p += 2;
276
    } while (--j);
277

    
278
    /* pass 1 */
279

    
280
    p = &z[0];
281
    j = np >> 2;
282
    do {
283
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
284
           p[0].re, p[0].im, p[2].re,  p[2].im);
285
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
286
           p[1].re, p[1].im, p[3].im, -p[3].re);
287
        p+=4;
288
    } while (--j);
289

    
290
    /* pass 2 .. ln-1 */
291

    
292
    nblocks = np >> 3;
293
    nloops  =  1 << 2;
294
    np2     = np >> 1;
295
    do {
296
        p = z;
297
        q = z + nloops;
298
        for (j = 0; j < nblocks; j++) {
299
            BF(p->re, p->im, q->re, q->im,
300
               p->re, p->im, q->re, q->im);
301
            p++;
302
            q++;
303
            for(l = nblocks; l < np2; l += nblocks) {
304
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
305
                BF(p->re, p->im, q->re,  q->im,
306
                   p->re, p->im, tmp_re, tmp_im);
307
                p++;
308
                q++;
309
            }
310
            p += nloops;
311
            q += nloops;
312
        }
313
        nblocks = nblocks >> 1;
314
        nloops  = nloops  << 1;
315
    } while (nblocks);
316
}
317

    
318

    
319
/**
320
 * Calculate a 512-point MDCT
321
 * @param out 256 output frequency coefficients
322
 * @param in  512 windowed input audio samples
323
 */
324
static void mdct512(int32_t *out, int16_t *in)
325
{
326
    int i, re, im, re1, im1;
327
    int16_t rot[MDCT_SAMPLES];
328
    IComplex x[MDCT_SAMPLES/4];
329

    
330
    /* shift to simplify computations */
331
    for (i = 0; i < MDCT_SAMPLES/4; i++)
332
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
333
    for (;i < MDCT_SAMPLES; i++)
334
        rot[i] =  in[i -   MDCT_SAMPLES/4];
335

    
336
    /* pre rotation */
337
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
338
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
339
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
340
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
341
    }
342

    
343
    fft(x, MDCT_NBITS - 2);
344

    
345
    /* post rotation */
346
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
347
        re = x[i].re;
348
        im = x[i].im;
349
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
350
        out[                 2*i] = im1;
351
        out[MDCT_SAMPLES/2-1-2*i] = re1;
352
    }
353
}
354

    
355

    
356
/**
357
 * Apply KBD window to input samples prior to MDCT.
358
 */
359
static void apply_window(int16_t *output, const int16_t *input,
360
                         const int16_t *window, int n)
361
{
362
    int i;
363
    int n2 = n >> 1;
364

    
365
    for (i = 0; i < n2; i++) {
366
        output[i]     = MUL16(input[i],     window[i]) >> 15;
367
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
368
    }
369
}
370

    
371

    
372
/**
373
 * Calculate the log2() of the maximum absolute value in an array.
374
 * @param tab input array
375
 * @param n   number of values in the array
376
 * @return    log2(max(abs(tab[])))
377
 */
378
static int log2_tab(int16_t *tab, int n)
379
{
380
    int i, v;
381

    
382
    v = 0;
383
    for (i = 0; i < n; i++)
384
        v |= abs(tab[i]);
385

    
386
    return av_log2(v);
387
}
388

    
389

    
390
/**
391
 * Left-shift each value in an array by a specified amount.
392
 * @param tab    input array
393
 * @param n      number of values in the array
394
 * @param lshift left shift amount. a negative value means right shift.
395
 */
396
static void lshift_tab(int16_t *tab, int n, int lshift)
397
{
398
    int i;
399

    
400
    if (lshift > 0) {
401
        for (i = 0; i < n; i++)
402
            tab[i] <<= lshift;
403
    } else if (lshift < 0) {
404
        lshift = -lshift;
405
        for (i = 0; i < n; i++)
406
            tab[i] >>= lshift;
407
    }
408
}
409

    
410

    
411
/**
412
 * Normalize the input samples to use the maximum available precision.
413
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
414
 * match the 24-bit internal precision for MDCT coefficients.
415
 *
416
 * @return exponent shift
417
 */
418
static int normalize_samples(AC3EncodeContext *s)
419
{
420
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
421
    v = FFMAX(0, v);
422
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
423
    return v - 9;
424
}
425

    
426

    
427
/**
428
 * Apply the MDCT to input samples to generate frequency coefficients.
429
 * This applies the KBD window and normalizes the input to reduce precision
430
 * loss due to fixed-point calculations.
431
 */
432
static void apply_mdct(AC3EncodeContext *s)
433
{
434
    int blk, ch;
435

    
436
    for (ch = 0; ch < s->channels; ch++) {
437
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
438
            AC3Block *block = &s->blocks[blk];
439
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
440

    
441
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
442

    
443
            block->exp_shift[ch] = normalize_samples(s);
444

    
445
            mdct512(block->mdct_coef[ch], s->windowed_samples);
446
        }
447
    }
448
}
449

    
450

    
451
/**
452
 * Extract exponents from the MDCT coefficients.
453
 * This takes into account the normalization that was done to the input samples
454
 * by adjusting the exponents by the exponent shift values.
455
 */
456
static void extract_exponents(AC3EncodeContext *s)
457
{
458
    int blk, ch, i;
459

    
460
    for (ch = 0; ch < s->channels; ch++) {
461
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
462
            AC3Block *block = &s->blocks[blk];
463
            for (i = 0; i < AC3_MAX_COEFS; i++) {
464
                int e;
465
                int v = abs(block->mdct_coef[ch][i]);
466
                if (v == 0)
467
                    e = 24;
468
                else {
469
                    e = 23 - av_log2(v) + block->exp_shift[ch];
470
                    if (e >= 24) {
471
                        e = 24;
472
                        block->mdct_coef[ch][i] = 0;
473
                    }
474
                }
475
                block->exp[ch][i] = e;
476
            }
477
        }
478
    }
479
}
480

    
481

    
482
/**
483
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
484
 */
485
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
486
{
487
    int sum, i;
488
    sum = 0;
489
    for (i = 0; i < n; i++)
490
        sum += abs(exp1[i] - exp2[i]);
491
    return sum;
492
}
493

    
494

    
495
/**
496
 * Exponent Difference Threshold.
497
 * New exponents are sent if their SAD exceed this number.
498
 */
499
#define EXP_DIFF_THRESHOLD 1000
500

    
501

    
502
/**
503
 * Calculate exponent strategies for all blocks in a single channel.
504
 */
505
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
506
{
507
    int blk, blk1;
508
    int exp_diff;
509

    
510
    /* estimate if the exponent variation & decide if they should be
511
       reused in the next frame */
512
    exp_strategy[0] = EXP_NEW;
513
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
514
        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
515
        if (exp_diff > EXP_DIFF_THRESHOLD)
516
            exp_strategy[blk] = EXP_NEW;
517
        else
518
            exp_strategy[blk] = EXP_REUSE;
519
    }
520

    
521
    /* now select the encoding strategy type : if exponents are often
522
       recoded, we use a coarse encoding */
523
    blk = 0;
524
    while (blk < AC3_MAX_BLOCKS) {
525
        blk1 = blk + 1;
526
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
527
            blk1++;
528
        switch (blk1 - blk) {
529
        case 1:  exp_strategy[blk] = EXP_D45; break;
530
        case 2:
531
        case 3:  exp_strategy[blk] = EXP_D25; break;
532
        default: exp_strategy[blk] = EXP_D15; break;
533
        }
534
        blk = blk1;
535
    }
536
}
537

    
538

    
539
/**
540
 * Calculate exponent strategies for all channels.
541
 * Array arrangement is reversed to simplify the per-channel calculation.
542
 */
543
static void compute_exp_strategy(AC3EncodeContext *s)
544
{
545
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
546
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
547
    int ch, blk;
548

    
549
    for (ch = 0; ch < s->fbw_channels; ch++) {
550
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
551
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
552
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
553
        }
554

    
555
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
556

    
557
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
558
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
559
    }
560
    if (s->lfe_on) {
561
        ch = s->lfe_channel;
562
        s->blocks[0].exp_strategy[ch] = EXP_D15;
563
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
564
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
565
    }
566
}
567

    
568

    
569
/**
570
 * Set each encoded exponent in a block to the minimum of itself and the
571
 * exponent in the same frequency bin of a following block.
572
 * exp[i] = min(exp[i], exp1[i]
573
 */
574
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
575
{
576
    int i;
577
    for (i = 0; i < n; i++) {
578
        if (exp1[i] < exp[i])
579
            exp[i] = exp1[i];
580
    }
581
}
582

    
583

    
584
/**
585
 * Update the exponents so that they are the ones the decoder will decode.
586
 */
587
static void encode_exponents_blk_ch(uint8_t *encoded_exp, uint8_t *exp,
588
                                    int nb_exps, int exp_strategy,
589
                                    uint8_t *num_exp_groups)
590
{
591
    int group_size, nb_groups, i, j, k, exp_min;
592
    uint8_t exp1[AC3_MAX_COEFS];
593

    
594
    group_size = exp_strategy + (exp_strategy == EXP_D45);
595
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
596
    nb_groups = *num_exp_groups * 3;
597

    
598
    /* for each group, compute the minimum exponent */
599
    exp1[0] = exp[0]; /* DC exponent is handled separately */
600
    k = 1;
601
    for (i = 1; i <= nb_groups; i++) {
602
        exp_min = exp[k];
603
        assert(exp_min >= 0 && exp_min <= 24);
604
        for (j = 1; j < group_size; j++) {
605
            if (exp[k+j] < exp_min)
606
                exp_min = exp[k+j];
607
        }
608
        exp1[i] = exp_min;
609
        k += group_size;
610
    }
611

    
612
    /* constraint for DC exponent */
613
    if (exp1[0] > 15)
614
        exp1[0] = 15;
615

    
616
    /* decrease the delta between each groups to within 2 so that they can be
617
       differentially encoded */
618
    for (i = 1; i <= nb_groups; i++)
619
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
620
    for (i = nb_groups-1; i >= 0; i--)
621
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
622

    
623
    /* now we have the exponent values the decoder will see */
624
    encoded_exp[0] = exp1[0];
625
    k = 1;
626
    for (i = 1; i <= nb_groups; i++) {
627
        for (j = 0; j < group_size; j++)
628
            encoded_exp[k+j] = exp1[i];
629
        k += group_size;
630
    }
631
}
632

    
633

    
634
/**
635
 * Encode exponents from original extracted form to what the decoder will see.
636
 * This copies and groups exponents based on exponent strategy and reduces
637
 * deltas between adjacent exponent groups so that they can be differentially
638
 * encoded.
639
 */
640
static void encode_exponents(AC3EncodeContext *s)
641
{
642
    int blk, blk1, blk2, ch;
643
    AC3Block *block, *block1, *block2;
644

    
645
    for (ch = 0; ch < s->channels; ch++) {
646
        blk = 0;
647
        block = &s->blocks[0];
648
        while (blk < AC3_MAX_BLOCKS) {
649
            blk1 = blk + 1;
650
            block1 = block + 1;
651
            /* for the EXP_REUSE case we select the min of the exponents */
652
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
653
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
654
                blk1++;
655
                block1++;
656
            }
657
            encode_exponents_blk_ch(block->encoded_exp[ch],
658
                                    block->exp[ch], s->nb_coefs[ch],
659
                                    block->exp_strategy[ch],
660
                                    &block->num_exp_groups[ch]);
661
            /* copy encoded exponents for reuse case */
662
            block2 = block + 1;
663
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
664
                memcpy(block2->encoded_exp[ch], block->encoded_exp[ch],
665
                       s->nb_coefs[ch] * sizeof(uint8_t));
666
            }
667
            blk = blk1;
668
            block = block1;
669
        }
670
    }
671
}
672

    
673

    
674
/**
675
 * Group exponents.
676
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
677
 * varies depending on exponent strategy and bandwidth.
678
 */
679
static void group_exponents(AC3EncodeContext *s)
680
{
681
    int blk, ch, i;
682
    int group_size, bit_count;
683
    uint8_t *p;
684
    int delta0, delta1, delta2;
685
    int exp0, exp1;
686

    
687
    bit_count = 0;
688
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
689
        AC3Block *block = &s->blocks[blk];
690
        for (ch = 0; ch < s->channels; ch++) {
691
            if (block->exp_strategy[ch] == EXP_REUSE) {
692
                block->num_exp_groups[ch] = 0;
693
                continue;
694
            }
695
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
696
            bit_count += 4 + (block->num_exp_groups[ch] * 7);
697
            p = block->encoded_exp[ch];
698

    
699
            /* DC exponent */
700
            exp1 = *p++;
701
            block->grouped_exp[ch][0] = exp1;
702

    
703
            /* remaining exponents are delta encoded */
704
            for (i = 1; i <= block->num_exp_groups[ch]; i++) {
705
                /* merge three delta in one code */
706
                exp0   = exp1;
707
                exp1   = p[0];
708
                p     += group_size;
709
                delta0 = exp1 - exp0 + 2;
710

    
711
                exp0   = exp1;
712
                exp1   = p[0];
713
                p     += group_size;
714
                delta1 = exp1 - exp0 + 2;
715

    
716
                exp0   = exp1;
717
                exp1   = p[0];
718
                p     += group_size;
719
                delta2 = exp1 - exp0 + 2;
720

    
721
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
722
            }
723
        }
724
    }
725

    
726
    s->exponent_bits = bit_count;
727
}
728

    
729

    
730
/**
731
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
732
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
733
 * and encode final exponents.
734
 */
735
static void process_exponents(AC3EncodeContext *s)
736
{
737
    extract_exponents(s);
738

    
739
    compute_exp_strategy(s);
740

    
741
    encode_exponents(s);
742

    
743
    group_exponents(s);
744
}
745

    
746

    
747
/**
748
 * Initialize bit allocation.
749
 * Set default parameter codes and calculate parameter values.
750
 */
751
static void bit_alloc_init(AC3EncodeContext *s)
752
{
753
    int ch;
754

    
755
    /* init default parameters */
756
    s->slow_decay_code = 2;
757
    s->fast_decay_code = 1;
758
    s->slow_gain_code  = 1;
759
    s->db_per_bit_code = 2;
760
    s->floor_code      = 4;
761
    for (ch = 0; ch < s->channels; ch++)
762
        s->fast_gain_code[ch] = 4;
763

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

    
767
    /* compute real values */
768
    /* currently none of these values change during encoding, so we can just
769
       set them once at initialization */
770
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
771
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
772
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
773
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
774
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
775
}
776

    
777

    
778
/**
779
 * Count the bits used to encode the frame, minus exponents and mantissas.
780
 */
781
static void count_frame_bits(AC3EncodeContext *s)
782
{
783
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
784
    int blk, ch;
785
    int frame_bits;
786

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

    
791
    /* audio blocks */
792
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
793
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
794
        if (s->channel_mode == AC3_CHMODE_STEREO) {
795
            frame_bits++; /* rematstr */
796
            if (!blk)
797
                frame_bits += 4;
798
        }
799
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
800
        if (s->lfe_on)
801
            frame_bits++; /* lfeexpstr */
802
        for (ch = 0; ch < s->fbw_channels; ch++) {
803
            if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
804
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
805
        }
806
        frame_bits++; /* baie */
807
        frame_bits++; /* snr */
808
        frame_bits += 2; /* delta / skip */
809
    }
810
    frame_bits++; /* cplinu for block 0 */
811
    /* bit alloc info */
812
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
813
    /* csnroffset[6] */
814
    /* (fsnoffset[4] + fgaincod[4]) * c */
815
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
816

    
817
    /* auxdatae, crcrsv */
818
    frame_bits += 2;
819

    
820
    /* CRC */
821
    frame_bits += 16;
822

    
823
    s->frame_bits = frame_bits;
824
}
825

    
826

    
827
/**
828
 * Calculate the number of bits needed to encode a set of mantissas.
829
 */
830
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
831
{
832
    int bits, b, i;
833

    
834
    bits = 0;
835
    for (i = 0; i < nb_coefs; i++) {
836
        b = bap[i];
837
        switch (b) {
838
        case 0:
839
            /* bap=0 mantissas are not encoded */
840
            break;
841
        case 1:
842
            /* 3 mantissas in 5 bits */
843
            if (s->mant1_cnt == 0)
844
                bits += 5;
845
            if (++s->mant1_cnt == 3)
846
                s->mant1_cnt = 0;
847
            break;
848
        case 2:
849
            /* 3 mantissas in 7 bits */
850
            if (s->mant2_cnt == 0)
851
                bits += 7;
852
            if (++s->mant2_cnt == 3)
853
                s->mant2_cnt = 0;
854
            break;
855
        case 3:
856
            bits += 3;
857
            break;
858
        case 4:
859
            /* 2 mantissas in 7 bits */
860
            if (s->mant4_cnt == 0)
861
                bits += 7;
862
            if (++s->mant4_cnt == 2)
863
                s->mant4_cnt = 0;
864
            break;
865
        case 14:
866
            bits += 14;
867
            break;
868
        case 15:
869
            bits += 16;
870
            break;
871
        default:
872
            bits += b - 1;
873
            break;
874
        }
875
    }
876
    return bits;
877
}
878

    
879

    
880
/**
881
 * Calculate masking curve based on the final exponents.
882
 * Also calculate the power spectral densities to use in future calculations.
883
 */
884
static void bit_alloc_masking(AC3EncodeContext *s)
885
{
886
    int blk, ch;
887

    
888
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
889
        AC3Block *block = &s->blocks[blk];
890
        for (ch = 0; ch < s->channels; ch++) {
891
            if (block->exp_strategy[ch] == EXP_REUSE) {
892
                AC3Block *block1 = &s->blocks[blk-1];
893
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
894
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
895
            } else {
896
                ff_ac3_bit_alloc_calc_psd(block->encoded_exp[ch], 0,
897
                                          s->nb_coefs[ch],
898
                                          block->psd[ch], block->band_psd[ch]);
899
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
900
                                           0, s->nb_coefs[ch],
901
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
902
                                           ch == s->lfe_channel,
903
                                           DBA_NONE, 0, NULL, NULL, NULL,
904
                                           block->mask[ch]);
905
            }
906
        }
907
    }
908
}
909

    
910

    
911
/**
912
 * Ensure that bap for each block and channel point to the current bap_buffer.
913
 * They may have been switched during the bit allocation search.
914
 */
915
static void reset_block_bap(AC3EncodeContext *s)
916
{
917
    int blk, ch;
918
    if (s->blocks[0].bap[0] == s->bap_buffer)
919
        return;
920
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
921
        for (ch = 0; ch < s->channels; ch++) {
922
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
923
        }
924
    }
925
}
926

    
927

    
928
/**
929
 * Run the bit allocation with a given SNR offset.
930
 * This calculates the bit allocation pointers that will be used to determine
931
 * the quantization of each mantissa.
932
 * @return the number of bits needed for mantissas if the given SNR offset is
933
 *         is used.
934
 */
935
static int bit_alloc(AC3EncodeContext *s,
936
                     int snr_offset)
937
{
938
    int blk, ch;
939
    int mantissa_bits;
940

    
941
    snr_offset = (snr_offset - 240) << 2;
942

    
943
    reset_block_bap(s);
944
    mantissa_bits = 0;
945
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
946
        AC3Block *block = &s->blocks[blk];
947
        s->mant1_cnt = 0;
948
        s->mant2_cnt = 0;
949
        s->mant4_cnt = 0;
950
        for (ch = 0; ch < s->channels; ch++) {
951
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
952
                                      s->nb_coefs[ch], snr_offset,
953
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
954
                                      block->bap[ch]);
955
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
956
        }
957
    }
958
    return mantissa_bits;
959
}
960

    
961

    
962
/**
963
 * Constant bitrate bit allocation search.
964
 * Find the largest SNR offset that will allow data to fit in the frame.
965
 */
966
static int cbr_bit_allocation(AC3EncodeContext *s)
967
{
968
    int ch;
969
    int bits_left;
970
    int snr_offset;
971

    
972
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
973

    
974
    snr_offset = s->coarse_snr_offset << 4;
975

    
976
    while (snr_offset >= 0 &&
977
           bit_alloc(s, snr_offset) > bits_left) {
978
        snr_offset -= 64;
979
    }
980
    if (snr_offset < 0)
981
        return AVERROR(EINVAL);
982

    
983
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
984
    while (snr_offset + 64 <= 1023 &&
985
           bit_alloc(s, snr_offset + 64) <= bits_left) {
986
        snr_offset += 64;
987
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
988
    }
989
    while (snr_offset + 16 <= 1023 &&
990
           bit_alloc(s, snr_offset + 16) <= bits_left) {
991
        snr_offset += 16;
992
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
993
    }
994
    while (snr_offset + 4 <= 1023 &&
995
           bit_alloc(s, snr_offset + 4) <= bits_left) {
996
        snr_offset += 4;
997
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
998
    }
999
    while (snr_offset + 1 <= 1023 &&
1000
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1001
        snr_offset++;
1002
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1003
    }
1004
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1005
    reset_block_bap(s);
1006

    
1007
    s->coarse_snr_offset = snr_offset >> 4;
1008
    for (ch = 0; ch < s->channels; ch++)
1009
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1010

    
1011
    return 0;
1012
}
1013

    
1014

    
1015
/**
1016
 * Perform bit allocation search.
1017
 * Finds the SNR offset value that maximizes quality and fits in the specified
1018
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1019
 * used to quantize the mantissas.
1020
 */
1021
static int compute_bit_allocation(AC3EncodeContext *s)
1022
{
1023
    count_frame_bits(s);
1024

    
1025
    bit_alloc_masking(s);
1026

    
1027
    return cbr_bit_allocation(s);
1028
}
1029

    
1030

    
1031
/**
1032
 * Symmetric quantization on 'levels' levels.
1033
 */
1034
static inline int sym_quant(int c, int e, int levels)
1035
{
1036
    int v;
1037

    
1038
    if (c >= 0) {
1039
        v = (levels * (c << e)) >> 24;
1040
        v = (v + 1) >> 1;
1041
        v = (levels >> 1) + v;
1042
    } else {
1043
        v = (levels * ((-c) << e)) >> 24;
1044
        v = (v + 1) >> 1;
1045
        v = (levels >> 1) - v;
1046
    }
1047
    assert(v >= 0 && v < levels);
1048
    return v;
1049
}
1050

    
1051

    
1052
/**
1053
 * Asymmetric quantization on 2^qbits levels.
1054
 */
1055
static inline int asym_quant(int c, int e, int qbits)
1056
{
1057
    int lshift, m, v;
1058

    
1059
    lshift = e + qbits - 24;
1060
    if (lshift >= 0)
1061
        v = c << lshift;
1062
    else
1063
        v = c >> (-lshift);
1064
    /* rounding */
1065
    v = (v + 1) >> 1;
1066
    m = (1 << (qbits-1));
1067
    if (v >= m)
1068
        v = m - 1;
1069
    assert(v >= -m);
1070
    return v & ((1 << qbits)-1);
1071
}
1072

    
1073

    
1074
/**
1075
 * Quantize a set of mantissas for a single channel in a single block.
1076
 */
1077
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1078
                                      int32_t *mdct_coef, int8_t exp_shift,
1079
                                      uint8_t *encoded_exp, uint8_t *bap,
1080
                                      uint16_t *qmant, int n)
1081
{
1082
    int i;
1083

    
1084
    for (i = 0; i < n; i++) {
1085
        int v;
1086
        int c = mdct_coef[i];
1087
        int e = encoded_exp[i] - exp_shift;
1088
        int b = bap[i];
1089
        switch (b) {
1090
        case 0:
1091
            v = 0;
1092
            break;
1093
        case 1:
1094
            v = sym_quant(c, e, 3);
1095
            switch (s->mant1_cnt) {
1096
            case 0:
1097
                s->qmant1_ptr = &qmant[i];
1098
                v = 9 * v;
1099
                s->mant1_cnt = 1;
1100
                break;
1101
            case 1:
1102
                *s->qmant1_ptr += 3 * v;
1103
                s->mant1_cnt = 2;
1104
                v = 128;
1105
                break;
1106
            default:
1107
                *s->qmant1_ptr += v;
1108
                s->mant1_cnt = 0;
1109
                v = 128;
1110
                break;
1111
            }
1112
            break;
1113
        case 2:
1114
            v = sym_quant(c, e, 5);
1115
            switch (s->mant2_cnt) {
1116
            case 0:
1117
                s->qmant2_ptr = &qmant[i];
1118
                v = 25 * v;
1119
                s->mant2_cnt = 1;
1120
                break;
1121
            case 1:
1122
                *s->qmant2_ptr += 5 * v;
1123
                s->mant2_cnt = 2;
1124
                v = 128;
1125
                break;
1126
            default:
1127
                *s->qmant2_ptr += v;
1128
                s->mant2_cnt = 0;
1129
                v = 128;
1130
                break;
1131
            }
1132
            break;
1133
        case 3:
1134
            v = sym_quant(c, e, 7);
1135
            break;
1136
        case 4:
1137
            v = sym_quant(c, e, 11);
1138
            switch (s->mant4_cnt) {
1139
            case 0:
1140
                s->qmant4_ptr = &qmant[i];
1141
                v = 11 * v;
1142
                s->mant4_cnt = 1;
1143
                break;
1144
            default:
1145
                *s->qmant4_ptr += v;
1146
                s->mant4_cnt = 0;
1147
                v = 128;
1148
                break;
1149
            }
1150
            break;
1151
        case 5:
1152
            v = sym_quant(c, e, 15);
1153
            break;
1154
        case 14:
1155
            v = asym_quant(c, e, 14);
1156
            break;
1157
        case 15:
1158
            v = asym_quant(c, e, 16);
1159
            break;
1160
        default:
1161
            v = asym_quant(c, e, b - 1);
1162
            break;
1163
        }
1164
        qmant[i] = v;
1165
    }
1166
}
1167

    
1168

    
1169
/**
1170
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1171
 */
1172
static void quantize_mantissas(AC3EncodeContext *s)
1173
{
1174
    int blk, ch;
1175

    
1176

    
1177
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1178
        AC3Block *block = &s->blocks[blk];
1179
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1180
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1181

    
1182
        for (ch = 0; ch < s->channels; ch++) {
1183
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1184
                                      block->encoded_exp[ch], block->bap[ch],
1185
                                      block->qmant[ch], s->nb_coefs[ch]);
1186
        }
1187
    }
1188
}
1189

    
1190

    
1191
/**
1192
 * Write the AC-3 frame header to the output bitstream.
1193
 */
1194
static void output_frame_header(AC3EncodeContext *s)
1195
{
1196
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1197
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1198
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1199
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1200
    put_bits(&s->pb, 5,  s->bitstream_id);
1201
    put_bits(&s->pb, 3,  s->bitstream_mode);
1202
    put_bits(&s->pb, 3,  s->channel_mode);
1203
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1204
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1205
    if (s->channel_mode & 0x04)
1206
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1207
    if (s->channel_mode == AC3_CHMODE_STEREO)
1208
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1209
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1210
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1211
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1212
    put_bits(&s->pb, 1, 0);         /* no lang code */
1213
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1214
    put_bits(&s->pb, 1, 0);         /* no copyright */
1215
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1216
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1217
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1218
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1219
}
1220

    
1221

    
1222
/**
1223
 * Write one audio block to the output bitstream.
1224
 */
1225
static void output_audio_block(AC3EncodeContext *s,
1226
                               int block_num)
1227
{
1228
    int ch, i, baie, rbnd;
1229
    AC3Block *block = &s->blocks[block_num];
1230

    
1231
    /* block switching */
1232
    for (ch = 0; ch < s->fbw_channels; ch++)
1233
        put_bits(&s->pb, 1, 0);
1234

    
1235
    /* dither flags */
1236
    for (ch = 0; ch < s->fbw_channels; ch++)
1237
        put_bits(&s->pb, 1, 1);
1238

    
1239
    /* dynamic range codes */
1240
    put_bits(&s->pb, 1, 0);
1241

    
1242
    /* channel coupling */
1243
    if (!block_num) {
1244
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1245
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1246
    } else {
1247
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1248
    }
1249

    
1250
    /* stereo rematrixing */
1251
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1252
        if (!block_num) {
1253
            /* first block must define rematrixing (rematstr) */
1254
            put_bits(&s->pb, 1, 1);
1255

    
1256
            /* dummy rematrixing rematflg(1:4)=0 */
1257
            for (rbnd = 0; rbnd < 4; rbnd++)
1258
                put_bits(&s->pb, 1, 0);
1259
        } else {
1260
            /* no matrixing (but should be used in the future) */
1261
            put_bits(&s->pb, 1, 0);
1262
        }
1263
    }
1264

    
1265
    /* exponent strategy */
1266
    for (ch = 0; ch < s->fbw_channels; ch++)
1267
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1268
    if (s->lfe_on)
1269
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1270

    
1271
    /* bandwidth */
1272
    for (ch = 0; ch < s->fbw_channels; ch++) {
1273
        if (block->exp_strategy[ch] != EXP_REUSE)
1274
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1275
    }
1276

    
1277
    /* exponents */
1278
    for (ch = 0; ch < s->channels; ch++) {
1279
        if (block->exp_strategy[ch] == EXP_REUSE)
1280
            continue;
1281

    
1282
        /* DC exponent */
1283
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1284

    
1285
        /* exponent groups */
1286
        for (i = 1; i <= block->num_exp_groups[ch]; i++)
1287
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1288

    
1289
        /* gain range info */
1290
        if (ch != s->lfe_channel)
1291
            put_bits(&s->pb, 2, 0);
1292
    }
1293

    
1294
    /* bit allocation info */
1295
    baie = (block_num == 0);
1296
    put_bits(&s->pb, 1, baie);
1297
    if (baie) {
1298
        put_bits(&s->pb, 2, s->slow_decay_code);
1299
        put_bits(&s->pb, 2, s->fast_decay_code);
1300
        put_bits(&s->pb, 2, s->slow_gain_code);
1301
        put_bits(&s->pb, 2, s->db_per_bit_code);
1302
        put_bits(&s->pb, 3, s->floor_code);
1303
    }
1304

    
1305
    /* snr offset */
1306
    put_bits(&s->pb, 1, baie);
1307
    if (baie) {
1308
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1309
        for (ch = 0; ch < s->channels; ch++) {
1310
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1311
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1312
        }
1313
    }
1314

    
1315
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1316
    put_bits(&s->pb, 1, 0); /* no data to skip */
1317

    
1318
    /* mantissas */
1319
    for (ch = 0; ch < s->channels; ch++) {
1320
        int b, q;
1321
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1322
            q = block->qmant[ch][i];
1323
            b = block->bap[ch][i];
1324
            switch (b) {
1325
            case 0:                                         break;
1326
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1327
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1328
            case 3:               put_bits(&s->pb,   3, q); break;
1329
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1330
            case 14:              put_bits(&s->pb,  14, q); break;
1331
            case 15:              put_bits(&s->pb,  16, q); break;
1332
            default:              put_bits(&s->pb, b-1, q); break;
1333
            }
1334
        }
1335
    }
1336
}
1337

    
1338

    
1339
/** CRC-16 Polynomial */
1340
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1341

    
1342

    
1343
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1344
{
1345
    unsigned int c;
1346

    
1347
    c = 0;
1348
    while (a) {
1349
        if (a & 1)
1350
            c ^= b;
1351
        a = a >> 1;
1352
        b = b << 1;
1353
        if (b & (1 << 16))
1354
            b ^= poly;
1355
    }
1356
    return c;
1357
}
1358

    
1359

    
1360
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1361
{
1362
    unsigned int r;
1363
    r = 1;
1364
    while (n) {
1365
        if (n & 1)
1366
            r = mul_poly(r, a, poly);
1367
        a = mul_poly(a, a, poly);
1368
        n >>= 1;
1369
    }
1370
    return r;
1371
}
1372

    
1373

    
1374
/**
1375
 * Fill the end of the frame with 0's and compute the two CRCs.
1376
 */
1377
static void output_frame_end(AC3EncodeContext *s)
1378
{
1379
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1380
    uint8_t *frame;
1381

    
1382
    frame_size    = s->frame_size;
1383
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1384

    
1385
    /* pad the remainder of the frame with zeros */
1386
    flush_put_bits(&s->pb);
1387
    frame = s->pb.buf;
1388
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1389
    assert(pad_bytes >= 0);
1390
    if (pad_bytes > 0)
1391
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1392

    
1393
    /* compute crc1 */
1394
    /* this is not so easy because it is at the beginning of the data... */
1395
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1396
                             frame + 4, frame_size_58 - 4));
1397
    /* XXX: could precompute crc_inv */
1398
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1399
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1400
    AV_WB16(frame + 2, crc1);
1401

    
1402
    /* compute crc2 */
1403
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1404
                             frame + frame_size_58,
1405
                             frame_size - frame_size_58 - 2));
1406
    AV_WB16(frame + frame_size - 2, crc2);
1407
}
1408

    
1409

    
1410
/**
1411
 * Write the frame to the output bitstream.
1412
 */
1413
static void output_frame(AC3EncodeContext *s,
1414
                         unsigned char *frame)
1415
{
1416
    int blk;
1417

    
1418
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1419

    
1420
    output_frame_header(s);
1421

    
1422
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1423
        output_audio_block(s, blk);
1424

    
1425
    output_frame_end(s);
1426
}
1427

    
1428

    
1429
/**
1430
 * Encode a single AC-3 frame.
1431
 */
1432
static int ac3_encode_frame(AVCodecContext *avctx,
1433
                            unsigned char *frame, int buf_size, void *data)
1434
{
1435
    AC3EncodeContext *s = avctx->priv_data;
1436
    const int16_t *samples = data;
1437
    int ret;
1438

    
1439
    if (s->bit_alloc.sr_code == 1)
1440
        adjust_frame_size(s);
1441

    
1442
    deinterleave_input_samples(s, samples);
1443

    
1444
    apply_mdct(s);
1445

    
1446
    process_exponents(s);
1447

    
1448
    ret = compute_bit_allocation(s);
1449
    if (ret) {
1450
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1451
        return ret;
1452
    }
1453

    
1454
    quantize_mantissas(s);
1455

    
1456
    output_frame(s, frame);
1457

    
1458
    return s->frame_size;
1459
}
1460

    
1461

    
1462
/**
1463
 * Finalize encoding and free any memory allocated by the encoder.
1464
 */
1465
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1466
{
1467
    int blk;
1468
    AC3EncodeContext *s = avctx->priv_data;
1469

    
1470
    av_freep(&s->bap_buffer);
1471
    av_freep(&s->bap1_buffer);
1472
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1473
        AC3Block *block = &s->blocks[blk];
1474
        av_freep(&block->bap);
1475
    }
1476

    
1477
    av_freep(&avctx->coded_frame);
1478
    return 0;
1479
}
1480

    
1481

    
1482
/**
1483
 * Set channel information during initialization.
1484
 */
1485
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1486
                                    int64_t *channel_layout)
1487
{
1488
    int ch_layout;
1489

    
1490
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1491
        return AVERROR(EINVAL);
1492
    if ((uint64_t)*channel_layout > 0x7FF)
1493
        return AVERROR(EINVAL);
1494
    ch_layout = *channel_layout;
1495
    if (!ch_layout)
1496
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1497
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1498
        return AVERROR(EINVAL);
1499

    
1500
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1501
    s->channels     = channels;
1502
    s->fbw_channels = channels - s->lfe_on;
1503
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1504
    if (s->lfe_on)
1505
        ch_layout -= AV_CH_LOW_FREQUENCY;
1506

    
1507
    switch (ch_layout) {
1508
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1509
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1510
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1511
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1512
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1513
    case AV_CH_LAYOUT_QUAD:
1514
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1515
    case AV_CH_LAYOUT_5POINT0:
1516
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1517
    default:
1518
        return AVERROR(EINVAL);
1519
    }
1520

    
1521
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1522
    *channel_layout = ch_layout;
1523
    if (s->lfe_on)
1524
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1525

    
1526
    return 0;
1527
}
1528

    
1529

    
1530
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1531
{
1532
    int i, ret;
1533

    
1534
    /* validate channel layout */
1535
    if (!avctx->channel_layout) {
1536
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1537
                                      "encoder will guess the layout, but it "
1538
                                      "might be incorrect.\n");
1539
    }
1540
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1541
    if (ret) {
1542
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1543
        return ret;
1544
    }
1545

    
1546
    /* validate sample rate */
1547
    for (i = 0; i < 9; i++) {
1548
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1549
            break;
1550
    }
1551
    if (i == 9) {
1552
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1553
        return AVERROR(EINVAL);
1554
    }
1555
    s->sample_rate        = avctx->sample_rate;
1556
    s->bit_alloc.sr_shift = i % 3;
1557
    s->bit_alloc.sr_code  = i / 3;
1558

    
1559
    /* validate bit rate */
1560
    for (i = 0; i < 19; i++) {
1561
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1562
            break;
1563
    }
1564
    if (i == 19) {
1565
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1566
        return AVERROR(EINVAL);
1567
    }
1568
    s->bit_rate        = avctx->bit_rate;
1569
    s->frame_size_code = i << 1;
1570

    
1571
    return 0;
1572
}
1573

    
1574

    
1575
/**
1576
 * Set bandwidth for all channels.
1577
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1578
 * default value will be used.
1579
 */
1580
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1581
{
1582
    int ch, bw_code;
1583

    
1584
    if (cutoff) {
1585
        /* calculate bandwidth based on user-specified cutoff frequency */
1586
        int fbw_coeffs;
1587
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1588
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1589
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1590
    } else {
1591
        /* use default bandwidth setting */
1592
        /* XXX: should compute the bandwidth according to the frame
1593
           size, so that we avoid annoying high frequency artifacts */
1594
        bw_code = 50;
1595
    }
1596

    
1597
    /* set number of coefficients for each channel */
1598
    for (ch = 0; ch < s->fbw_channels; ch++) {
1599
        s->bandwidth_code[ch] = bw_code;
1600
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1601
    }
1602
    if (s->lfe_on)
1603
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1604
}
1605

    
1606

    
1607
static av_cold int allocate_buffers(AVCodecContext *avctx)
1608
{
1609
    int blk;
1610
    AC3EncodeContext *s = avctx->priv_data;
1611

    
1612
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1613
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1614
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1615
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1616
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1617
        AC3Block *block = &s->blocks[blk];
1618
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1619
                         alloc_fail);
1620
    }
1621
    s->blocks[0].bap[0] = NULL;
1622
    reset_block_bap(s);
1623

    
1624
    return 0;
1625
alloc_fail:
1626
    return AVERROR(ENOMEM);
1627
}
1628

    
1629

    
1630
/**
1631
 * Initialize the encoder.
1632
 */
1633
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1634
{
1635
    AC3EncodeContext *s = avctx->priv_data;
1636
    int ret;
1637

    
1638
    avctx->frame_size = AC3_FRAME_SIZE;
1639

    
1640
    ac3_common_init();
1641

    
1642
    ret = validate_options(avctx, s);
1643
    if (ret)
1644
        return ret;
1645

    
1646
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1647
    s->bitstream_mode = 0; /* complete main audio service */
1648

    
1649
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1650
    s->bits_written    = 0;
1651
    s->samples_written = 0;
1652
    s->frame_size      = s->frame_size_min;
1653

    
1654
    set_bandwidth(s, avctx->cutoff);
1655

    
1656
    bit_alloc_init(s);
1657

    
1658
    mdct_init(9);
1659

    
1660
    ret = allocate_buffers(avctx);
1661
    if (ret) {
1662
        ac3_encode_close(avctx);
1663
        return ret;
1664
    }
1665

    
1666
    avctx->coded_frame= avcodec_alloc_frame();
1667

    
1668
    return 0;
1669
}
1670

    
1671

    
1672
#ifdef TEST
1673
/*************************************************************************/
1674
/* TEST */
1675

    
1676
#include "libavutil/lfg.h"
1677

    
1678
#define FN (MDCT_SAMPLES/4)
1679

    
1680

    
1681
static void fft_test(AVLFG *lfg)
1682
{
1683
    IComplex in[FN], in1[FN];
1684
    int k, n, i;
1685
    float sum_re, sum_im, a;
1686

    
1687
    for (i = 0; i < FN; i++) {
1688
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1689
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1690
        in1[i]   = in[i];
1691
    }
1692
    fft(in, 7);
1693

    
1694
    /* do it by hand */
1695
    for (k = 0; k < FN; k++) {
1696
        sum_re = 0;
1697
        sum_im = 0;
1698
        for (n = 0; n < FN; n++) {
1699
            a = -2 * M_PI * (n * k) / FN;
1700
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1701
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1702
        }
1703
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1704
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1705
    }
1706
}
1707

    
1708

    
1709
static void mdct_test(AVLFG *lfg)
1710
{
1711
    int16_t input[MDCT_SAMPLES];
1712
    int32_t output[AC3_MAX_COEFS];
1713
    float input1[MDCT_SAMPLES];
1714
    float output1[AC3_MAX_COEFS];
1715
    float s, a, err, e, emax;
1716
    int i, k, n;
1717

    
1718
    for (i = 0; i < MDCT_SAMPLES; i++) {
1719
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1720
        input1[i] = input[i];
1721
    }
1722

    
1723
    mdct512(output, input);
1724

    
1725
    /* do it by hand */
1726
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1727
        s = 0;
1728
        for (n = 0; n < MDCT_SAMPLES; n++) {
1729
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1730
            s += input1[n] * cos(a);
1731
        }
1732
        output1[k] = -2 * s / MDCT_SAMPLES;
1733
    }
1734

    
1735
    err  = 0;
1736
    emax = 0;
1737
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1738
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1739
        e = output[i] - output1[i];
1740
        if (e > emax)
1741
            emax = e;
1742
        err += e * e;
1743
    }
1744
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1745
}
1746

    
1747

    
1748
int main(void)
1749
{
1750
    AVLFG lfg;
1751

    
1752
    av_log_set_level(AV_LOG_DEBUG);
1753
    mdct_init(9);
1754

    
1755
    fft_test(&lfg);
1756
    mdct_test(&lfg);
1757

    
1758
    return 0;
1759
}
1760
#endif /* TEST */
1761

    
1762

    
1763
AVCodec ac3_encoder = {
1764
    "ac3",
1765
    AVMEDIA_TYPE_AUDIO,
1766
    CODEC_ID_AC3,
1767
    sizeof(AC3EncodeContext),
1768
    ac3_encode_init,
1769
    ac3_encode_frame,
1770
    ac3_encode_close,
1771
    NULL,
1772
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1773
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1774
    .channel_layouts = (const int64_t[]){
1775
        AV_CH_LAYOUT_MONO,
1776
        AV_CH_LAYOUT_STEREO,
1777
        AV_CH_LAYOUT_2_1,
1778
        AV_CH_LAYOUT_SURROUND,
1779
        AV_CH_LAYOUT_2_2,
1780
        AV_CH_LAYOUT_QUAD,
1781
        AV_CH_LAYOUT_4POINT0,
1782
        AV_CH_LAYOUT_5POINT0,
1783
        AV_CH_LAYOUT_5POINT0_BACK,
1784
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1785
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1786
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1787
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1788
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1789
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1790
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1791
        AV_CH_LAYOUT_5POINT1,
1792
        AV_CH_LAYOUT_5POINT1_BACK,
1793
        0 },
1794
};