Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ cb6247cb

History | View | Annotate | Download (50.2 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
 * AC-3 encoder private context.
60
 */
61
typedef struct AC3EncodeContext {
62
    PutBitContext pb;                       ///< bitstream writer context
63

    
64
    int bitstream_id;                       ///< bitstream id                           (bsid)
65
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
66

    
67
    int bit_rate;                           ///< target bit rate, in bits-per-second
68
    int sample_rate;                        ///< sampling frequency, in Hz
69

    
70
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
71
    int frame_size;                         ///< current frame size in bytes
72
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
73
    int bits_written;                       ///< bit count    (used to avg. bitrate)
74
    int samples_written;                    ///< sample count (used to avg. bitrate)
75

    
76
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
77
    int channels;                           ///< total number of channels               (nchans)
78
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
79
    int lfe_channel;                        ///< channel index of the LFE channel
80
    int channel_mode;                       ///< channel mode                           (acmod)
81
    const uint8_t *channel_map;             ///< channel map used to reorder channels
82

    
83
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
84
    int nb_coefs[AC3_MAX_CHANNELS];
85

    
86
    /* bitrate allocation control */
87
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
88
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
89
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
90
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
91
    int floor_code;                         ///< floor code                             (floorcod)
92
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
93
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
94
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
95
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
96
    int frame_bits;                         ///< all frame bits except exponents and mantissas
97
    int exponent_bits;                      ///< number of bits used for exponents
98

    
99
    /* mantissa encoding */
100
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
101
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
102

    
103
    int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
104
    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
105
    int16_t windowed_samples[AC3_WINDOW_SIZE];
106
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
107
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
108
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
109
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
110
    uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
111
    uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
112
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
113
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
114
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
115
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
116
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
117
    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
118
    uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
119
} AC3EncodeContext;
120

    
121

    
122
/** MDCT and FFT tables */
123
static int16_t costab[64];
124
static int16_t sintab[64];
125
static int16_t xcos1[128];
126
static int16_t xsin1[128];
127

    
128

    
129
/**
130
 * Adjust the frame size to make the average bit rate match the target bit rate.
131
 * This is only needed for 11025, 22050, and 44100 sample rates.
132
 */
133
static void adjust_frame_size(AC3EncodeContext *s)
134
{
135
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
136
        s->bits_written    -= s->bit_rate;
137
        s->samples_written -= s->sample_rate;
138
    }
139
    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
140
    s->bits_written    += s->frame_size * 8;
141
    s->samples_written += AC3_FRAME_SIZE;
142
}
143

    
144

    
145
/**
146
 * Deinterleave input samples.
147
 * Channels are reordered from FFmpeg's default order to AC-3 order.
148
 */
149
static void deinterleave_input_samples(AC3EncodeContext *s,
150
                                       const int16_t *samples)
151
{
152
    int ch, i;
153

    
154
    /* deinterleave and remap input samples */
155
    for (ch = 0; ch < s->channels; ch++) {
156
        const int16_t *sptr;
157
        int sinc;
158

    
159
        /* copy last 256 samples of previous frame to the start of the current frame */
160
        memcpy(&s->planar_samples[ch][0], s->last_samples[ch],
161
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
162

    
163
        /* deinterleave */
164
        sinc = s->channels;
165
        sptr = samples + s->channel_map[ch];
166
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
167
            s->planar_samples[ch][i] = *sptr;
168
            sptr += sinc;
169
        }
170

    
171
        /* save last 256 samples for next frame */
172
        memcpy(s->last_samples[ch], &s->planar_samples[ch][6* AC3_BLOCK_SIZE],
173
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
174
    }
175
}
176

    
177

    
178
/**
179
 * Initialize FFT tables.
180
 * @param ln log2(FFT size)
181
 */
182
static av_cold void fft_init(int ln)
183
{
184
    int i, n, n2;
185
    float alpha;
186

    
187
    n  = 1 << ln;
188
    n2 = n >> 1;
189

    
190
    for (i = 0; i < n2; i++) {
191
        alpha     = 2.0 * M_PI * i / n;
192
        costab[i] = FIX15(cos(alpha));
193
        sintab[i] = FIX15(sin(alpha));
194
    }
195
}
196

    
197

    
198
/**
199
 * Initialize MDCT tables.
200
 * @param nbits log2(MDCT size)
201
 */
202
static av_cold void mdct_init(int nbits)
203
{
204
    int i, n, n4;
205

    
206
    n  = 1 << nbits;
207
    n4 = n >> 2;
208

    
209
    fft_init(nbits - 2);
210

    
211
    for (i = 0; i < n4; i++) {
212
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
213
        xcos1[i] = FIX15(-cos(alpha));
214
        xsin1[i] = FIX15(-sin(alpha));
215
    }
216
}
217

    
218

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

    
233

    
234
/** Complex multiply */
235
#define CMUL(pre, pim, are, aim, bre, bim)              \
236
{                                                       \
237
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
238
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
239
}
240

    
241

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

    
254
    np = 1 << ln;
255

    
256
    /* reverse */
257
    for (j = 0; j < np; j++) {
258
        int k = av_reverse[j] >> (8 - ln);
259
        if (k < j)
260
            FFSWAP(IComplex, z[k], z[j]);
261
    }
262

    
263
    /* pass 0 */
264

    
265
    p = &z[0];
266
    j = np >> 1;
267
    do {
268
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
269
           p[0].re, p[0].im, p[1].re, p[1].im);
270
        p += 2;
271
    } while (--j);
272

    
273
    /* pass 1 */
274

    
275
    p = &z[0];
276
    j = np >> 2;
277
    do {
278
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
279
           p[0].re, p[0].im, p[2].re,  p[2].im);
280
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
281
           p[1].re, p[1].im, p[3].im, -p[3].re);
282
        p+=4;
283
    } while (--j);
284

    
285
    /* pass 2 .. ln-1 */
286

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

    
313

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

    
325
    /* shift to simplify computations */
326
    for (i = 0; i < MDCT_SAMPLES/4; i++)
327
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
328
    for (;i < MDCT_SAMPLES; i++)
329
        rot[i] =  in[i -   MDCT_SAMPLES/4];
330

    
331
    /* pre rotation */
332
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
333
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
334
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
335
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
336
    }
337

    
338
    fft(x, MDCT_NBITS - 2);
339

    
340
    /* post rotation */
341
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
342
        re = x[i].re;
343
        im = x[i].im;
344
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
345
        out[                 2*i] = im1;
346
        out[MDCT_SAMPLES/2-1-2*i] = re1;
347
    }
348
}
349

    
350

    
351
/**
352
 * Apply KBD window to input samples prior to MDCT.
353
 */
354
static void apply_window(int16_t *output, const int16_t *input,
355
                         const int16_t *window, int n)
356
{
357
    int i;
358
    int n2 = n >> 1;
359

    
360
    for (i = 0; i < n2; i++) {
361
        output[i]     = MUL16(input[i],     window[i]) >> 15;
362
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
363
    }
364
}
365

    
366

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

    
377
    v = 0;
378
    for (i = 0; i < n; i++)
379
        v |= abs(tab[i]);
380

    
381
    return av_log2(v);
382
}
383

    
384

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

    
395
    if (lshift > 0) {
396
        for(i = 0; i < n; i++)
397
            tab[i] <<= lshift;
398
    } else if (lshift < 0) {
399
        lshift = -lshift;
400
        for (i = 0; i < n; i++)
401
            tab[i] >>= lshift;
402
    }
403
}
404

    
405

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

    
421

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

    
431
    for (ch = 0; ch < s->channels; ch++) {
432
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
433
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
434

    
435
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
436

    
437
            s->exp_shift[blk][ch] = normalize_samples(s);
438

    
439
            mdct512(s->mdct_coef[blk][ch], s->windowed_samples);
440
        }
441
    }
442
}
443

    
444

    
445
/**
446
 * Extract exponents from the MDCT coefficients.
447
 * This takes into account the normalization that was done to the input samples
448
 * by adjusting the exponents by the exponent shift values.
449
 */
450
static void extract_exponents(AC3EncodeContext *s)
451
{
452
    int blk, ch, i;
453

    
454
    /* extract exponents */
455
    for (ch = 0; ch < s->channels; ch++) {
456
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
457
            /* compute "exponents". We take into account the normalization there */
458
            for (i = 0; i < AC3_MAX_COEFS; i++) {
459
                int e;
460
                int v = abs(s->mdct_coef[blk][ch][i]);
461
                if (v == 0)
462
                    e = 24;
463
                else {
464
                    e = 23 - av_log2(v) + s->exp_shift[blk][ch];
465
                    if (e >= 24) {
466
                        e = 24;
467
                        s->mdct_coef[blk][ch][i] = 0;
468
                    }
469
                }
470
                s->exp[blk][ch][i] = e;
471
            }
472
        }
473
    }
474
}
475

    
476

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

    
489

    
490
/**
491
 * Exponent Difference Threshold.
492
 * New exponents are sent if their SAD exceed this number.
493
 */
494
#define EXP_DIFF_THRESHOLD 1000
495

    
496

    
497
/**
498
 * Calculate exponent strategies for all blocks in a single channel.
499
 */
500
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
501
{
502
    int blk, blk1;
503
    int exp_diff;
504

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

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

    
533

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

    
544
    for (ch = 0; ch < s->fbw_channels; ch++) {
545
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
546
            exp1[ch][blk]     = s->exp[blk][ch];
547
            exp_str1[ch][blk] = s->exp_strategy[blk][ch];
548
        }
549

    
550
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
551

    
552
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
553
            s->exp_strategy[blk][ch] = exp_str1[ch][blk];
554
    }
555
    if (s->lfe_on) {
556
        ch = s->lfe_channel;
557
        s->exp_strategy[0][ch] = EXP_D15;
558
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
559
            s->exp_strategy[blk][ch] = EXP_REUSE;
560
    }
561
}
562

    
563

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

    
578

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

    
590
    group_size = exp_strategy + (exp_strategy == EXP_D45);
591
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
592
    nb_groups = *num_exp_groups * 3;
593

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

    
608
    /* constraint for DC exponent */
609
    if (exp1[0] > 15)
610
        exp1[0] = 15;
611

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

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

    
629

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

    
640
    for (ch = 0; ch < s->channels; ch++) {
641
        /* for the EXP_REUSE case we select the min of the exponents */
642
        blk = 0;
643
        while (blk < AC3_MAX_BLOCKS) {
644
            blk1 = blk + 1;
645
            while (blk1 < AC3_MAX_BLOCKS && s->exp_strategy[blk1][ch] == EXP_REUSE) {
646
                exponent_min(s->exp[blk][ch], s->exp[blk1][ch], s->nb_coefs[ch]);
647
                blk1++;
648
            }
649
            encode_exponents_blk_ch(s->encoded_exp[blk][ch],
650
                                    s->exp[blk][ch], s->nb_coefs[ch],
651
                                    s->exp_strategy[blk][ch],
652
                                    &s->num_exp_groups[blk][ch]);
653
            /* copy encoded exponents for reuse case */
654
            for (blk2 = blk+1; blk2 < blk1; blk2++) {
655
                memcpy(s->encoded_exp[blk2][ch], s->encoded_exp[blk][ch],
656
                       s->nb_coefs[ch] * sizeof(uint8_t));
657
            }
658
            blk = blk1;
659
        }
660
    }
661
}
662

    
663

    
664
/**
665
 * Group exponents.
666
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
667
 * varies depending on exponent strategy and bandwidth.
668
 */
669
static void group_exponents(AC3EncodeContext *s)
670
{
671
    int blk, ch, i;
672
    int group_size, bit_count;
673
    uint8_t *p;
674
    int delta0, delta1, delta2;
675
    int exp0, exp1;
676

    
677
    bit_count = 0;
678
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
679
        for (ch = 0; ch < s->channels; ch++) {
680
            if (s->exp_strategy[blk][ch] == EXP_REUSE) {
681
                s->num_exp_groups[blk][ch] = 0;
682
                continue;
683
            }
684
            group_size = s->exp_strategy[blk][ch] + (s->exp_strategy[blk][ch] == EXP_D45);
685
            bit_count += 4 + (s->num_exp_groups[blk][ch] * 7);
686
            p = s->encoded_exp[blk][ch];
687

    
688
            /* DC exponent */
689
            exp1 = *p++;
690
            s->grouped_exp[blk][ch][0] = exp1;
691

    
692
            /* remaining exponents are delta encoded */
693
            for (i = 1; i <= s->num_exp_groups[blk][ch]; i++) {
694
                /* merge three delta in one code */
695
                exp0   = exp1;
696
                exp1   = p[0];
697
                p     += group_size;
698
                delta0 = exp1 - exp0 + 2;
699

    
700
                exp0   = exp1;
701
                exp1   = p[0];
702
                p     += group_size;
703
                delta1 = exp1 - exp0 + 2;
704

    
705
                exp0   = exp1;
706
                exp1   = p[0];
707
                p     += group_size;
708
                delta2 = exp1 - exp0 + 2;
709

    
710
                s->grouped_exp[blk][ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
711
            }
712
        }
713
    }
714

    
715
    s->exponent_bits = bit_count;
716
}
717

    
718

    
719
/**
720
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
721
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
722
 * and encode final exponents.
723
 */
724
static void process_exponents(AC3EncodeContext *s)
725
{
726
    extract_exponents(s);
727

    
728
    compute_exp_strategy(s);
729

    
730
    encode_exponents(s);
731

    
732
    group_exponents(s);
733
}
734

    
735

    
736
/**
737
 * Initialize bit allocation.
738
 * Set default parameter codes and calculate parameter values.
739
 */
740
static void bit_alloc_init(AC3EncodeContext *s)
741
{
742
    int ch;
743

    
744
    /* init default parameters */
745
    s->slow_decay_code = 2;
746
    s->fast_decay_code = 1;
747
    s->slow_gain_code  = 1;
748
    s->db_per_bit_code = 2;
749
    s->floor_code      = 4;
750
    for (ch = 0; ch < s->channels; ch++)
751
        s->fast_gain_code[ch] = 4;
752

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

    
756
    /* compute real values */
757
    /* currently none of these values change during encoding, so we can just
758
       set them once at initialization */
759
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
760
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
761
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
762
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
763
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
764
}
765

    
766

    
767
/**
768
 * Count the bits used to encode the frame, minus exponents and mantissas.
769
 */
770
static void count_frame_bits(AC3EncodeContext *s)
771
{
772
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
773
    int blk, ch;
774
    int frame_bits;
775

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

    
780
    /* audio blocks */
781
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
782
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
783
        if (s->channel_mode == AC3_CHMODE_STEREO) {
784
            frame_bits++; /* rematstr */
785
            if (!blk)
786
                frame_bits += 4;
787
        }
788
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
789
        if (s->lfe_on)
790
            frame_bits++; /* lfeexpstr */
791
        for (ch = 0; ch < s->fbw_channels; ch++) {
792
            if (s->exp_strategy[blk][ch] != EXP_REUSE)
793
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
794
        }
795
        frame_bits++; /* baie */
796
        frame_bits++; /* snr */
797
        frame_bits += 2; /* delta / skip */
798
    }
799
    frame_bits++; /* cplinu for block 0 */
800
    /* bit alloc info */
801
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
802
    /* csnroffset[6] */
803
    /* (fsnoffset[4] + fgaincod[4]) * c */
804
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
805

    
806
    /* auxdatae, crcrsv */
807
    frame_bits += 2;
808

    
809
    /* CRC */
810
    frame_bits += 16;
811

    
812
    s->frame_bits = frame_bits;
813
}
814

    
815

    
816
/**
817
 * Calculate the number of bits needed to encode a set of mantissas.
818
 */
819
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
820
{
821
    int bits, mant, i;
822

    
823
    bits = 0;
824
    for (i = 0; i < nb_coefs; i++) {
825
        mant = m[i];
826
        switch (mant) {
827
        case 0:
828
            /* nothing */
829
            break;
830
        case 1:
831
            /* 3 mantissa in 5 bits */
832
            if (s->mant1_cnt == 0)
833
                bits += 5;
834
            if (++s->mant1_cnt == 3)
835
                s->mant1_cnt = 0;
836
            break;
837
        case 2:
838
            /* 3 mantissa in 7 bits */
839
            if (s->mant2_cnt == 0)
840
                bits += 7;
841
            if (++s->mant2_cnt == 3)
842
                s->mant2_cnt = 0;
843
            break;
844
        case 3:
845
            bits += 3;
846
            break;
847
        case 4:
848
            /* 2 mantissa in 7 bits */
849
            if (s->mant4_cnt == 0)
850
                bits += 7;
851
            if (++s->mant4_cnt == 2)
852
                s->mant4_cnt = 0;
853
            break;
854
        case 14:
855
            bits += 14;
856
            break;
857
        case 15:
858
            bits += 16;
859
            break;
860
        default:
861
            bits += mant - 1;
862
            break;
863
        }
864
    }
865
    return bits;
866
}
867

    
868

    
869
/**
870
 * Calculate masking curve based on the final exponents.
871
 * Also calculate the power spectral densities to use in future calculations.
872
 */
873
static void bit_alloc_masking(AC3EncodeContext *s)
874
{
875
    int blk, ch;
876

    
877
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
878
        for (ch = 0; ch < s->channels; ch++) {
879
            if (s->exp_strategy[blk][ch] == EXP_REUSE) {
880
                memcpy(s->psd[blk][ch],  s->psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(s->psd[0][0][0]));
881
                memcpy(s->mask[blk][ch], s->mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(s->mask[0][0][0]));
882
            } else {
883
                ff_ac3_bit_alloc_calc_psd(s->encoded_exp[blk][ch], 0,
884
                                          s->nb_coefs[ch],
885
                                          s->psd[blk][ch], s->band_psd[blk][ch]);
886
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, s->band_psd[blk][ch],
887
                                           0, s->nb_coefs[ch],
888
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
889
                                           ch == s->lfe_channel,
890
                                           DBA_NONE, 0, NULL, NULL, NULL,
891
                                           s->mask[blk][ch]);
892
            }
893
        }
894
    }
895
}
896

    
897

    
898
/**
899
 * Run the bit allocation with a given SNR offset.
900
 * This calculates the bit allocation pointers that will be used to determine
901
 * the quantization of each mantissa.
902
 * @return the number of bits needed for mantissas if the given SNR offset is
903
 *         is used.
904
 */
905
static int bit_alloc(AC3EncodeContext *s,
906
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
907
                     int snr_offset)
908
{
909
    int blk, ch;
910
    int mantissa_bits;
911

    
912
    snr_offset = (snr_offset - 240) << 2;
913

    
914
    mantissa_bits = 0;
915
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
916
        s->mant1_cnt = 0;
917
        s->mant2_cnt = 0;
918
        s->mant4_cnt = 0;
919
        for (ch = 0; ch < s->channels; ch++) {
920
            ff_ac3_bit_alloc_calc_bap(s->mask[blk][ch], s->psd[blk][ch], 0,
921
                                      s->nb_coefs[ch], snr_offset,
922
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
923
                                      bap[blk][ch]);
924
            mantissa_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
925
        }
926
    }
927
    return mantissa_bits;
928
}
929

    
930

    
931
/**
932
 * Constant bitrate bit allocation search.
933
 * Find the largest SNR offset that will allow data to fit in the frame.
934
 */
935
static int cbr_bit_allocation(AC3EncodeContext *s)
936
{
937
    int ch;
938
    int bits_left;
939
    int snr_offset;
940

    
941
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
942

    
943
    snr_offset = s->coarse_snr_offset << 4;
944

    
945
    while (snr_offset >= 0 &&
946
           bit_alloc(s, s->bap, snr_offset) > bits_left) {
947
        snr_offset -= 64;
948
    }
949
    if (snr_offset < 0) {
950
        return AVERROR(EINVAL);
951
    }
952

    
953
    while (snr_offset + 64 <= 1023 &&
954
           bit_alloc(s, s->bap1, snr_offset + 64) <= bits_left) {
955
        snr_offset += 64;
956
        memcpy(s->bap, s->bap1, sizeof(s->bap1));
957
    }
958
    while (snr_offset + 16 <= 1023 &&
959
           bit_alloc(s, s->bap1, snr_offset + 16) <= bits_left) {
960
        snr_offset += 16;
961
        memcpy(s->bap, s->bap1, sizeof(s->bap1));
962
    }
963
    while (snr_offset + 4 <= 1023 &&
964
           bit_alloc(s, s->bap1, snr_offset + 4) <= bits_left) {
965
        snr_offset += 4;
966
        memcpy(s->bap, s->bap1, sizeof(s->bap1));
967
    }
968
    while (snr_offset + 1 <= 1023 &&
969
           bit_alloc(s, s->bap1, snr_offset + 1) <= bits_left) {
970
        snr_offset++;
971
        memcpy(s->bap, s->bap1, sizeof(s->bap1));
972
    }
973

    
974
    s->coarse_snr_offset = snr_offset >> 4;
975
    for (ch = 0; ch < s->channels; ch++)
976
        s->fine_snr_offset[ch] = snr_offset & 0xF;
977

    
978
    return 0;
979
}
980

    
981

    
982
/**
983
 * Perform bit allocation search.
984
 * Finds the SNR offset value that maximizes quality and fits in the specified
985
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
986
 * used to quantize the mantissas.
987
 */
988
static int compute_bit_allocation(AC3EncodeContext *s)
989
{
990
    /* count frame bits other than exponents and mantissas */
991
    count_frame_bits(s);
992

    
993
    /* calculate psd and masking curve before doing bit allocation */
994
    bit_alloc_masking(s);
995

    
996
    return cbr_bit_allocation(s);
997
}
998

    
999

    
1000
/**
1001
 * Symmetric quantization on 'levels' levels.
1002
 */
1003
static inline int sym_quant(int c, int e, int levels)
1004
{
1005
    int v;
1006

    
1007
    if (c >= 0) {
1008
        v = (levels * (c << e)) >> 24;
1009
        v = (v + 1) >> 1;
1010
        v = (levels >> 1) + v;
1011
    } else {
1012
        v = (levels * ((-c) << e)) >> 24;
1013
        v = (v + 1) >> 1;
1014
        v = (levels >> 1) - v;
1015
    }
1016
    assert (v >= 0 && v < levels);
1017
    return v;
1018
}
1019

    
1020

    
1021
/**
1022
 * Asymmetric quantization on 2^qbits levels.
1023
 */
1024
static inline int asym_quant(int c, int e, int qbits)
1025
{
1026
    int lshift, m, v;
1027

    
1028
    lshift = e + qbits - 24;
1029
    if (lshift >= 0)
1030
        v = c << lshift;
1031
    else
1032
        v = c >> (-lshift);
1033
    /* rounding */
1034
    v = (v + 1) >> 1;
1035
    m = (1 << (qbits-1));
1036
    if (v >= m)
1037
        v = m - 1;
1038
    assert(v >= -m);
1039
    return v & ((1 << qbits)-1);
1040
}
1041

    
1042

    
1043
/**
1044
 * Quantize a set of mantissas for a single channel in a single block.
1045
 */
1046
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1047
                                      int32_t *mdct_coef, int8_t exp_shift,
1048
                                      uint8_t *encoded_exp, uint8_t *bap,
1049
                                      uint16_t *qmant, int n)
1050
{
1051
    int i;
1052

    
1053
    for (i = 0; i < n; i++) {
1054
        int v;
1055
        int c = mdct_coef[i];
1056
        int e = encoded_exp[i] - exp_shift;
1057
        int b = bap[i];
1058
        switch (b) {
1059
        case 0:
1060
            v = 0;
1061
            break;
1062
        case 1:
1063
            v = sym_quant(c, e, 3);
1064
            switch (s->mant1_cnt) {
1065
            case 0:
1066
                s->qmant1_ptr = &qmant[i];
1067
                v = 9 * v;
1068
                s->mant1_cnt = 1;
1069
                break;
1070
            case 1:
1071
                *s->qmant1_ptr += 3 * v;
1072
                s->mant1_cnt = 2;
1073
                v = 128;
1074
                break;
1075
            default:
1076
                *s->qmant1_ptr += v;
1077
                s->mant1_cnt = 0;
1078
                v = 128;
1079
                break;
1080
            }
1081
            break;
1082
        case 2:
1083
            v = sym_quant(c, e, 5);
1084
            switch (s->mant2_cnt) {
1085
            case 0:
1086
                s->qmant2_ptr = &qmant[i];
1087
                v = 25 * v;
1088
                s->mant2_cnt = 1;
1089
                break;
1090
            case 1:
1091
                *s->qmant2_ptr += 5 * v;
1092
                s->mant2_cnt = 2;
1093
                v = 128;
1094
                break;
1095
            default:
1096
                *s->qmant2_ptr += v;
1097
                s->mant2_cnt = 0;
1098
                v = 128;
1099
                break;
1100
            }
1101
            break;
1102
        case 3:
1103
            v = sym_quant(c, e, 7);
1104
            break;
1105
        case 4:
1106
            v = sym_quant(c, e, 11);
1107
            switch (s->mant4_cnt) {
1108
            case 0:
1109
                s->qmant4_ptr = &qmant[i];
1110
                v = 11 * v;
1111
                s->mant4_cnt = 1;
1112
                break;
1113
            default:
1114
                *s->qmant4_ptr += v;
1115
                s->mant4_cnt = 0;
1116
                v = 128;
1117
                break;
1118
            }
1119
            break;
1120
        case 5:
1121
            v = sym_quant(c, e, 15);
1122
            break;
1123
        case 14:
1124
            v = asym_quant(c, e, 14);
1125
            break;
1126
        case 15:
1127
            v = asym_quant(c, e, 16);
1128
            break;
1129
        default:
1130
            v = asym_quant(c, e, b - 1);
1131
            break;
1132
        }
1133
        qmant[i] = v;
1134
    }
1135
}
1136

    
1137

    
1138
/**
1139
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1140
 */
1141
static void quantize_mantissas(AC3EncodeContext *s)
1142
{
1143
    int blk, ch;
1144

    
1145

    
1146
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1147
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1148
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1149

    
1150
        for (ch = 0; ch < s->channels; ch++) {
1151
            quantize_mantissas_blk_ch(s, s->mdct_coef[blk][ch], s->exp_shift[blk][ch],
1152
                                      s->encoded_exp[blk][ch], s->bap[blk][ch],
1153
                                      s->qmant[blk][ch], s->nb_coefs[ch]);
1154
        }
1155
    }
1156
}
1157

    
1158

    
1159
/**
1160
 * Write the AC-3 frame header to the output bitstream.
1161
 */
1162
static void output_frame_header(AC3EncodeContext *s)
1163
{
1164
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1165
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1166
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1167
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1168
    put_bits(&s->pb, 5,  s->bitstream_id);
1169
    put_bits(&s->pb, 3,  s->bitstream_mode);
1170
    put_bits(&s->pb, 3,  s->channel_mode);
1171
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1172
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1173
    if (s->channel_mode & 0x04)
1174
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1175
    if (s->channel_mode == AC3_CHMODE_STEREO)
1176
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1177
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1178
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1179
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1180
    put_bits(&s->pb, 1, 0);         /* no lang code */
1181
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1182
    put_bits(&s->pb, 1, 0);         /* no copyright */
1183
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1184
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1185
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1186
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1187
}
1188

    
1189

    
1190
/**
1191
 * Write one audio block to the output bitstream.
1192
 */
1193
static void output_audio_block(AC3EncodeContext *s,
1194
                               int block_num)
1195
{
1196
    int ch, i, baie, rbnd;
1197

    
1198
    for (ch = 0; ch < s->fbw_channels; ch++)
1199
        put_bits(&s->pb, 1, 0); /* no block switching */
1200
    for (ch = 0; ch < s->fbw_channels; ch++)
1201
        put_bits(&s->pb, 1, 1); /* no dither */
1202
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
1203
    if (!block_num) {
1204
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1205
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1206
    } else {
1207
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1208
    }
1209

    
1210
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1211
        if (!block_num) {
1212
            /* first block must define rematrixing (rematstr) */
1213
            put_bits(&s->pb, 1, 1);
1214

    
1215
            /* dummy rematrixing rematflg(1:4)=0 */
1216
            for (rbnd = 0; rbnd < 4; rbnd++)
1217
                put_bits(&s->pb, 1, 0);
1218
        } else {
1219
            /* no matrixing (but should be used in the future) */
1220
            put_bits(&s->pb, 1, 0);
1221
        }
1222
    }
1223

    
1224
    /* exponent strategy */
1225
    for (ch = 0; ch < s->fbw_channels; ch++)
1226
        put_bits(&s->pb, 2, s->exp_strategy[block_num][ch]);
1227

    
1228
    if (s->lfe_on)
1229
        put_bits(&s->pb, 1, s->exp_strategy[block_num][s->lfe_channel]);
1230

    
1231
    /* bandwidth */
1232
    for (ch = 0; ch < s->fbw_channels; ch++) {
1233
        if (s->exp_strategy[block_num][ch] != EXP_REUSE)
1234
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1235
    }
1236

    
1237
    /* exponents */
1238
    for (ch = 0; ch < s->channels; ch++) {
1239
        if (s->exp_strategy[block_num][ch] == EXP_REUSE)
1240
            continue;
1241

    
1242
        /* first exponent */
1243
        put_bits(&s->pb, 4, s->grouped_exp[block_num][ch][0]);
1244

    
1245
        /* next ones are delta-encoded and grouped */
1246
        for (i = 1; i <= s->num_exp_groups[block_num][ch]; i++)
1247
            put_bits(&s->pb, 7, s->grouped_exp[block_num][ch][i]);
1248

    
1249
        if (ch != s->lfe_channel)
1250
            put_bits(&s->pb, 2, 0); /* no gain range info */
1251
    }
1252

    
1253
    /* bit allocation info */
1254
    baie = (block_num == 0);
1255
    put_bits(&s->pb, 1, baie);
1256
    if (baie) {
1257
        put_bits(&s->pb, 2, s->slow_decay_code);
1258
        put_bits(&s->pb, 2, s->fast_decay_code);
1259
        put_bits(&s->pb, 2, s->slow_gain_code);
1260
        put_bits(&s->pb, 2, s->db_per_bit_code);
1261
        put_bits(&s->pb, 3, s->floor_code);
1262
    }
1263

    
1264
    /* snr offset */
1265
    put_bits(&s->pb, 1, baie);
1266
    if (baie) {
1267
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1268
        for (ch = 0; ch < s->channels; ch++) {
1269
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1270
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1271
        }
1272
    }
1273

    
1274
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1275
    put_bits(&s->pb, 1, 0); /* no data to skip */
1276

    
1277
    /* mantissa encoding */
1278
    for (ch = 0; ch < s->channels; ch++) {
1279
        int b, q;
1280

    
1281
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1282
            q = s->qmant[block_num][ch][i];
1283
            b = s->bap[block_num][ch][i];
1284
            switch (b) {
1285
            case 0:                                         break;
1286
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1287
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1288
            case 3:               put_bits(&s->pb,   3, q); break;
1289
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1290
            case 14:              put_bits(&s->pb,  14, q); break;
1291
            case 15:              put_bits(&s->pb,  16, q); break;
1292
            default:              put_bits(&s->pb, b-1, q); break;
1293
            }
1294
        }
1295
    }
1296
}
1297

    
1298

    
1299
/** CRC-16 Polynomial */
1300
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1301

    
1302

    
1303
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1304
{
1305
    unsigned int c;
1306

    
1307
    c = 0;
1308
    while (a) {
1309
        if (a & 1)
1310
            c ^= b;
1311
        a = a >> 1;
1312
        b = b << 1;
1313
        if (b & (1 << 16))
1314
            b ^= poly;
1315
    }
1316
    return c;
1317
}
1318

    
1319

    
1320
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1321
{
1322
    unsigned int r;
1323
    r = 1;
1324
    while (n) {
1325
        if (n & 1)
1326
            r = mul_poly(r, a, poly);
1327
        a = mul_poly(a, a, poly);
1328
        n >>= 1;
1329
    }
1330
    return r;
1331
}
1332

    
1333

    
1334
/**
1335
 * Fill the end of the frame with 0's and compute the two CRCs.
1336
 */
1337
static void output_frame_end(AC3EncodeContext *s)
1338
{
1339
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1340
    uint8_t *frame;
1341

    
1342
    frame_size = s->frame_size; /* frame size in words */
1343
    /* align to 8 bits */
1344
    flush_put_bits(&s->pb);
1345
    /* add zero bytes to reach the frame size */
1346
    frame = s->pb.buf;
1347
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1348
    assert(pad_bytes >= 0);
1349
    if (pad_bytes > 0)
1350
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1351

    
1352
    /* Now we must compute both crcs : this is not so easy for crc1
1353
       because it is at the beginning of the data... */
1354
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1355

    
1356
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1357
                             frame + 4, frame_size_58 - 4));
1358

    
1359
    /* XXX: could precompute crc_inv */
1360
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1361
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1362
    AV_WB16(frame + 2, crc1);
1363

    
1364
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1365
                             frame + frame_size_58,
1366
                             frame_size - frame_size_58 - 2));
1367
    AV_WB16(frame + frame_size - 2, crc2);
1368
}
1369

    
1370

    
1371
/**
1372
 * Write the frame to the output bitstream.
1373
 */
1374
static void output_frame(AC3EncodeContext *s,
1375
                         unsigned char *frame)
1376
{
1377
    int blk;
1378

    
1379
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1380

    
1381
    output_frame_header(s);
1382

    
1383
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1384
        output_audio_block(s, blk);
1385
    }
1386

    
1387
    output_frame_end(s);
1388
}
1389

    
1390

    
1391
/**
1392
 * Encode a single AC-3 frame.
1393
 */
1394
static int ac3_encode_frame(AVCodecContext *avctx,
1395
                            unsigned char *frame, int buf_size, void *data)
1396
{
1397
    AC3EncodeContext *s = avctx->priv_data;
1398
    const int16_t *samples = data;
1399
    int ret;
1400

    
1401
    if (s->bit_alloc.sr_code == 1)
1402
        adjust_frame_size(s);
1403

    
1404
    deinterleave_input_samples(s, samples);
1405

    
1406
    apply_mdct(s);
1407

    
1408
    process_exponents(s);
1409

    
1410
    ret = compute_bit_allocation(s);
1411
    if (ret) {
1412
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1413
        return ret;
1414
    }
1415

    
1416
    quantize_mantissas(s);
1417

    
1418
    output_frame(s, frame);
1419

    
1420
    return s->frame_size;
1421
}
1422

    
1423

    
1424
/**
1425
 * Finalize encoding and free any memory allocated by the encoder.
1426
 */
1427
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1428
{
1429
    av_freep(&avctx->coded_frame);
1430
    return 0;
1431
}
1432

    
1433

    
1434
/**
1435
 * Set channel information during initialization.
1436
 */
1437
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1438
                                    int64_t *channel_layout)
1439
{
1440
    int ch_layout;
1441

    
1442
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1443
        return AVERROR(EINVAL);
1444
    if ((uint64_t)*channel_layout > 0x7FF)
1445
        return AVERROR(EINVAL);
1446
    ch_layout = *channel_layout;
1447
    if (!ch_layout)
1448
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1449
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1450
        return AVERROR(EINVAL);
1451

    
1452
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1453
    s->channels     = channels;
1454
    s->fbw_channels = channels - s->lfe_on;
1455
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1456
    if (s->lfe_on)
1457
        ch_layout -= AV_CH_LOW_FREQUENCY;
1458

    
1459
    switch (ch_layout) {
1460
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1461
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1462
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1463
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1464
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1465
    case AV_CH_LAYOUT_QUAD:
1466
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1467
    case AV_CH_LAYOUT_5POINT0:
1468
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1469
    default:
1470
        return AVERROR(EINVAL);
1471
    }
1472

    
1473
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1474
    *channel_layout = ch_layout;
1475
    if (s->lfe_on)
1476
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1477

    
1478
    return 0;
1479
}
1480

    
1481

    
1482
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1483
{
1484
    int i, ret;
1485

    
1486
    /* validate channel layout */
1487
    if (!avctx->channel_layout) {
1488
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1489
                                      "encoder will guess the layout, but it "
1490
                                      "might be incorrect.\n");
1491
    }
1492
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1493
    if (ret) {
1494
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1495
        return ret;
1496
    }
1497

    
1498
    /* validate sample rate */
1499
    for (i = 0; i < 9; i++) {
1500
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1501
            break;
1502
    }
1503
    if (i == 9) {
1504
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1505
        return AVERROR(EINVAL);
1506
    }
1507
    s->sample_rate        = avctx->sample_rate;
1508
    s->bit_alloc.sr_shift = i % 3;
1509
    s->bit_alloc.sr_code  = i / 3;
1510

    
1511
    /* validate bit rate */
1512
    for (i = 0; i < 19; i++) {
1513
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1514
            break;
1515
    }
1516
    if (i == 19) {
1517
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1518
        return AVERROR(EINVAL);
1519
    }
1520
    s->bit_rate        = avctx->bit_rate;
1521
    s->frame_size_code = i << 1;
1522

    
1523
    return 0;
1524
}
1525

    
1526

    
1527
/**
1528
 * Set bandwidth for all channels.
1529
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1530
 * default value will be used.
1531
 */
1532
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1533
{
1534
    int ch, bw_code;
1535

    
1536
    if (cutoff) {
1537
        /* calculate bandwidth based on user-specified cutoff frequency */
1538
        int fbw_coeffs;
1539
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1540
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1541
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1542
    } else {
1543
        /* use default bandwidth setting */
1544
        /* XXX: should compute the bandwidth according to the frame
1545
           size, so that we avoid annoying high frequency artifacts */
1546
        bw_code = 50;
1547
    }
1548

    
1549
    /* set number of coefficients for each channel */
1550
    for (ch = 0; ch < s->fbw_channels; ch++) {
1551
        s->bandwidth_code[ch] = bw_code;
1552
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1553
    }
1554
    if (s->lfe_on)
1555
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1556
}
1557

    
1558

    
1559
/**
1560
 * Initialize the encoder.
1561
 */
1562
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1563
{
1564
    AC3EncodeContext *s = avctx->priv_data;
1565
    int ret;
1566

    
1567
    avctx->frame_size = AC3_FRAME_SIZE;
1568

    
1569
    ac3_common_init();
1570

    
1571
    ret = validate_options(avctx, s);
1572
    if (ret)
1573
        return ret;
1574

    
1575
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1576
    s->bitstream_mode = 0; /* complete main audio service */
1577

    
1578
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1579
    s->bits_written    = 0;
1580
    s->samples_written = 0;
1581
    s->frame_size      = s->frame_size_min;
1582

    
1583
    set_bandwidth(s, avctx->cutoff);
1584

    
1585
    bit_alloc_init(s);
1586

    
1587
    mdct_init(9);
1588

    
1589
    avctx->coded_frame= avcodec_alloc_frame();
1590
    avctx->coded_frame->key_frame= 1;
1591

    
1592
    return 0;
1593
}
1594

    
1595

    
1596
#ifdef TEST
1597
/*************************************************************************/
1598
/* TEST */
1599

    
1600
#include "libavutil/lfg.h"
1601

    
1602
#define FN (MDCT_SAMPLES/4)
1603

    
1604

    
1605
static void fft_test(AVLFG *lfg)
1606
{
1607
    IComplex in[FN], in1[FN];
1608
    int k, n, i;
1609
    float sum_re, sum_im, a;
1610

    
1611
    for (i = 0; i < FN; i++) {
1612
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1613
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1614
        in1[i]   = in[i];
1615
    }
1616
    fft(in, 7);
1617

    
1618
    /* do it by hand */
1619
    for (k = 0; k < FN; k++) {
1620
        sum_re = 0;
1621
        sum_im = 0;
1622
        for (n = 0; n < FN; n++) {
1623
            a = -2 * M_PI * (n * k) / FN;
1624
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1625
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1626
        }
1627
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1628
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1629
    }
1630
}
1631

    
1632

    
1633
static void mdct_test(AVLFG *lfg)
1634
{
1635
    int16_t input[MDCT_SAMPLES];
1636
    int32_t output[AC3_MAX_COEFS];
1637
    float input1[MDCT_SAMPLES];
1638
    float output1[AC3_MAX_COEFS];
1639
    float s, a, err, e, emax;
1640
    int i, k, n;
1641

    
1642
    for (i = 0; i < MDCT_SAMPLES; i++) {
1643
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1644
        input1[i] = input[i];
1645
    }
1646

    
1647
    mdct512(output, input);
1648

    
1649
    /* do it by hand */
1650
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1651
        s = 0;
1652
        for (n = 0; n < MDCT_SAMPLES; n++) {
1653
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1654
            s += input1[n] * cos(a);
1655
        }
1656
        output1[k] = -2 * s / MDCT_SAMPLES;
1657
    }
1658

    
1659
    err  = 0;
1660
    emax = 0;
1661
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1662
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1663
        e = output[i] - output1[i];
1664
        if (e > emax)
1665
            emax = e;
1666
        err += e * e;
1667
    }
1668
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1669
}
1670

    
1671

    
1672
int main(void)
1673
{
1674
    AVLFG lfg;
1675

    
1676
    av_log_set_level(AV_LOG_DEBUG);
1677
    mdct_init(9);
1678

    
1679
    fft_test(&lfg);
1680
    mdct_test(&lfg);
1681

    
1682
    return 0;
1683
}
1684
#endif /* TEST */
1685

    
1686

    
1687
AVCodec ac3_encoder = {
1688
    "ac3",
1689
    AVMEDIA_TYPE_AUDIO,
1690
    CODEC_ID_AC3,
1691
    sizeof(AC3EncodeContext),
1692
    ac3_encode_init,
1693
    ac3_encode_frame,
1694
    ac3_encode_close,
1695
    NULL,
1696
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1697
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1698
    .channel_layouts = (const int64_t[]){
1699
        AV_CH_LAYOUT_MONO,
1700
        AV_CH_LAYOUT_STEREO,
1701
        AV_CH_LAYOUT_2_1,
1702
        AV_CH_LAYOUT_SURROUND,
1703
        AV_CH_LAYOUT_2_2,
1704
        AV_CH_LAYOUT_QUAD,
1705
        AV_CH_LAYOUT_4POINT0,
1706
        AV_CH_LAYOUT_5POINT0,
1707
        AV_CH_LAYOUT_5POINT0_BACK,
1708
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1709
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1710
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1711
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1712
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1713
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1714
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1715
        AV_CH_LAYOUT_5POINT1,
1716
        AV_CH_LAYOUT_5POINT1_BACK,
1717
        0 },
1718
};