Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ b6a1e523

History | View | Annotate | Download (52.4 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
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
97

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

    
101

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

    
108

    
109
/**
110
 * Adjust the frame size to make the average bit rate match the target bit rate.
111
 * This is only needed for 11025, 22050, and 44100 sample rates.
112
 */
113
static void adjust_frame_size(AC3EncodeContext *s)
114
{
115
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
116
        s->bits_written    -= s->bit_rate;
117
        s->samples_written -= s->sample_rate;
118
    }
119
    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
120
    s->bits_written    += s->frame_size * 8;
121
    s->samples_written += AC3_FRAME_SIZE;
122
}
123

    
124

    
125
/**
126
 * Deinterleave input samples.
127
 * Channels are reordered from FFmpeg's default order to AC-3 order.
128
 */
129
static void deinterleave_input_samples(AC3EncodeContext *s,
130
                                       const int16_t *samples,
131
                                       int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE])
132
{
133
    int ch, i;
134

    
135
    /* deinterleave and remap input samples */
136
    for (ch = 0; ch < s->channels; ch++) {
137
        const int16_t *sptr;
138
        int sinc;
139

    
140
        /* copy last 256 samples of previous frame to the start of the current frame */
141
        memcpy(&planar_samples[ch][0], s->last_samples[ch],
142
               AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
143

    
144
        /* deinterleave */
145
        sinc = s->channels;
146
        sptr = samples + s->channel_map[ch];
147
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
148
            planar_samples[ch][i] = *sptr;
149
            sptr += sinc;
150
        }
151

    
152
        /* save last 256 samples for next frame */
153
        memcpy(s->last_samples[ch], &planar_samples[ch][6* AC3_BLOCK_SIZE],
154
               AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
155
    }
156
}
157

    
158

    
159
/**
160
 * Initialize FFT tables.
161
 * @param ln log2(FFT size)
162
 */
163
static av_cold void fft_init(int ln)
164
{
165
    int i, n, n2;
166
    float alpha;
167

    
168
    n  = 1 << ln;
169
    n2 = n >> 1;
170

    
171
    for (i = 0; i < n2; i++) {
172
        alpha     = 2.0 * M_PI * i / n;
173
        costab[i] = FIX15(cos(alpha));
174
        sintab[i] = FIX15(sin(alpha));
175
    }
176
}
177

    
178

    
179
/**
180
 * Initialize MDCT tables.
181
 * @param nbits log2(MDCT size)
182
 */
183
static av_cold void mdct_init(int nbits)
184
{
185
    int i, n, n4;
186

    
187
    n  = 1 << nbits;
188
    n4 = n >> 2;
189

    
190
    fft_init(nbits - 2);
191

    
192
    for (i = 0; i < n4; i++) {
193
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
194
        xcos1[i] = FIX15(-cos(alpha));
195
        xsin1[i] = FIX15(-sin(alpha));
196
    }
197
}
198

    
199

    
200
/** Butterfly op */
201
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
202
{                                                       \
203
  int ax, ay, bx, by;                                   \
204
  bx  = pre1;                                           \
205
  by  = pim1;                                           \
206
  ax  = qre1;                                           \
207
  ay  = qim1;                                           \
208
  pre = (bx + ax) >> 1;                                 \
209
  pim = (by + ay) >> 1;                                 \
210
  qre = (bx - ax) >> 1;                                 \
211
  qim = (by - ay) >> 1;                                 \
212
}
213

    
214

    
215
/** Complex multiply */
216
#define CMUL(pre, pim, are, aim, bre, bim)              \
217
{                                                       \
218
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
219
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
220
}
221

    
222

    
223
/**
224
 * Calculate a 2^n point complex FFT on 2^ln points.
225
 * @param z  complex input/output samples
226
 * @param ln log2(FFT size)
227
 */
228
static void fft(IComplex *z, int ln)
229
{
230
    int j, l, np, np2;
231
    int nblocks, nloops;
232
    register IComplex *p,*q;
233
    int tmp_re, tmp_im;
234

    
235
    np = 1 << ln;
236

    
237
    /* reverse */
238
    for (j = 0; j < np; j++) {
239
        int k = av_reverse[j] >> (8 - ln);
240
        if (k < j)
241
            FFSWAP(IComplex, z[k], z[j]);
242
    }
243

    
244
    /* pass 0 */
245

    
246
    p = &z[0];
247
    j = np >> 1;
248
    do {
249
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
250
           p[0].re, p[0].im, p[1].re, p[1].im);
251
        p += 2;
252
    } while (--j);
253

    
254
    /* pass 1 */
255

    
256
    p = &z[0];
257
    j = np >> 2;
258
    do {
259
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
260
           p[0].re, p[0].im, p[2].re,  p[2].im);
261
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
262
           p[1].re, p[1].im, p[3].im, -p[3].re);
263
        p+=4;
264
    } while (--j);
265

    
266
    /* pass 2 .. ln-1 */
267

    
268
    nblocks = np >> 3;
269
    nloops  =  1 << 2;
270
    np2     = np >> 1;
271
    do {
272
        p = z;
273
        q = z + nloops;
274
        for (j = 0; j < nblocks; j++) {
275
            BF(p->re, p->im, q->re, q->im,
276
               p->re, p->im, q->re, q->im);
277
            p++;
278
            q++;
279
            for(l = nblocks; l < np2; l += nblocks) {
280
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
281
                BF(p->re, p->im, q->re,  q->im,
282
                   p->re, p->im, tmp_re, tmp_im);
283
                p++;
284
                q++;
285
            }
286
            p += nloops;
287
            q += nloops;
288
        }
289
        nblocks = nblocks >> 1;
290
        nloops  = nloops  << 1;
291
    } while (nblocks);
292
}
293

    
294

    
295
/**
296
 * Calculate a 512-point MDCT
297
 * @param out 256 output frequency coefficients
298
 * @param in  512 windowed input audio samples
299
 */
300
static void mdct512(int32_t *out, int16_t *in)
301
{
302
    int i, re, im, re1, im1;
303
    int16_t rot[MDCT_SAMPLES];
304
    IComplex x[MDCT_SAMPLES/4];
305

    
306
    /* shift to simplify computations */
307
    for (i = 0; i < MDCT_SAMPLES/4; i++)
308
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
309
    for (;i < MDCT_SAMPLES; i++)
310
        rot[i] =  in[i -   MDCT_SAMPLES/4];
311

    
312
    /* pre rotation */
313
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
314
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
315
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
316
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
317
    }
318

    
319
    fft(x, MDCT_NBITS - 2);
320

    
321
    /* post rotation */
322
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
323
        re = x[i].re;
324
        im = x[i].im;
325
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
326
        out[                 2*i] = im1;
327
        out[MDCT_SAMPLES/2-1-2*i] = re1;
328
    }
329
}
330

    
331

    
332
/**
333
 * Apply KBD window to input samples prior to MDCT.
334
 */
335
static void apply_window(int16_t *output, const int16_t *input,
336
                         const int16_t *window, int n)
337
{
338
    int i;
339
    int n2 = n >> 1;
340

    
341
    for (i = 0; i < n2; i++) {
342
        output[i]     = MUL16(input[i],     window[i]) >> 15;
343
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
344
    }
345
}
346

    
347

    
348
/**
349
 * Calculate the log2() of the maximum absolute value in an array.
350
 * @param tab input array
351
 * @param n   number of values in the array
352
 * @return    log2(max(abs(tab[])))
353
 */
354
static int log2_tab(int16_t *tab, int n)
355
{
356
    int i, v;
357

    
358
    v = 0;
359
    for (i = 0; i < n; i++)
360
        v |= abs(tab[i]);
361

    
362
    return av_log2(v);
363
}
364

    
365

    
366
/**
367
 * Left-shift each value in an array by a specified amount.
368
 * @param tab    input array
369
 * @param n      number of values in the array
370
 * @param lshift left shift amount. a negative value means right shift.
371
 */
372
static void lshift_tab(int16_t *tab, int n, int lshift)
373
{
374
    int i;
375

    
376
    if (lshift > 0) {
377
        for(i = 0; i < n; i++)
378
            tab[i] <<= lshift;
379
    } else if (lshift < 0) {
380
        lshift = -lshift;
381
        for (i = 0; i < n; i++)
382
            tab[i] >>= lshift;
383
    }
384
}
385

    
386

    
387
/**
388
 * Normalize the input samples to use the maximum available precision.
389
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
390
 * match the 24-bit internal precision for MDCT coefficients.
391
 *
392
 * @return exponent shift
393
 */
394
static int normalize_samples(AC3EncodeContext *s,
395
                             int16_t windowed_samples[AC3_WINDOW_SIZE])
396
{
397
    int v = 14 - log2_tab(windowed_samples, AC3_WINDOW_SIZE);
398
    v = FFMAX(0, v);
399
    lshift_tab(windowed_samples, AC3_WINDOW_SIZE, v);
400
    return v - 9;
401
}
402

    
403

    
404
/**
405
 * Apply the MDCT to input samples to generate frequency coefficients.
406
 * This applies the KBD window and normalizes the input to reduce precision
407
 * loss due to fixed-point calculations.
408
 */
409
static void apply_mdct(AC3EncodeContext *s,
410
                       int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE],
411
                       int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
412
                       int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
413
{
414
    int blk, ch;
415
    int16_t windowed_samples[AC3_WINDOW_SIZE];
416

    
417
    for (ch = 0; ch < s->channels; ch++) {
418
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
419
            const int16_t *input_samples = &planar_samples[ch][blk * AC3_BLOCK_SIZE];
420

    
421
            apply_window(windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
422

    
423
            exp_shift[blk][ch] = normalize_samples(s, windowed_samples);
424

    
425
            mdct512(mdct_coef[blk][ch], windowed_samples);
426
        }
427
    }
428
}
429

    
430

    
431
/**
432
 * Extract exponents from the MDCT coefficients.
433
 * This takes into account the normalization that was done to the input samples
434
 * by adjusting the exponents by the exponent shift values.
435
 */
436
static void extract_exponents(AC3EncodeContext *s,
437
                              int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
438
                              int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
439
                              uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
440
{
441
    int blk, ch, i;
442

    
443
    /* extract exponents */
444
    for (ch = 0; ch < s->channels; ch++) {
445
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
446
            /* compute "exponents". We take into account the normalization there */
447
            for (i = 0; i < AC3_MAX_COEFS; i++) {
448
                int e;
449
                int v = abs(mdct_coef[blk][ch][i]);
450
                if (v == 0)
451
                    e = 24;
452
                else {
453
                    e = 23 - av_log2(v) + exp_shift[blk][ch];
454
                    if (e >= 24) {
455
                        e = 24;
456
                        mdct_coef[blk][ch][i] = 0;
457
                    }
458
                }
459
                exp[blk][ch][i] = e;
460
            }
461
        }
462
    }
463
}
464

    
465

    
466
/**
467
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
468
 */
469
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
470
{
471
    int sum, i;
472
    sum = 0;
473
    for (i = 0; i < n; i++)
474
        sum += abs(exp1[i] - exp2[i]);
475
    return sum;
476
}
477

    
478

    
479
/**
480
 * Exponent Difference Threshold.
481
 * New exponents are sent if their SAD exceed this number.
482
 */
483
#define EXP_DIFF_THRESHOLD 1000
484

    
485

    
486
/**
487
 * Calculate exponent strategies for all blocks in a single channel.
488
 */
489
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
490
{
491
    int blk, blk1;
492
    int exp_diff;
493

    
494
    /* estimate if the exponent variation & decide if they should be
495
       reused in the next frame */
496
    exp_strategy[0] = EXP_NEW;
497
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
498
        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
499
        if (exp_diff > EXP_DIFF_THRESHOLD)
500
            exp_strategy[blk] = EXP_NEW;
501
        else
502
            exp_strategy[blk] = EXP_REUSE;
503
    }
504

    
505
    /* now select the encoding strategy type : if exponents are often
506
       recoded, we use a coarse encoding */
507
    blk = 0;
508
    while (blk < AC3_MAX_BLOCKS) {
509
        blk1 = blk + 1;
510
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
511
            blk1++;
512
        switch (blk1 - blk) {
513
        case 1:  exp_strategy[blk] = EXP_D45; break;
514
        case 2:
515
        case 3:  exp_strategy[blk] = EXP_D25; break;
516
        default: exp_strategy[blk] = EXP_D15; break;
517
        }
518
        blk = blk1;
519
    }
520
}
521

    
522

    
523
/**
524
 * Calculate exponent strategies for all channels.
525
 * Array arrangement is reversed to simplify the per-channel calculation.
526
 */
527
static void compute_exp_strategy(AC3EncodeContext *s,
528
                                 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
529
                                 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
530
{
531
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
532
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
533
    int ch, blk;
534

    
535
    for (ch = 0; ch < s->fbw_channels; ch++) {
536
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
537
            exp1[ch][blk]     = exp[blk][ch];
538
            exp_str1[ch][blk] = exp_strategy[blk][ch];
539
        }
540

    
541
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
542

    
543
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
544
            exp_strategy[blk][ch] = exp_str1[ch][blk];
545
    }
546
    if (s->lfe_on) {
547
        ch = s->lfe_channel;
548
        exp_strategy[0][ch] = EXP_D15;
549
        for (blk = 1; blk < 5; blk++)
550
            exp_strategy[blk][ch] = EXP_REUSE;
551
    }
552
}
553

    
554

    
555
/**
556
 * Set each encoded exponent in a block to the minimum of itself and the
557
 * exponent in the same frequency bin of a following block.
558
 * exp[i] = min(exp[i], exp1[i]
559
 */
560
static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
561
{
562
    int i;
563
    for (i = 0; i < n; i++) {
564
        if (exp1[i] < exp[i])
565
            exp[i] = exp1[i];
566
    }
567
}
568

    
569

    
570
/**
571
 * Update the exponents so that they are the ones the decoder will decode.
572
 * @return the number of bits used to encode the exponents.
573
 */
574
static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
575
                                   uint8_t exp[AC3_MAX_COEFS],
576
                                   int nb_exps, int exp_strategy)
577
{
578
    int group_size, nb_groups, i, j, k, exp_min;
579
    uint8_t exp1[AC3_MAX_COEFS];
580

    
581
    group_size = exp_strategy + (exp_strategy == EXP_D45);
582
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
583

    
584
    /* for each group, compute the minimum exponent */
585
    exp1[0] = exp[0]; /* DC exponent is handled separately */
586
    k = 1;
587
    for (i = 1; i <= nb_groups; i++) {
588
        exp_min = exp[k];
589
        assert(exp_min >= 0 && exp_min <= 24);
590
        for (j = 1; j < group_size; j++) {
591
            if (exp[k+j] < exp_min)
592
                exp_min = exp[k+j];
593
        }
594
        exp1[i] = exp_min;
595
        k += group_size;
596
    }
597

    
598
    /* constraint for DC exponent */
599
    if (exp1[0] > 15)
600
        exp1[0] = 15;
601

    
602
    /* decrease the delta between each groups to within 2 so that they can be
603
       differentially encoded */
604
    for (i = 1; i <= nb_groups; i++)
605
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
606
    for (i = nb_groups-1; i >= 0; i--)
607
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
608

    
609
    /* now we have the exponent values the decoder will see */
610
    encoded_exp[0] = exp1[0];
611
    k = 1;
612
    for (i = 1; i <= nb_groups; i++) {
613
        for (j = 0; j < group_size; j++)
614
            encoded_exp[k+j] = exp1[i];
615
        k += group_size;
616
    }
617

    
618
    return 4 + (nb_groups / 3) * 7;
619
}
620

    
621

    
622
/**
623
 * Encode exponents from original extracted form to what the decoder will see.
624
 * This copies and groups exponents based on exponent strategy and reduces
625
 * deltas between adjacent exponent groups so that they can be differentially
626
 * encoded.
627
 * @return bits needed to encode the exponents
628
 */
629
static int encode_exponents(AC3EncodeContext *s,
630
                            uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
631
                            uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
632
                            uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
633
{
634
    int blk, blk1, blk2, ch;
635
    int frame_bits;
636

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

    
659
    return frame_bits;
660
}
661

    
662

    
663
/**
664
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
665
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
666
 * and encode final exponents.
667
 * @return bits needed to encode the exponents
668
 */
669
static int process_exponents(AC3EncodeContext *s,
670
                             int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
671
                             int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
672
                             uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
673
                             uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
674
                             uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
675
{
676
    extract_exponents(s, mdct_coef, exp_shift, exp);
677

    
678
    compute_exp_strategy(s, exp_strategy, exp);
679

    
680
    return encode_exponents(s, exp, exp_strategy, encoded_exp);
681
}
682

    
683

    
684
/**
685
 * Calculate the number of bits needed to encode a set of mantissas.
686
 */
687
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
688
{
689
    int bits, mant, i;
690

    
691
    bits = 0;
692
    for (i = 0; i < nb_coefs; i++) {
693
        mant = m[i];
694
        switch (mant) {
695
        case 0:
696
            /* nothing */
697
            break;
698
        case 1:
699
            /* 3 mantissa in 5 bits */
700
            if (s->mant1_cnt == 0)
701
                bits += 5;
702
            if (++s->mant1_cnt == 3)
703
                s->mant1_cnt = 0;
704
            break;
705
        case 2:
706
            /* 3 mantissa in 7 bits */
707
            if (s->mant2_cnt == 0)
708
                bits += 7;
709
            if (++s->mant2_cnt == 3)
710
                s->mant2_cnt = 0;
711
            break;
712
        case 3:
713
            bits += 3;
714
            break;
715
        case 4:
716
            /* 2 mantissa in 7 bits */
717
            if (s->mant4_cnt == 0)
718
                bits += 7;
719
            if (++s->mant4_cnt == 2)
720
                s->mant4_cnt = 0;
721
            break;
722
        case 14:
723
            bits += 14;
724
            break;
725
        case 15:
726
            bits += 16;
727
            break;
728
        default:
729
            bits += mant - 1;
730
            break;
731
        }
732
    }
733
    return bits;
734
}
735

    
736

    
737
/**
738
 * Calculate masking curve based on the final exponents.
739
 * Also calculate the power spectral densities to use in future calculations.
740
 */
741
static void bit_alloc_masking(AC3EncodeContext *s,
742
                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
743
                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
744
                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
745
                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
746
{
747
    int blk, ch;
748
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
749

    
750
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
751
        for (ch = 0; ch < s->channels; ch++) {
752
            if(exp_strategy[blk][ch] == EXP_REUSE) {
753
                memcpy(psd[blk][ch],  psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(psd[0][0][0]));
754
                memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
755
            } else {
756
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
757
                                          s->nb_coefs[ch],
758
                                          psd[blk][ch], band_psd[blk][ch]);
759
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
760
                                           0, s->nb_coefs[ch],
761
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
762
                                           ch == s->lfe_channel,
763
                                           DBA_NONE, 0, NULL, NULL, NULL,
764
                                           mask[blk][ch]);
765
            }
766
        }
767
    }
768
}
769

    
770

    
771
/**
772
 * Run the bit allocation with a given SNR offset.
773
 * This calculates the bit allocation pointers that will be used to determine
774
 * the quantization of each mantissa.
775
 * @return the number of remaining bits (positive or negative) if the given
776
 *         SNR offset is used to quantize the mantissas.
777
 */
778
static int bit_alloc(AC3EncodeContext *s,
779
                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
780
                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
781
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
782
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
783
{
784
    int blk, ch;
785
    int snr_offset;
786

    
787
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
788

    
789
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
790
        s->mant1_cnt = 0;
791
        s->mant2_cnt = 0;
792
        s->mant4_cnt = 0;
793
        for (ch = 0; ch < s->channels; ch++) {
794
            ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
795
                                      s->nb_coefs[ch], snr_offset,
796
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
797
                                      bap[blk][ch]);
798
            frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
799
        }
800
    }
801
    return 8 * s->frame_size - frame_bits;
802
}
803

    
804

    
805
#define SNR_INC1 4
806

    
807
/**
808
 * Perform bit allocation search.
809
 * Finds the SNR offset value that maximizes quality and fits in the specified
810
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
811
 * used to quantize the mantissas.
812
 */
813
static int compute_bit_allocation(AC3EncodeContext *s,
814
                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
815
                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
816
                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
817
                                  int frame_bits)
818
{
819
    int blk, ch;
820
    int coarse_snr_offset, fine_snr_offset;
821
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
822
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
823
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
824
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
825

    
826
    /* init default parameters */
827
    s->slow_decay_code = 2;
828
    s->fast_decay_code = 1;
829
    s->slow_gain_code  = 1;
830
    s->db_per_bit_code = 2;
831
    s->floor_code      = 4;
832
    for (ch = 0; ch < s->channels; ch++)
833
        s->fast_gain_code[ch] = 4;
834

    
835
    /* compute real values */
836
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
837
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
838
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
839
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
840
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
841

    
842
    /* header size */
843
    frame_bits += 65;
844
    // if (s->channel_mode == 2)
845
    //    frame_bits += 2;
846
    frame_bits += frame_bits_inc[s->channel_mode];
847

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

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

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

    
880
    /* calculate psd and masking curve before doing bit allocation */
881
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
882

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

    
886
    coarse_snr_offset = s->coarse_snr_offset;
887
    while (coarse_snr_offset >= 0 &&
888
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
889
        coarse_snr_offset -= SNR_INC1;
890
    if (coarse_snr_offset < 0) {
891
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
892
        return -1;
893
    }
894
    while (coarse_snr_offset + SNR_INC1 <= 63 &&
895
           bit_alloc(s, mask, psd, bap1, frame_bits,
896
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
897
        coarse_snr_offset += SNR_INC1;
898
        memcpy(bap, bap1, sizeof(bap1));
899
    }
900
    while (coarse_snr_offset + 1 <= 63 &&
901
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
902
        coarse_snr_offset++;
903
        memcpy(bap, bap1, sizeof(bap1));
904
    }
905

    
906
    fine_snr_offset = 0;
907
    while (fine_snr_offset + SNR_INC1 <= 15 &&
908
           bit_alloc(s, mask, psd, bap1, frame_bits,
909
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
910
        fine_snr_offset += SNR_INC1;
911
        memcpy(bap, bap1, sizeof(bap1));
912
    }
913
    while (fine_snr_offset + 1 <= 15 &&
914
           bit_alloc(s, mask, psd, bap1, frame_bits,
915
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
916
        fine_snr_offset++;
917
        memcpy(bap, bap1, sizeof(bap1));
918
    }
919

    
920
    s->coarse_snr_offset = coarse_snr_offset;
921
    for (ch = 0; ch < s->channels; ch++)
922
        s->fine_snr_offset[ch] = fine_snr_offset;
923

    
924
    return 0;
925
}
926

    
927

    
928
/**
929
 * Symmetric quantization on 'levels' levels.
930
 */
931
static inline int sym_quant(int c, int e, int levels)
932
{
933
    int v;
934

    
935
    if (c >= 0) {
936
        v = (levels * (c << e)) >> 24;
937
        v = (v + 1) >> 1;
938
        v = (levels >> 1) + v;
939
    } else {
940
        v = (levels * ((-c) << e)) >> 24;
941
        v = (v + 1) >> 1;
942
        v = (levels >> 1) - v;
943
    }
944
    assert (v >= 0 && v < levels);
945
    return v;
946
}
947

    
948

    
949
/**
950
 * Asymmetric quantization on 2^qbits levels.
951
 */
952
static inline int asym_quant(int c, int e, int qbits)
953
{
954
    int lshift, m, v;
955

    
956
    lshift = e + qbits - 24;
957
    if (lshift >= 0)
958
        v = c << lshift;
959
    else
960
        v = c >> (-lshift);
961
    /* rounding */
962
    v = (v + 1) >> 1;
963
    m = (1 << (qbits-1));
964
    if (v >= m)
965
        v = m - 1;
966
    assert(v >= -m);
967
    return v & ((1 << qbits)-1);
968
}
969

    
970

    
971
/**
972
 * Quantize a set of mantissas for a single channel in a single block.
973
 */
974
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
975
                                      int32_t *mdct_coef, int8_t exp_shift,
976
                                      uint8_t *encoded_exp, uint8_t *bap,
977
                                      uint16_t *qmant, int n)
978
{
979
    int i;
980

    
981
    for (i = 0; i < n; i++) {
982
        int v;
983
        int c = mdct_coef[i];
984
        int e = encoded_exp[i] - exp_shift;
985
        int b = bap[i];
986
        switch (b) {
987
        case 0:
988
            v = 0;
989
            break;
990
        case 1:
991
            v = sym_quant(c, e, 3);
992
            switch (s->mant1_cnt) {
993
            case 0:
994
                s->qmant1_ptr = &qmant[i];
995
                v = 9 * v;
996
                s->mant1_cnt = 1;
997
                break;
998
            case 1:
999
                *s->qmant1_ptr += 3 * v;
1000
                s->mant1_cnt = 2;
1001
                v = 128;
1002
                break;
1003
            default:
1004
                *s->qmant1_ptr += v;
1005
                s->mant1_cnt = 0;
1006
                v = 128;
1007
                break;
1008
            }
1009
            break;
1010
        case 2:
1011
            v = sym_quant(c, e, 5);
1012
            switch (s->mant2_cnt) {
1013
            case 0:
1014
                s->qmant2_ptr = &qmant[i];
1015
                v = 25 * v;
1016
                s->mant2_cnt = 1;
1017
                break;
1018
            case 1:
1019
                *s->qmant2_ptr += 5 * v;
1020
                s->mant2_cnt = 2;
1021
                v = 128;
1022
                break;
1023
            default:
1024
                *s->qmant2_ptr += v;
1025
                s->mant2_cnt = 0;
1026
                v = 128;
1027
                break;
1028
            }
1029
            break;
1030
        case 3:
1031
            v = sym_quant(c, e, 7);
1032
            break;
1033
        case 4:
1034
            v = sym_quant(c, e, 11);
1035
            switch (s->mant4_cnt) {
1036
            case 0:
1037
                s->qmant4_ptr = &qmant[i];
1038
                v = 11 * v;
1039
                s->mant4_cnt = 1;
1040
                break;
1041
            default:
1042
                *s->qmant4_ptr += v;
1043
                s->mant4_cnt = 0;
1044
                v = 128;
1045
                break;
1046
            }
1047
            break;
1048
        case 5:
1049
            v = sym_quant(c, e, 15);
1050
            break;
1051
        case 14:
1052
            v = asym_quant(c, e, 14);
1053
            break;
1054
        case 15:
1055
            v = asym_quant(c, e, 16);
1056
            break;
1057
        default:
1058
            v = asym_quant(c, e, b - 1);
1059
            break;
1060
        }
1061
        qmant[i] = v;
1062
    }
1063
}
1064

    
1065

    
1066
/**
1067
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1068
 */
1069
static void quantize_mantissas(AC3EncodeContext *s,
1070
                               int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1071
                               int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1072
                               uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1073
                               uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1074
                               uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
1075
{
1076
    int blk, ch;
1077

    
1078

    
1079
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1080
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1081
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1082

    
1083
        for (ch = 0; ch < s->channels; ch++) {
1084
            quantize_mantissas_blk_ch(s, mdct_coef[blk][ch], exp_shift[blk][ch],
1085
                                      encoded_exp[blk][ch], bap[blk][ch],
1086
                                      qmant[blk][ch], s->nb_coefs[ch]);
1087
        }
1088
    }
1089
}
1090

    
1091

    
1092
/**
1093
 * Write the AC-3 frame header to the output bitstream.
1094
 */
1095
static void output_frame_header(AC3EncodeContext *s)
1096
{
1097
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1098
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1099
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1100
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1101
    put_bits(&s->pb, 5,  s->bitstream_id);
1102
    put_bits(&s->pb, 3,  s->bitstream_mode);
1103
    put_bits(&s->pb, 3,  s->channel_mode);
1104
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1105
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1106
    if (s->channel_mode & 0x04)
1107
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1108
    if (s->channel_mode == AC3_CHMODE_STEREO)
1109
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1110
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1111
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1112
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1113
    put_bits(&s->pb, 1, 0);         /* no lang code */
1114
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1115
    put_bits(&s->pb, 1, 0);         /* no copyright */
1116
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1117
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1118
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1119
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1120
}
1121

    
1122

    
1123
/**
1124
 * Write one audio block to the output bitstream.
1125
 */
1126
static void output_audio_block(AC3EncodeContext *s,
1127
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
1128
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1129
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1130
                               uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1131
                               int block_num)
1132
{
1133
    int ch, nb_groups, group_size, i, baie, rbnd;
1134
    uint8_t *p;
1135
    int exp0, exp1;
1136
    int delta0, delta1, delta2;
1137

    
1138
    for (ch = 0; ch < s->fbw_channels; ch++)
1139
        put_bits(&s->pb, 1, 0); /* no block switching */
1140
    for (ch = 0; ch < s->fbw_channels; ch++)
1141
        put_bits(&s->pb, 1, 1); /* no dither */
1142
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
1143
    if (!block_num) {
1144
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1145
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1146
    } else {
1147
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1148
    }
1149

    
1150
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1151
        if (!block_num) {
1152
            /* first block must define rematrixing (rematstr) */
1153
            put_bits(&s->pb, 1, 1);
1154

    
1155
            /* dummy rematrixing rematflg(1:4)=0 */
1156
            for (rbnd = 0; rbnd < 4; rbnd++)
1157
                put_bits(&s->pb, 1, 0);
1158
        } else {
1159
            /* no matrixing (but should be used in the future) */
1160
            put_bits(&s->pb, 1, 0);
1161
        }
1162
    }
1163

    
1164
    /* exponent strategy */
1165
    for (ch = 0; ch < s->fbw_channels; ch++)
1166
        put_bits(&s->pb, 2, exp_strategy[ch]);
1167

    
1168
    if (s->lfe_on)
1169
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1170

    
1171
    /* bandwidth */
1172
    for (ch = 0; ch < s->fbw_channels; ch++) {
1173
        if (exp_strategy[ch] != EXP_REUSE)
1174
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1175
    }
1176

    
1177
    /* exponents */
1178
    for (ch = 0; ch < s->channels; ch++) {
1179
        if (exp_strategy[ch] == EXP_REUSE)
1180
            continue;
1181
        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
1182
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1183
        p = encoded_exp[ch];
1184

    
1185
        /* first exponent */
1186
        exp1 = *p++;
1187
        put_bits(&s->pb, 4, exp1);
1188

    
1189
        /* next ones are delta encoded */
1190
        for (i = 0; i < nb_groups; i++) {
1191
            /* merge three delta in one code */
1192
            exp0   = exp1;
1193
            exp1   = p[0];
1194
            p     += group_size;
1195
            delta0 = exp1 - exp0 + 2;
1196

    
1197
            exp0   = exp1;
1198
            exp1   = p[0];
1199
            p     += group_size;
1200
            delta1 = exp1 - exp0 + 2;
1201

    
1202
            exp0   = exp1;
1203
            exp1   = p[0];
1204
            p     += group_size;
1205
            delta2 = exp1 - exp0 + 2;
1206

    
1207
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1208
        }
1209

    
1210
        if (ch != s->lfe_channel)
1211
            put_bits(&s->pb, 2, 0); /* no gain range info */
1212
    }
1213

    
1214
    /* bit allocation info */
1215
    baie = (block_num == 0);
1216
    put_bits(&s->pb, 1, baie);
1217
    if (baie) {
1218
        put_bits(&s->pb, 2, s->slow_decay_code);
1219
        put_bits(&s->pb, 2, s->fast_decay_code);
1220
        put_bits(&s->pb, 2, s->slow_gain_code);
1221
        put_bits(&s->pb, 2, s->db_per_bit_code);
1222
        put_bits(&s->pb, 3, s->floor_code);
1223
    }
1224

    
1225
    /* snr offset */
1226
    put_bits(&s->pb, 1, baie);
1227
    if (baie) {
1228
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1229
        for (ch = 0; ch < s->channels; ch++) {
1230
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1231
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1232
        }
1233
    }
1234

    
1235
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1236
    put_bits(&s->pb, 1, 0); /* no data to skip */
1237

    
1238
    /* mantissa encoding */
1239
    for (ch = 0; ch < s->channels; ch++) {
1240
        int b, q;
1241

    
1242
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1243
            q = qmant[ch][i];
1244
            b = bap[ch][i];
1245
            switch (b) {
1246
            case 0:                                         break;
1247
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1248
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1249
            case 3:               put_bits(&s->pb,   3, q); break;
1250
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1251
            case 14:              put_bits(&s->pb,  14, q); break;
1252
            case 15:              put_bits(&s->pb,  16, q); break;
1253
            default:              put_bits(&s->pb, b-1, q); break;
1254
            }
1255
        }
1256
    }
1257
}
1258

    
1259

    
1260
/** CRC-16 Polynomial */
1261
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1262

    
1263

    
1264
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1265
{
1266
    unsigned int c;
1267

    
1268
    c = 0;
1269
    while (a) {
1270
        if (a & 1)
1271
            c ^= b;
1272
        a = a >> 1;
1273
        b = b << 1;
1274
        if (b & (1 << 16))
1275
            b ^= poly;
1276
    }
1277
    return c;
1278
}
1279

    
1280

    
1281
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1282
{
1283
    unsigned int r;
1284
    r = 1;
1285
    while (n) {
1286
        if (n & 1)
1287
            r = mul_poly(r, a, poly);
1288
        a = mul_poly(a, a, poly);
1289
        n >>= 1;
1290
    }
1291
    return r;
1292
}
1293

    
1294

    
1295
/**
1296
 * Fill the end of the frame with 0's and compute the two CRCs.
1297
 */
1298
static void output_frame_end(AC3EncodeContext *s)
1299
{
1300
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1301
    uint8_t *frame;
1302

    
1303
    frame_size = s->frame_size; /* frame size in words */
1304
    /* align to 8 bits */
1305
    flush_put_bits(&s->pb);
1306
    /* add zero bytes to reach the frame size */
1307
    frame = s->pb.buf;
1308
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1309
    assert(pad_bytes >= 0);
1310
    if (pad_bytes > 0)
1311
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1312

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

    
1317
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1318
                             frame + 4, frame_size_58 - 4));
1319

    
1320
    /* XXX: could precompute crc_inv */
1321
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1322
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1323
    AV_WB16(frame + 2, crc1);
1324

    
1325
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1326
                             frame + frame_size_58,
1327
                             frame_size - frame_size_58 - 2));
1328
    AV_WB16(frame + frame_size - 2, crc2);
1329
}
1330

    
1331

    
1332
/**
1333
 * Write the frame to the output bitstream.
1334
 */
1335
static void output_frame(AC3EncodeContext *s,
1336
                         unsigned char *frame,
1337
                         uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1338
                         uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1339
                         uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1340
                         uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
1341
{
1342
    int blk;
1343

    
1344
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1345

    
1346
    output_frame_header(s);
1347

    
1348
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1349
        output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
1350
                           bap[blk], qmant[blk], blk);
1351
    }
1352

    
1353
    output_frame_end(s);
1354
}
1355

    
1356

    
1357
/**
1358
 * Encode a single AC-3 frame.
1359
 */
1360
static int ac3_encode_frame(AVCodecContext *avctx,
1361
                            unsigned char *frame, int buf_size, void *data)
1362
{
1363
    AC3EncodeContext *s = avctx->priv_data;
1364
    const int16_t *samples = data;
1365
    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
1366
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1367
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1368
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1369
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1370
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1371
    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1372
    uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1373
    int frame_bits;
1374

    
1375
    if (s->bit_alloc.sr_code == 1)
1376
        adjust_frame_size(s);
1377

    
1378
    deinterleave_input_samples(s, samples, planar_samples);
1379

    
1380
    apply_mdct(s, planar_samples, exp_shift, mdct_coef);
1381

    
1382
    frame_bits = process_exponents(s, mdct_coef, exp_shift, exp, exp_strategy, encoded_exp);
1383

    
1384
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1385

    
1386
    quantize_mantissas(s, mdct_coef, exp_shift, encoded_exp, bap, qmant);
1387

    
1388
    output_frame(s, frame, exp_strategy, encoded_exp, bap, qmant);
1389

    
1390
    return s->frame_size;
1391
}
1392

    
1393

    
1394
/**
1395
 * Finalize encoding and free any memory allocated by the encoder.
1396
 */
1397
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1398
{
1399
    av_freep(&avctx->coded_frame);
1400
    return 0;
1401
}
1402

    
1403

    
1404
/**
1405
 * Set channel information during initialization.
1406
 */
1407
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1408
                                    int64_t *channel_layout)
1409
{
1410
    int ch_layout;
1411

    
1412
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1413
        return AVERROR(EINVAL);
1414
    if ((uint64_t)*channel_layout > 0x7FF)
1415
        return AVERROR(EINVAL);
1416
    ch_layout = *channel_layout;
1417
    if (!ch_layout)
1418
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1419
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1420
        return AVERROR(EINVAL);
1421

    
1422
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1423
    s->channels     = channels;
1424
    s->fbw_channels = channels - s->lfe_on;
1425
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1426
    if (s->lfe_on)
1427
        ch_layout -= AV_CH_LOW_FREQUENCY;
1428

    
1429
    switch (ch_layout) {
1430
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1431
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1432
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1433
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1434
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1435
    case AV_CH_LAYOUT_QUAD:
1436
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1437
    case AV_CH_LAYOUT_5POINT0:
1438
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1439
    default:
1440
        return AVERROR(EINVAL);
1441
    }
1442

    
1443
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1444
    *channel_layout = ch_layout;
1445
    if (s->lfe_on)
1446
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1447

    
1448
    return 0;
1449
}
1450

    
1451

    
1452
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1453
{
1454
    int i, ret;
1455

    
1456
    /* validate channel layout */
1457
    if (!avctx->channel_layout) {
1458
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1459
                                      "encoder will guess the layout, but it "
1460
                                      "might be incorrect.\n");
1461
    }
1462
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1463
    if (ret) {
1464
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1465
        return ret;
1466
    }
1467

    
1468
    /* validate sample rate */
1469
    for (i = 0; i < 9; i++) {
1470
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1471
            break;
1472
    }
1473
    if (i == 9) {
1474
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1475
        return AVERROR(EINVAL);
1476
    }
1477
    s->sample_rate        = avctx->sample_rate;
1478
    s->bit_alloc.sr_shift = i % 3;
1479
    s->bit_alloc.sr_code  = i / 3;
1480

    
1481
    /* validate bit rate */
1482
    for (i = 0; i < 19; i++) {
1483
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1484
            break;
1485
    }
1486
    if (i == 19) {
1487
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1488
        return AVERROR(EINVAL);
1489
    }
1490
    s->bit_rate        = avctx->bit_rate;
1491
    s->frame_size_code = i << 1;
1492

    
1493
    return 0;
1494
}
1495

    
1496

    
1497
/**
1498
 * Set bandwidth for all channels.
1499
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1500
 * default value will be used.
1501
 */
1502
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1503
{
1504
    int ch, bw_code;
1505

    
1506
    if (cutoff) {
1507
        /* calculate bandwidth based on user-specified cutoff frequency */
1508
        int fbw_coeffs;
1509
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1510
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1511
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1512
    } else {
1513
        /* use default bandwidth setting */
1514
        /* XXX: should compute the bandwidth according to the frame
1515
           size, so that we avoid annoying high frequency artifacts */
1516
        bw_code = 50;
1517
    }
1518

    
1519
    /* set number of coefficients for each channel */
1520
    for (ch = 0; ch < s->fbw_channels; ch++) {
1521
        s->bandwidth_code[ch] = bw_code;
1522
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1523
    }
1524
    if (s->lfe_on)
1525
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1526
}
1527

    
1528

    
1529
/**
1530
 * Initialize the encoder.
1531
 */
1532
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1533
{
1534
    AC3EncodeContext *s = avctx->priv_data;
1535
    int ret;
1536

    
1537
    avctx->frame_size = AC3_FRAME_SIZE;
1538

    
1539
    ac3_common_init();
1540

    
1541
    ret = validate_options(avctx, s);
1542
    if (ret)
1543
        return ret;
1544

    
1545
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1546
    s->bitstream_mode = 0; /* complete main audio service */
1547

    
1548
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1549
    s->bits_written    = 0;
1550
    s->samples_written = 0;
1551
    s->frame_size      = s->frame_size_min;
1552

    
1553
    set_bandwidth(s, avctx->cutoff);
1554

    
1555
    /* initial snr offset */
1556
    s->coarse_snr_offset = 40;
1557

    
1558
    mdct_init(9);
1559

    
1560
    avctx->coded_frame= avcodec_alloc_frame();
1561
    avctx->coded_frame->key_frame= 1;
1562

    
1563
    return 0;
1564
}
1565

    
1566

    
1567
#ifdef TEST
1568
/*************************************************************************/
1569
/* TEST */
1570

    
1571
#include "libavutil/lfg.h"
1572

    
1573
#define FN (MDCT_SAMPLES/4)
1574

    
1575

    
1576
static void fft_test(AVLFG *lfg)
1577
{
1578
    IComplex in[FN], in1[FN];
1579
    int k, n, i;
1580
    float sum_re, sum_im, a;
1581

    
1582
    for (i = 0; i < FN; i++) {
1583
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1584
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1585
        in1[i]   = in[i];
1586
    }
1587
    fft(in, 7);
1588

    
1589
    /* do it by hand */
1590
    for (k = 0; k < FN; k++) {
1591
        sum_re = 0;
1592
        sum_im = 0;
1593
        for (n = 0; n < FN; n++) {
1594
            a = -2 * M_PI * (n * k) / FN;
1595
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1596
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1597
        }
1598
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1599
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1600
    }
1601
}
1602

    
1603

    
1604
static void mdct_test(AVLFG *lfg)
1605
{
1606
    int16_t input[MDCT_SAMPLES];
1607
    int32_t output[AC3_MAX_COEFS];
1608
    float input1[MDCT_SAMPLES];
1609
    float output1[AC3_MAX_COEFS];
1610
    float s, a, err, e, emax;
1611
    int i, k, n;
1612

    
1613
    for (i = 0; i < MDCT_SAMPLES; i++) {
1614
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1615
        input1[i] = input[i];
1616
    }
1617

    
1618
    mdct512(output, input);
1619

    
1620
    /* do it by hand */
1621
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1622
        s = 0;
1623
        for (n = 0; n < MDCT_SAMPLES; n++) {
1624
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1625
            s += input1[n] * cos(a);
1626
        }
1627
        output1[k] = -2 * s / MDCT_SAMPLES;
1628
    }
1629

    
1630
    err  = 0;
1631
    emax = 0;
1632
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1633
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1634
        e = output[i] - output1[i];
1635
        if (e > emax)
1636
            emax = e;
1637
        err += e * e;
1638
    }
1639
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1640
}
1641

    
1642

    
1643
int main(void)
1644
{
1645
    AVLFG lfg;
1646

    
1647
    av_log_set_level(AV_LOG_DEBUG);
1648
    mdct_init(9);
1649

    
1650
    fft_test(&lfg);
1651
    mdct_test(&lfg);
1652

    
1653
    return 0;
1654
}
1655
#endif /* TEST */
1656

    
1657

    
1658
AVCodec ac3_encoder = {
1659
    "ac3",
1660
    AVMEDIA_TYPE_AUDIO,
1661
    CODEC_ID_AC3,
1662
    sizeof(AC3EncodeContext),
1663
    ac3_encode_init,
1664
    ac3_encode_frame,
1665
    ac3_encode_close,
1666
    NULL,
1667
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1668
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1669
    .channel_layouts = (const int64_t[]){
1670
        AV_CH_LAYOUT_MONO,
1671
        AV_CH_LAYOUT_STEREO,
1672
        AV_CH_LAYOUT_2_1,
1673
        AV_CH_LAYOUT_SURROUND,
1674
        AV_CH_LAYOUT_2_2,
1675
        AV_CH_LAYOUT_QUAD,
1676
        AV_CH_LAYOUT_4POINT0,
1677
        AV_CH_LAYOUT_5POINT0,
1678
        AV_CH_LAYOUT_5POINT0_BACK,
1679
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1680
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1681
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1682
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1683
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1684
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1685
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1686
        AV_CH_LAYOUT_5POINT1,
1687
        AV_CH_LAYOUT_5POINT1_BACK,
1688
        0 },
1689
};