Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ e35c984a

History | View | Annotate | Download (46 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
/** Scale a float value by 2^bits and convert to an integer. */
41
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
42

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

    
46

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

    
55
/**
56
 * AC-3 encoder private context.
57
 */
58
typedef struct AC3EncodeContext {
59
    PutBitContext pb;                       ///< bitstream writer context
60

    
61
    int bitstream_id;                       ///< bitstream id                           (bsid)
62
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
63

    
64
    int bit_rate;                           ///< target bit rate, in bits-per-second
65
    int sample_rate;                        ///< sampling frequency, in Hz
66

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

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

    
80
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
81
    int nb_coefs[AC3_MAX_CHANNELS];
82

    
83
    /* bitrate allocation control */
84
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
85
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
86
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
87
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
88
    int floor_code;                         ///< floor code                             (floorcod)
89
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
90
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
91
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
92
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
93

    
94
    /* mantissa encoding */
95
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
96

    
97
    int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
98
} AC3EncodeContext;
99

    
100

    
101
/** MDCT and FFT tables */
102
static int16_t costab[64];
103
static int16_t sintab[64];
104
static int16_t xcos1[128];
105
static int16_t xsin1[128];
106

    
107

    
108
/**
109
 * Initialize FFT tables.
110
 * @param ln log2(FFT size)
111
 */
112
static av_cold void fft_init(int ln)
113
{
114
    int i, n, n2;
115
    float alpha;
116

    
117
    n  = 1 << ln;
118
    n2 = n >> 1;
119

    
120
    for (i = 0; i < n2; i++) {
121
        alpha     = 2.0 * M_PI * i / n;
122
        costab[i] = FIX15(cos(alpha));
123
        sintab[i] = FIX15(sin(alpha));
124
    }
125
}
126

    
127

    
128
/**
129
 * Initialize MDCT tables.
130
 * @param nbits log2(MDCT size)
131
 */
132
static av_cold void mdct_init(int nbits)
133
{
134
    int i, n, n4;
135

    
136
    n  = 1 << nbits;
137
    n4 = n >> 2;
138

    
139
    fft_init(nbits - 2);
140

    
141
    for (i = 0; i < n4; i++) {
142
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
143
        xcos1[i] = FIX15(-cos(alpha));
144
        xsin1[i] = FIX15(-sin(alpha));
145
    }
146
}
147

    
148

    
149
/** Butterfly op */
150
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
151
{                                                       \
152
  int ax, ay, bx, by;                                   \
153
  bx  = pre1;                                           \
154
  by  = pim1;                                           \
155
  ax  = qre1;                                           \
156
  ay  = qim1;                                           \
157
  pre = (bx + ax) >> 1;                                 \
158
  pim = (by + ay) >> 1;                                 \
159
  qre = (bx - ax) >> 1;                                 \
160
  qim = (by - ay) >> 1;                                 \
161
}
162

    
163

    
164
/** Complex multiply */
165
#define CMUL(pre, pim, are, aim, bre, bim)              \
166
{                                                       \
167
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
168
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
169
}
170

    
171

    
172
/**
173
 * Calculate a 2^n point complex FFT on 2^ln points.
174
 * @param z  complex input/output samples
175
 * @param ln log2(FFT size)
176
 */
177
static void fft(IComplex *z, int ln)
178
{
179
    int j, l, np, np2;
180
    int nblocks, nloops;
181
    register IComplex *p,*q;
182
    int tmp_re, tmp_im;
183

    
184
    np = 1 << ln;
185

    
186
    /* reverse */
187
    for (j = 0; j < np; j++) {
188
        int k = av_reverse[j] >> (8 - ln);
189
        if (k < j)
190
            FFSWAP(IComplex, z[k], z[j]);
191
    }
192

    
193
    /* pass 0 */
194

    
195
    p = &z[0];
196
    j = np >> 1;
197
    do {
198
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
199
           p[0].re, p[0].im, p[1].re, p[1].im);
200
        p += 2;
201
    } while (--j);
202

    
203
    /* pass 1 */
204

    
205
    p = &z[0];
206
    j = np >> 2;
207
    do {
208
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
209
           p[0].re, p[0].im, p[2].re,  p[2].im);
210
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
211
           p[1].re, p[1].im, p[3].im, -p[3].re);
212
        p+=4;
213
    } while (--j);
214

    
215
    /* pass 2 .. ln-1 */
216

    
217
    nblocks = np >> 3;
218
    nloops  =  1 << 2;
219
    np2     = np >> 1;
220
    do {
221
        p = z;
222
        q = z + nloops;
223
        for (j = 0; j < nblocks; j++) {
224
            BF(p->re, p->im, q->re, q->im,
225
               p->re, p->im, q->re, q->im);
226
            p++;
227
            q++;
228
            for(l = nblocks; l < np2; l += nblocks) {
229
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
230
                BF(p->re, p->im, q->re,  q->im,
231
                   p->re, p->im, tmp_re, tmp_im);
232
                p++;
233
                q++;
234
            }
235
            p += nloops;
236
            q += nloops;
237
        }
238
        nblocks = nblocks >> 1;
239
        nloops  = nloops  << 1;
240
    } while (nblocks);
241
}
242

    
243

    
244
/**
245
 * Calculate a 512-point MDCT
246
 * @param out 256 output frequency coefficients
247
 * @param in  512 windowed input audio samples
248
 */
249
static void mdct512(int32_t *out, int16_t *in)
250
{
251
    int i, re, im, re1, im1;
252
    int16_t rot[MDCT_SAMPLES];
253
    IComplex x[MDCT_SAMPLES/4];
254

    
255
    /* shift to simplify computations */
256
    for (i = 0; i < MDCT_SAMPLES/4; i++)
257
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
258
    for (;i < MDCT_SAMPLES; i++)
259
        rot[i] =  in[i -   MDCT_SAMPLES/4];
260

    
261
    /* pre rotation */
262
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
263
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
264
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
265
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
266
    }
267

    
268
    fft(x, MDCT_NBITS - 2);
269

    
270
    /* post rotation */
271
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
272
        re = x[i].re;
273
        im = x[i].im;
274
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
275
        out[                 2*i] = im1;
276
        out[MDCT_SAMPLES/2-1-2*i] = re1;
277
    }
278
}
279

    
280

    
281
/**
282
 * Calculate the log2() of the maximum absolute value in an array.
283
 * @param tab input array
284
 * @param n   number of values in the array
285
 * @return    log2(max(abs(tab[])))
286
 */
287
static int log2_tab(int16_t *tab, int n)
288
{
289
    int i, v;
290

    
291
    v = 0;
292
    for (i = 0; i < n; i++)
293
        v |= abs(tab[i]);
294

    
295
    return av_log2(v);
296
}
297

    
298

    
299
/**
300
 * Left-shift each value in an array by a specified amount.
301
 * @param tab    input array
302
 * @param n      number of values in the array
303
 * @param lshift left shift amount. a negative value means right shift.
304
 */
305
static void lshift_tab(int16_t *tab, int n, int lshift)
306
{
307
    int i;
308

    
309
    if (lshift > 0) {
310
        for(i = 0; i < n; i++)
311
            tab[i] <<= lshift;
312
    } else if (lshift < 0) {
313
        lshift = -lshift;
314
        for (i = 0; i < n; i++)
315
            tab[i] >>= lshift;
316
    }
317
}
318

    
319

    
320
/**
321
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
322
 */
323
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
324
{
325
    int sum, i;
326
    sum = 0;
327
    for (i = 0; i < n; i++)
328
        sum += abs(exp1[i] - exp2[i]);
329
    return sum;
330
}
331

    
332

    
333
/**
334
 * Exponent Difference Threshold.
335
 * New exponents are sent if their SAD exceed this number.
336
 */
337
#define EXP_DIFF_THRESHOLD 1000
338

    
339

    
340
/**
341
 * Calculate exponent strategies for all blocks in a single channel.
342
 */
343
static void compute_exp_strategy_ch(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
344
                                    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
345
                                    int ch, int is_lfe)
346
{
347
    int blk, blk1;
348
    int exp_diff;
349

    
350
    /* estimate if the exponent variation & decide if they should be
351
       reused in the next frame */
352
    exp_strategy[0][ch] = EXP_NEW;
353
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
354
        exp_diff = calc_exp_diff(exp[blk][ch], exp[blk-1][ch], AC3_MAX_COEFS);
355
        if (exp_diff > EXP_DIFF_THRESHOLD)
356
            exp_strategy[blk][ch] = EXP_NEW;
357
        else
358
            exp_strategy[blk][ch] = EXP_REUSE;
359
    }
360
    if (is_lfe)
361
        return;
362

    
363
    /* now select the encoding strategy type : if exponents are often
364
       recoded, we use a coarse encoding */
365
    blk = 0;
366
    while (blk < AC3_MAX_BLOCKS) {
367
        blk1 = blk + 1;
368
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE)
369
            blk1++;
370
        switch (blk1 - blk) {
371
        case 1:  exp_strategy[blk][ch] = EXP_D45; break;
372
        case 2:
373
        case 3:  exp_strategy[blk][ch] = EXP_D25; break;
374
        default: exp_strategy[blk][ch] = EXP_D15; break;
375
        }
376
        blk = blk1;
377
    }
378
}
379

    
380

    
381
/**
382
 * Set each encoded exponent in a block to the minimum of itself and the
383
 * exponent in the same frequency bin of a following block.
384
 * exp[i] = min(exp[i], exp1[i]
385
 */
386
static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
387
{
388
    int i;
389
    for (i = 0; i < n; i++) {
390
        if (exp1[i] < exp[i])
391
            exp[i] = exp1[i];
392
    }
393
}
394

    
395

    
396
/**
397
 * Update the exponents so that they are the ones the decoder will decode.
398
 * @return the number of bits used to encode the exponents.
399
 */
400
static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
401
                                   uint8_t exp[AC3_MAX_COEFS],
402
                                   int nb_exps, int exp_strategy)
403
{
404
    int group_size, nb_groups, i, j, k, exp_min;
405
    uint8_t exp1[AC3_MAX_COEFS];
406

    
407
    group_size = exp_strategy + (exp_strategy == EXP_D45);
408
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
409

    
410
    /* for each group, compute the minimum exponent */
411
    exp1[0] = exp[0]; /* DC exponent is handled separately */
412
    k = 1;
413
    for (i = 1; i <= nb_groups; i++) {
414
        exp_min = exp[k];
415
        assert(exp_min >= 0 && exp_min <= 24);
416
        for (j = 1; j < group_size; j++) {
417
            if (exp[k+j] < exp_min)
418
                exp_min = exp[k+j];
419
        }
420
        exp1[i] = exp_min;
421
        k += group_size;
422
    }
423

    
424
    /* constraint for DC exponent */
425
    if (exp1[0] > 15)
426
        exp1[0] = 15;
427

    
428
    /* decrease the delta between each groups to within 2 so that they can be
429
       differentially encoded */
430
    for (i = 1; i <= nb_groups; i++)
431
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
432
    for (i = nb_groups-1; i >= 0; i--)
433
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
434

    
435
    /* now we have the exponent values the decoder will see */
436
    encoded_exp[0] = exp1[0];
437
    k = 1;
438
    for (i = 1; i <= nb_groups; i++) {
439
        for (j = 0; j < group_size; j++)
440
            encoded_exp[k+j] = exp1[i];
441
        k += group_size;
442
    }
443

    
444
    return 4 + (nb_groups / 3) * 7;
445
}
446

    
447

    
448
/**
449
 * Calculate the number of bits needed to encode a set of mantissas.
450
 */
451
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
452
{
453
    int bits, mant, i;
454

    
455
    bits = 0;
456
    for (i = 0; i < nb_coefs; i++) {
457
        mant = m[i];
458
        switch (mant) {
459
        case 0:
460
            /* nothing */
461
            break;
462
        case 1:
463
            /* 3 mantissa in 5 bits */
464
            if (s->mant1_cnt == 0)
465
                bits += 5;
466
            if (++s->mant1_cnt == 3)
467
                s->mant1_cnt = 0;
468
            break;
469
        case 2:
470
            /* 3 mantissa in 7 bits */
471
            if (s->mant2_cnt == 0)
472
                bits += 7;
473
            if (++s->mant2_cnt == 3)
474
                s->mant2_cnt = 0;
475
            break;
476
        case 3:
477
            bits += 3;
478
            break;
479
        case 4:
480
            /* 2 mantissa in 7 bits */
481
            if (s->mant4_cnt == 0)
482
                bits += 7;
483
            if (++s->mant4_cnt == 2)
484
                s->mant4_cnt = 0;
485
            break;
486
        case 14:
487
            bits += 14;
488
            break;
489
        case 15:
490
            bits += 16;
491
            break;
492
        default:
493
            bits += mant - 1;
494
            break;
495
        }
496
    }
497
    return bits;
498
}
499

    
500

    
501
/**
502
 * Calculate masking curve based on the final exponents.
503
 * Also calculate the power spectral densities to use in future calculations.
504
 */
505
static void bit_alloc_masking(AC3EncodeContext *s,
506
                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
507
                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
508
                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
509
                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
510
{
511
    int blk, ch;
512
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
513

    
514
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
515
        for (ch = 0; ch < s->channels; ch++) {
516
            if(exp_strategy[blk][ch] == EXP_REUSE) {
517
                memcpy(psd[blk][ch],  psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(psd[0][0][0]));
518
                memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
519
            } else {
520
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
521
                                          s->nb_coefs[ch],
522
                                          psd[blk][ch], band_psd[blk][ch]);
523
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
524
                                           0, s->nb_coefs[ch],
525
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
526
                                           ch == s->lfe_channel,
527
                                           DBA_NONE, 0, NULL, NULL, NULL,
528
                                           mask[blk][ch]);
529
            }
530
        }
531
    }
532
}
533

    
534

    
535
/**
536
 * Run the bit allocation with a given SNR offset.
537
 * This calculates the bit allocation pointers that will be used to determine
538
 * the quantization of each mantissa.
539
 * @return the number of remaining bits (positive or negative) if the given
540
 *         SNR offset is used to quantize the mantissas.
541
 */
542
static int bit_alloc(AC3EncodeContext *s,
543
                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
544
                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
545
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
546
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
547
{
548
    int blk, ch;
549
    int snr_offset;
550

    
551
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
552

    
553
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
554
        s->mant1_cnt = 0;
555
        s->mant2_cnt = 0;
556
        s->mant4_cnt = 0;
557
        for (ch = 0; ch < s->channels; ch++) {
558
            ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
559
                                      s->nb_coefs[ch], snr_offset,
560
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
561
                                      bap[blk][ch]);
562
            frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
563
        }
564
    }
565
    return 8 * s->frame_size - frame_bits;
566
}
567

    
568

    
569
#define SNR_INC1 4
570

    
571
/**
572
 * Perform bit allocation search.
573
 * Finds the SNR offset value that maximizes quality and fits in the specified
574
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
575
 * used to quantize the mantissas.
576
 */
577
static int compute_bit_allocation(AC3EncodeContext *s,
578
                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
579
                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
580
                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
581
                                  int frame_bits)
582
{
583
    int blk, ch;
584
    int coarse_snr_offset, fine_snr_offset;
585
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
586
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
587
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
588
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
589

    
590
    /* init default parameters */
591
    s->slow_decay_code = 2;
592
    s->fast_decay_code = 1;
593
    s->slow_gain_code  = 1;
594
    s->db_per_bit_code = 2;
595
    s->floor_code      = 4;
596
    for (ch = 0; ch < s->channels; ch++)
597
        s->fast_gain_code[ch] = 4;
598

    
599
    /* compute real values */
600
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
601
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
602
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
603
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
604
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
605

    
606
    /* header size */
607
    frame_bits += 65;
608
    // if (s->channel_mode == 2)
609
    //    frame_bits += 2;
610
    frame_bits += frame_bits_inc[s->channel_mode];
611

    
612
    /* audio blocks */
613
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
614
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
615
        if (s->channel_mode == AC3_CHMODE_STEREO) {
616
            frame_bits++; /* rematstr */
617
            if (!blk)
618
                frame_bits += 4;
619
        }
620
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
621
        if (s->lfe_on)
622
            frame_bits++; /* lfeexpstr */
623
        for (ch = 0; ch < s->fbw_channels; ch++) {
624
            if (exp_strategy[blk][ch] != EXP_REUSE)
625
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
626
        }
627
        frame_bits++; /* baie */
628
        frame_bits++; /* snr */
629
        frame_bits += 2; /* delta / skip */
630
    }
631
    frame_bits++; /* cplinu for block 0 */
632
    /* bit alloc info */
633
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
634
    /* csnroffset[6] */
635
    /* (fsnoffset[4] + fgaincod[4]) * c */
636
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
637

    
638
    /* auxdatae, crcrsv */
639
    frame_bits += 2;
640

    
641
    /* CRC */
642
    frame_bits += 16;
643

    
644
    /* calculate psd and masking curve before doing bit allocation */
645
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
646

    
647
    /* now the big work begins : do the bit allocation. Modify the snr
648
       offset until we can pack everything in the requested frame size */
649

    
650
    coarse_snr_offset = s->coarse_snr_offset;
651
    while (coarse_snr_offset >= 0 &&
652
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
653
        coarse_snr_offset -= SNR_INC1;
654
    if (coarse_snr_offset < 0) {
655
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
656
        return -1;
657
    }
658
    while (coarse_snr_offset + SNR_INC1 <= 63 &&
659
           bit_alloc(s, mask, psd, bap1, frame_bits,
660
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
661
        coarse_snr_offset += SNR_INC1;
662
        memcpy(bap, bap1, sizeof(bap1));
663
    }
664
    while (coarse_snr_offset + 1 <= 63 &&
665
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
666
        coarse_snr_offset++;
667
        memcpy(bap, bap1, sizeof(bap1));
668
    }
669

    
670
    fine_snr_offset = 0;
671
    while (fine_snr_offset + SNR_INC1 <= 15 &&
672
           bit_alloc(s, mask, psd, bap1, frame_bits,
673
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
674
        fine_snr_offset += SNR_INC1;
675
        memcpy(bap, bap1, sizeof(bap1));
676
    }
677
    while (fine_snr_offset + 1 <= 15 &&
678
           bit_alloc(s, mask, psd, bap1, frame_bits,
679
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
680
        fine_snr_offset++;
681
        memcpy(bap, bap1, sizeof(bap1));
682
    }
683

    
684
    s->coarse_snr_offset = coarse_snr_offset;
685
    for (ch = 0; ch < s->channels; ch++)
686
        s->fine_snr_offset[ch] = fine_snr_offset;
687

    
688
    return 0;
689
}
690

    
691

    
692
/**
693
 * Write the AC-3 frame header to the output bitstream.
694
 */
695
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
696
{
697
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
698

    
699
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
700
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
701
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
702
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
703
    put_bits(&s->pb, 5,  s->bitstream_id);
704
    put_bits(&s->pb, 3,  s->bitstream_mode);
705
    put_bits(&s->pb, 3,  s->channel_mode);
706
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
707
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
708
    if (s->channel_mode & 0x04)
709
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
710
    if (s->channel_mode == AC3_CHMODE_STEREO)
711
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
712
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
713
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
714
    put_bits(&s->pb, 1, 0);         /* no compression control word */
715
    put_bits(&s->pb, 1, 0);         /* no lang code */
716
    put_bits(&s->pb, 1, 0);         /* no audio production info */
717
    put_bits(&s->pb, 1, 0);         /* no copyright */
718
    put_bits(&s->pb, 1, 1);         /* original bitstream */
719
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
720
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
721
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
722
}
723

    
724

    
725
/**
726
 * Symmetric quantization on 'levels' levels.
727
 */
728
static inline int sym_quant(int c, int e, int levels)
729
{
730
    int v;
731

    
732
    if (c >= 0) {
733
        v = (levels * (c << e)) >> 24;
734
        v = (v + 1) >> 1;
735
        v = (levels >> 1) + v;
736
    } else {
737
        v = (levels * ((-c) << e)) >> 24;
738
        v = (v + 1) >> 1;
739
        v = (levels >> 1) - v;
740
    }
741
    assert (v >= 0 && v < levels);
742
    return v;
743
}
744

    
745

    
746
/**
747
 * Asymmetric quantization on 2^qbits levels.
748
 */
749
static inline int asym_quant(int c, int e, int qbits)
750
{
751
    int lshift, m, v;
752

    
753
    lshift = e + qbits - 24;
754
    if (lshift >= 0)
755
        v = c << lshift;
756
    else
757
        v = c >> (-lshift);
758
    /* rounding */
759
    v = (v + 1) >> 1;
760
    m = (1 << (qbits-1));
761
    if (v >= m)
762
        v = m - 1;
763
    assert(v >= -m);
764
    return v & ((1 << qbits)-1);
765
}
766

    
767

    
768
/**
769
 * Write one audio block to the output bitstream.
770
 */
771
static void output_audio_block(AC3EncodeContext *s,
772
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
773
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
774
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
775
                               int32_t mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
776
                               int8_t exp_shift[AC3_MAX_CHANNELS],
777
                               int block_num)
778
{
779
    int ch, nb_groups, group_size, i, baie, rbnd;
780
    uint8_t *p;
781
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
782
    int exp0, exp1;
783
    int mant1_cnt, mant2_cnt, mant4_cnt;
784
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
785
    int delta0, delta1, delta2;
786

    
787
    for (ch = 0; ch < s->fbw_channels; ch++)
788
        put_bits(&s->pb, 1, 0); /* no block switching */
789
    for (ch = 0; ch < s->fbw_channels; ch++)
790
        put_bits(&s->pb, 1, 1); /* no dither */
791
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
792
    if (!block_num) {
793
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
794
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
795
    } else {
796
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
797
    }
798

    
799
    if (s->channel_mode == AC3_CHMODE_STEREO) {
800
        if (!block_num) {
801
            /* first block must define rematrixing (rematstr) */
802
            put_bits(&s->pb, 1, 1);
803

    
804
            /* dummy rematrixing rematflg(1:4)=0 */
805
            for (rbnd = 0; rbnd < 4; rbnd++)
806
                put_bits(&s->pb, 1, 0);
807
        } else {
808
            /* no matrixing (but should be used in the future) */
809
            put_bits(&s->pb, 1, 0);
810
        }
811
    }
812

    
813
    /* exponent strategy */
814
    for (ch = 0; ch < s->fbw_channels; ch++)
815
        put_bits(&s->pb, 2, exp_strategy[ch]);
816

    
817
    if (s->lfe_on)
818
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
819

    
820
    /* bandwidth */
821
    for (ch = 0; ch < s->fbw_channels; ch++) {
822
        if (exp_strategy[ch] != EXP_REUSE)
823
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
824
    }
825

    
826
    /* exponents */
827
    for (ch = 0; ch < s->channels; ch++) {
828
        if (exp_strategy[ch] == EXP_REUSE)
829
            continue;
830
        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
831
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
832
        p = encoded_exp[ch];
833

    
834
        /* first exponent */
835
        exp1 = *p++;
836
        put_bits(&s->pb, 4, exp1);
837

    
838
        /* next ones are delta encoded */
839
        for (i = 0; i < nb_groups; i++) {
840
            /* merge three delta in one code */
841
            exp0   = exp1;
842
            exp1   = p[0];
843
            p     += group_size;
844
            delta0 = exp1 - exp0 + 2;
845

    
846
            exp0   = exp1;
847
            exp1   = p[0];
848
            p     += group_size;
849
            delta1 = exp1 - exp0 + 2;
850

    
851
            exp0   = exp1;
852
            exp1   = p[0];
853
            p     += group_size;
854
            delta2 = exp1 - exp0 + 2;
855

    
856
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
857
        }
858

    
859
        if (ch != s->lfe_channel)
860
            put_bits(&s->pb, 2, 0); /* no gain range info */
861
    }
862

    
863
    /* bit allocation info */
864
    baie = (block_num == 0);
865
    put_bits(&s->pb, 1, baie);
866
    if (baie) {
867
        put_bits(&s->pb, 2, s->slow_decay_code);
868
        put_bits(&s->pb, 2, s->fast_decay_code);
869
        put_bits(&s->pb, 2, s->slow_gain_code);
870
        put_bits(&s->pb, 2, s->db_per_bit_code);
871
        put_bits(&s->pb, 3, s->floor_code);
872
    }
873

    
874
    /* snr offset */
875
    put_bits(&s->pb, 1, baie);
876
    if (baie) {
877
        put_bits(&s->pb, 6, s->coarse_snr_offset);
878
        for (ch = 0; ch < s->channels; ch++) {
879
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
880
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
881
        }
882
    }
883

    
884
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
885
    put_bits(&s->pb, 1, 0); /* no data to skip */
886

    
887
    /* mantissa encoding : we use two passes to handle the grouping. A
888
       one pass method may be faster, but it would necessitate to
889
       modify the output stream. */
890

    
891
    /* first pass: quantize */
892
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
893
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
894

    
895
    for (ch = 0; ch < s->channels; ch++) {
896
        int b, c, e, v;
897

    
898
        for (i = 0; i < s->nb_coefs[ch]; i++) {
899
            c = mdct_coef[ch][i];
900
            e = encoded_exp[ch][i] - exp_shift[ch];
901
            b = bap[ch][i];
902
            switch (b) {
903
            case 0:
904
                v = 0;
905
                break;
906
            case 1:
907
                v = sym_quant(c, e, 3);
908
                switch (mant1_cnt) {
909
                case 0:
910
                    qmant1_ptr = &qmant[ch][i];
911
                    v = 9 * v;
912
                    mant1_cnt = 1;
913
                    break;
914
                case 1:
915
                    *qmant1_ptr += 3 * v;
916
                    mant1_cnt = 2;
917
                    v = 128;
918
                    break;
919
                default:
920
                    *qmant1_ptr += v;
921
                    mant1_cnt = 0;
922
                    v = 128;
923
                    break;
924
                }
925
                break;
926
            case 2:
927
                v = sym_quant(c, e, 5);
928
                switch (mant2_cnt) {
929
                case 0:
930
                    qmant2_ptr = &qmant[ch][i];
931
                    v = 25 * v;
932
                    mant2_cnt = 1;
933
                    break;
934
                case 1:
935
                    *qmant2_ptr += 5 * v;
936
                    mant2_cnt = 2;
937
                    v = 128;
938
                    break;
939
                default:
940
                    *qmant2_ptr += v;
941
                    mant2_cnt = 0;
942
                    v = 128;
943
                    break;
944
                }
945
                break;
946
            case 3:
947
                v = sym_quant(c, e, 7);
948
                break;
949
            case 4:
950
                v = sym_quant(c, e, 11);
951
                switch (mant4_cnt) {
952
                case 0:
953
                    qmant4_ptr = &qmant[ch][i];
954
                    v = 11 * v;
955
                    mant4_cnt = 1;
956
                    break;
957
                default:
958
                    *qmant4_ptr += v;
959
                    mant4_cnt = 0;
960
                    v = 128;
961
                    break;
962
                }
963
                break;
964
            case 5:
965
                v = sym_quant(c, e, 15);
966
                break;
967
            case 14:
968
                v = asym_quant(c, e, 14);
969
                break;
970
            case 15:
971
                v = asym_quant(c, e, 16);
972
                break;
973
            default:
974
                v = asym_quant(c, e, b - 1);
975
                break;
976
            }
977
            qmant[ch][i] = v;
978
        }
979
    }
980

    
981
    /* second pass : output the values */
982
    for (ch = 0; ch < s->channels; ch++) {
983
        int b, q;
984

    
985
        for (i = 0; i < s->nb_coefs[ch]; i++) {
986
            q = qmant[ch][i];
987
            b = bap[ch][i];
988
            switch (b) {
989
            case 0:                                         break;
990
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
991
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
992
            case 3:               put_bits(&s->pb,   3, q); break;
993
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
994
            case 14:              put_bits(&s->pb,  14, q); break;
995
            case 15:              put_bits(&s->pb,  16, q); break;
996
            default:              put_bits(&s->pb, b-1, q); break;
997
            }
998
        }
999
    }
1000
}
1001

    
1002

    
1003
/** CRC-16 Polynomial */
1004
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1005

    
1006

    
1007
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1008
{
1009
    unsigned int c;
1010

    
1011
    c = 0;
1012
    while (a) {
1013
        if (a & 1)
1014
            c ^= b;
1015
        a = a >> 1;
1016
        b = b << 1;
1017
        if (b & (1 << 16))
1018
            b ^= poly;
1019
    }
1020
    return c;
1021
}
1022

    
1023

    
1024
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1025
{
1026
    unsigned int r;
1027
    r = 1;
1028
    while (n) {
1029
        if (n & 1)
1030
            r = mul_poly(r, a, poly);
1031
        a = mul_poly(a, a, poly);
1032
        n >>= 1;
1033
    }
1034
    return r;
1035
}
1036

    
1037

    
1038
/**
1039
 * Fill the end of the frame with 0's and compute the two CRCs.
1040
 */
1041
static void output_frame_end(AC3EncodeContext *s)
1042
{
1043
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1044
    uint8_t *frame;
1045

    
1046
    frame_size = s->frame_size; /* frame size in words */
1047
    /* align to 8 bits */
1048
    flush_put_bits(&s->pb);
1049
    /* add zero bytes to reach the frame size */
1050
    frame = s->pb.buf;
1051
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1052
    assert(pad_bytes >= 0);
1053
    if (pad_bytes > 0)
1054
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1055

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

    
1060
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1061
                             frame + 4, frame_size_58 - 4));
1062

    
1063
    /* XXX: could precompute crc_inv */
1064
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1065
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1066
    AV_WB16(frame + 2, crc1);
1067

    
1068
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1069
                             frame + frame_size_58,
1070
                             frame_size - frame_size_58 - 2));
1071
    AV_WB16(frame + frame_size - 2, crc2);
1072
}
1073

    
1074

    
1075
/**
1076
 * Encode a single AC-3 frame.
1077
 */
1078
static int ac3_encode_frame(AVCodecContext *avctx,
1079
                            unsigned char *frame, int buf_size, void *data)
1080
{
1081
    AC3EncodeContext *s = avctx->priv_data;
1082
    const int16_t *samples = data;
1083
    int v;
1084
    int blk, blk1, blk2, ch, i;
1085
    int16_t input_samples[AC3_WINDOW_SIZE];
1086
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1087
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1088
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1089
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1090
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1091
    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1092
    int frame_bits;
1093

    
1094
    frame_bits = 0;
1095
    for (ch = 0; ch < s->channels; ch++) {
1096
        int ich = s->channel_map[ch];
1097
        /* fixed mdct to the six sub blocks & exponent computation */
1098
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1099
            const int16_t *sptr;
1100
            int sinc;
1101

    
1102
            /* compute input samples */
1103
            memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
1104
            sinc = s->channels;
1105
            sptr = samples + (sinc * AC3_BLOCK_SIZE * blk) + ich;
1106
            for (i = 0; i < AC3_BLOCK_SIZE; i++) {
1107
                v = *sptr;
1108
                input_samples[i + AC3_BLOCK_SIZE] = v;
1109
                s->last_samples[ich][i] = v;
1110
                sptr += sinc;
1111
            }
1112

    
1113
            /* apply the MDCT window */
1114
            for (i = 0; i < AC3_BLOCK_SIZE; i++) {
1115
                input_samples[i]                   = MUL16(input_samples[i],
1116
                                                           ff_ac3_window[i]) >> 15;
1117
                input_samples[AC3_WINDOW_SIZE-i-1] = MUL16(input_samples[AC3_WINDOW_SIZE-i-1],
1118
                                                           ff_ac3_window[i]) >> 15;
1119
            }
1120

    
1121
            /* Normalize the samples to use the maximum available precision */
1122
            v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
1123
            if (v < 0)
1124
                v = 0;
1125
            exp_shift[blk][ch] = v - 9;
1126
            lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
1127

    
1128
            /* do the MDCT */
1129
            mdct512(mdct_coef[blk][ch], input_samples);
1130

    
1131
            /* compute "exponents". We take into account the normalization there */
1132
            for (i = 0; i < AC3_MAX_COEFS; i++) {
1133
                int e;
1134
                v = abs(mdct_coef[blk][ch][i]);
1135
                if (v == 0)
1136
                    e = 24;
1137
                else {
1138
                    e = 23 - av_log2(v) + exp_shift[blk][ch];
1139
                    if (e >= 24) {
1140
                        e = 24;
1141
                        mdct_coef[blk][ch][i] = 0;
1142
                    }
1143
                }
1144
                exp[blk][ch][i] = e;
1145
            }
1146
        }
1147

    
1148
        compute_exp_strategy_ch(exp_strategy, exp, ch, ch == s->lfe_channel);
1149

    
1150
        /* compute the exponents as the decoder will see them. The
1151
           EXP_REUSE case must be handled carefully : we select the
1152
           min of the exponents */
1153
        blk = 0;
1154
        while (blk < AC3_MAX_BLOCKS) {
1155
            blk1 = blk + 1;
1156
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE) {
1157
                exponent_min(exp[blk][ch], exp[blk1][ch], s->nb_coefs[ch]);
1158
                blk1++;
1159
            }
1160
            frame_bits += encode_exponents_blk_ch(encoded_exp[blk][ch],
1161
                                                  exp[blk][ch], s->nb_coefs[ch],
1162
                                                  exp_strategy[blk][ch]);
1163
            /* copy encoded exponents for reuse case */
1164
            for (blk2 = blk+1; blk2 < blk1; blk2++) {
1165
                memcpy(encoded_exp[blk2][ch], encoded_exp[blk][ch],
1166
                       s->nb_coefs[ch] * sizeof(uint8_t));
1167
            }
1168
            blk = blk1;
1169
        }
1170
    }
1171

    
1172
    /* adjust for fractional frame sizes */
1173
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1174
        s->bits_written    -= s->bit_rate;
1175
        s->samples_written -= s->sample_rate;
1176
    }
1177
    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1178
    s->bits_written    += s->frame_size * 8;
1179
    s->samples_written += AC3_FRAME_SIZE;
1180

    
1181
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1182
    /* everything is known... let's output the frame */
1183
    output_frame_header(s, frame);
1184

    
1185
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1186
        output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
1187
                           bap[blk], mdct_coef[blk], exp_shift[blk], blk);
1188
    }
1189
    output_frame_end(s);
1190

    
1191
    return s->frame_size;
1192
}
1193

    
1194

    
1195
/**
1196
 * Finalize encoding and free any memory allocated by the encoder.
1197
 */
1198
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1199
{
1200
    av_freep(&avctx->coded_frame);
1201
    return 0;
1202
}
1203

    
1204

    
1205
/**
1206
 * Set channel information during initialization.
1207
 */
1208
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1209
                                    int64_t *channel_layout)
1210
{
1211
    int ch_layout;
1212

    
1213
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1214
        return AVERROR(EINVAL);
1215
    if ((uint64_t)*channel_layout > 0x7FF)
1216
        return AVERROR(EINVAL);
1217
    ch_layout = *channel_layout;
1218
    if (!ch_layout)
1219
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1220
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1221
        return AVERROR(EINVAL);
1222

    
1223
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1224
    s->channels     = channels;
1225
    s->fbw_channels = channels - s->lfe_on;
1226
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1227
    if (s->lfe_on)
1228
        ch_layout -= AV_CH_LOW_FREQUENCY;
1229

    
1230
    switch (ch_layout) {
1231
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1232
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1233
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1234
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1235
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1236
    case AV_CH_LAYOUT_QUAD:
1237
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1238
    case AV_CH_LAYOUT_5POINT0:
1239
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1240
    default:
1241
        return AVERROR(EINVAL);
1242
    }
1243

    
1244
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1245
    *channel_layout = ch_layout;
1246
    if (s->lfe_on)
1247
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1248

    
1249
    return 0;
1250
}
1251

    
1252

    
1253
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1254
{
1255
    int i, ret;
1256

    
1257
    if (!avctx->channel_layout) {
1258
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1259
                                      "encoder will guess the layout, but it "
1260
                                      "might be incorrect.\n");
1261
    }
1262
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1263
    if (ret) {
1264
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1265
        return ret;
1266
    }
1267

    
1268
    /* frequency */
1269
    for (i = 0; i < 9; i++) {
1270
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1271
            break;
1272
    }
1273
    if (i == 9) {
1274
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1275
        return AVERROR(EINVAL);
1276
    }
1277
    s->sample_rate        = avctx->sample_rate;
1278
    s->bit_alloc.sr_shift = i % 3;
1279
    s->bit_alloc.sr_code  = i / 3;
1280

    
1281
    /* bitrate & frame size */
1282
    for (i = 0; i < 19; i++) {
1283
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1284
            break;
1285
    }
1286
    if (i == 19) {
1287
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1288
        return AVERROR(EINVAL);
1289
    }
1290
    s->bit_rate        = avctx->bit_rate;
1291
    s->frame_size_code = i << 1;
1292

    
1293
    return 0;
1294
}
1295

    
1296

    
1297
/**
1298
 * Initialize the encoder.
1299
 */
1300
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1301
{
1302
    AC3EncodeContext *s = avctx->priv_data;
1303
    int ch, bw_code, ret;
1304

    
1305
    avctx->frame_size = AC3_FRAME_SIZE;
1306

    
1307
    ac3_common_init();
1308

    
1309
    ret = validate_options(avctx, s);
1310
    if (ret)
1311
        return ret;
1312

    
1313
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1314
    s->bitstream_mode = 0; /* complete main audio service */
1315

    
1316
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1317
    s->bits_written    = 0;
1318
    s->samples_written = 0;
1319
    s->frame_size      = s->frame_size_min;
1320

    
1321
    /* set bandwidth */
1322
    if (avctx->cutoff) {
1323
        /* calculate bandwidth based on user-specified cutoff frequency */
1324
        int cutoff     = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
1325
        int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1326
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1327
    } else {
1328
        /* use default bandwidth setting */
1329
        /* XXX: should compute the bandwidth according to the frame
1330
           size, so that we avoid annoying high frequency artifacts */
1331
        bw_code = 50;
1332
    }
1333
    for (ch = 0; ch < s->fbw_channels; ch++) {
1334
        /* bandwidth for each channel */
1335
        s->bandwidth_code[ch] = bw_code;
1336
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1337
    }
1338
    if (s->lfe_on)
1339
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1340

    
1341
    /* initial snr offset */
1342
    s->coarse_snr_offset = 40;
1343

    
1344
    mdct_init(9);
1345

    
1346
    avctx->coded_frame= avcodec_alloc_frame();
1347
    avctx->coded_frame->key_frame= 1;
1348

    
1349
    return 0;
1350
}
1351

    
1352

    
1353
#ifdef TEST
1354
/*************************************************************************/
1355
/* TEST */
1356

    
1357
#include "libavutil/lfg.h"
1358

    
1359
#define FN (MDCT_SAMPLES/4)
1360

    
1361

    
1362
static void fft_test(AVLFG *lfg)
1363
{
1364
    IComplex in[FN], in1[FN];
1365
    int k, n, i;
1366
    float sum_re, sum_im, a;
1367

    
1368
    for (i = 0; i < FN; i++) {
1369
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1370
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1371
        in1[i]   = in[i];
1372
    }
1373
    fft(in, 7);
1374

    
1375
    /* do it by hand */
1376
    for (k = 0; k < FN; k++) {
1377
        sum_re = 0;
1378
        sum_im = 0;
1379
        for (n = 0; n < FN; n++) {
1380
            a = -2 * M_PI * (n * k) / FN;
1381
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1382
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1383
        }
1384
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1385
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1386
    }
1387
}
1388

    
1389

    
1390
static void mdct_test(AVLFG *lfg)
1391
{
1392
    int16_t input[MDCT_SAMPLES];
1393
    int32_t output[AC3_MAX_COEFS];
1394
    float input1[MDCT_SAMPLES];
1395
    float output1[AC3_MAX_COEFS];
1396
    float s, a, err, e, emax;
1397
    int i, k, n;
1398

    
1399
    for (i = 0; i < MDCT_SAMPLES; i++) {
1400
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1401
        input1[i] = input[i];
1402
    }
1403

    
1404
    mdct512(output, input);
1405

    
1406
    /* do it by hand */
1407
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1408
        s = 0;
1409
        for (n = 0; n < MDCT_SAMPLES; n++) {
1410
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1411
            s += input1[n] * cos(a);
1412
        }
1413
        output1[k] = -2 * s / MDCT_SAMPLES;
1414
    }
1415

    
1416
    err  = 0;
1417
    emax = 0;
1418
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1419
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1420
        e = output[i] - output1[i];
1421
        if (e > emax)
1422
            emax = e;
1423
        err += e * e;
1424
    }
1425
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1426
}
1427

    
1428

    
1429
int main(void)
1430
{
1431
    AVLFG lfg;
1432

    
1433
    av_log_set_level(AV_LOG_DEBUG);
1434
    mdct_init(9);
1435

    
1436
    fft_test(&lfg);
1437
    mdct_test(&lfg);
1438

    
1439
    return 0;
1440
}
1441
#endif /* TEST */
1442

    
1443

    
1444
AVCodec ac3_encoder = {
1445
    "ac3",
1446
    AVMEDIA_TYPE_AUDIO,
1447
    CODEC_ID_AC3,
1448
    sizeof(AC3EncodeContext),
1449
    ac3_encode_init,
1450
    ac3_encode_frame,
1451
    ac3_encode_close,
1452
    NULL,
1453
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1454
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1455
    .channel_layouts = (const int64_t[]){
1456
        AV_CH_LAYOUT_MONO,
1457
        AV_CH_LAYOUT_STEREO,
1458
        AV_CH_LAYOUT_2_1,
1459
        AV_CH_LAYOUT_SURROUND,
1460
        AV_CH_LAYOUT_2_2,
1461
        AV_CH_LAYOUT_QUAD,
1462
        AV_CH_LAYOUT_4POINT0,
1463
        AV_CH_LAYOUT_5POINT0,
1464
        AV_CH_LAYOUT_5POINT0_BACK,
1465
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1466
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1467
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1468
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1469
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1470
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1471
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1472
        AV_CH_LAYOUT_5POINT1,
1473
        AV_CH_LAYOUT_5POINT1_BACK,
1474
        0 },
1475
};