Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ aa645b98

History | View | Annotate | Download (52.1 KB)

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

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

    
27
//#define DEBUG
28

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

    
36

    
37
#define MDCT_NBITS 9
38
#define MDCT_SAMPLES (1 << MDCT_NBITS)
39

    
40
/** Maximum number of exponent groups. +1 for separate DC exponent. */
41
#define AC3_MAX_EXP_GROUPS 85
42

    
43
/** Scale a float value by 2^bits and convert to an integer. */
44
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
45

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

    
49

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

    
58
/**
59
 * Data for a single audio block.
60
 */
61
typedef struct AC3Block {
62
    uint8_t  **bap;                             ///< bap for each channel in this block
63
    int32_t  mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
64
    uint8_t  exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
65
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];
66
    uint8_t  encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
67
    uint8_t  num_exp_groups[AC3_MAX_CHANNELS];
68
    uint8_t  grouped_exp[AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
69
    int16_t  psd[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
70
    int16_t  band_psd[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
71
    int16_t  mask[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
72
    int8_t   exp_shift[AC3_MAX_CHANNELS];
73
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
74
} AC3Block;
75

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

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

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

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

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

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

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

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

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

    
123
    int16_t **planar_samples;
124
    uint8_t *bap_buffer;
125
    uint8_t *bap1_buffer;
126

    
127
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
128
} AC3EncodeContext;
129

    
130

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

    
137

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

    
154

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

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

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

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

    
183

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

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

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

    
203

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

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

    
215
    fft_init(nbits - 2);
216

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

    
224

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

    
239

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

    
247

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

    
260
    np = 1 << ln;
261

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

    
269
    /* pass 0 */
270

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

    
279
    /* pass 1 */
280

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

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

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

    
319

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

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

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

    
344
    fft(x, MDCT_NBITS - 2);
345

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

    
356

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

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

    
372

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

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

    
387
    return av_log2(v);
388
}
389

    
390

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

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

    
411

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

    
427

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

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

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

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

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

    
451

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

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

    
482

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

    
495

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

    
502

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

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

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

    
539

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

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

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

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

    
569

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

    
584

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

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

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

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

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

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

    
634

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

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

    
674

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

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

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

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

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

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

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

    
727
    s->exponent_bits = bit_count;
728
}
729

    
730

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

    
740
    compute_exp_strategy(s);
741

    
742
    encode_exponents(s);
743

    
744
    group_exponents(s);
745
}
746

    
747

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

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

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

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

    
778

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

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

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

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

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

    
824
    s->frame_bits = frame_bits;
825
}
826

    
827

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

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

    
880

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

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

    
911

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

    
928

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

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

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

    
962

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

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

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

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

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

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

    
1012
    return 0;
1013
}
1014

    
1015

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

    
1026
    bit_alloc_masking(s);
1027

    
1028
    return cbr_bit_allocation(s);
1029
}
1030

    
1031

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

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

    
1052

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

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

    
1074

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

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

    
1169

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

    
1177

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

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

    
1191

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

    
1222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1339

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

    
1343

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

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

    
1360

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

    
1374

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

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

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

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

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

    
1410

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

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

    
1421
    output_frame_header(s);
1422

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

    
1426
    output_frame_end(s);
1427
}
1428

    
1429

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

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

    
1443
    deinterleave_input_samples(s, samples);
1444

    
1445
    apply_mdct(s);
1446

    
1447
    process_exponents(s);
1448

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

    
1455
    quantize_mantissas(s);
1456

    
1457
    output_frame(s, frame);
1458

    
1459
    return s->frame_size;
1460
}
1461

    
1462

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

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

    
1481
    av_freep(&avctx->coded_frame);
1482
    return 0;
1483
}
1484

    
1485

    
1486
/**
1487
 * Set channel information during initialization.
1488
 */
1489
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1490
                                    int64_t *channel_layout)
1491
{
1492
    int ch_layout;
1493

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

    
1504
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1505
    s->channels     = channels;
1506
    s->fbw_channels = channels - s->lfe_on;
1507
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1508
    if (s->lfe_on)
1509
        ch_layout -= AV_CH_LOW_FREQUENCY;
1510

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

    
1525
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1526
    *channel_layout = ch_layout;
1527
    if (s->lfe_on)
1528
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1529

    
1530
    return 0;
1531
}
1532

    
1533

    
1534
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1535
{
1536
    int i, ret;
1537

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

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

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

    
1575
    return 0;
1576
}
1577

    
1578

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

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

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

    
1610

    
1611
static av_cold int allocate_buffers(AVCodecContext *avctx)
1612
{
1613
    int blk, ch;
1614
    AC3EncodeContext *s = avctx->priv_data;
1615

    
1616
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1617
                     alloc_fail);
1618
    for (ch = 0; ch < s->channels; ch++) {
1619
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1620
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1621
                          alloc_fail);
1622
    }
1623
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1624
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1625
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1626
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1627
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1628
        AC3Block *block = &s->blocks[blk];
1629
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1630
                         alloc_fail);
1631
    }
1632
    s->blocks[0].bap[0] = NULL;
1633
    reset_block_bap(s);
1634

    
1635
    return 0;
1636
alloc_fail:
1637
    return AVERROR(ENOMEM);
1638
}
1639

    
1640

    
1641
/**
1642
 * Initialize the encoder.
1643
 */
1644
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1645
{
1646
    AC3EncodeContext *s = avctx->priv_data;
1647
    int ret;
1648

    
1649
    avctx->frame_size = AC3_FRAME_SIZE;
1650

    
1651
    ac3_common_init();
1652

    
1653
    ret = validate_options(avctx, s);
1654
    if (ret)
1655
        return ret;
1656

    
1657
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1658
    s->bitstream_mode = 0; /* complete main audio service */
1659

    
1660
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1661
    s->bits_written    = 0;
1662
    s->samples_written = 0;
1663
    s->frame_size      = s->frame_size_min;
1664

    
1665
    set_bandwidth(s, avctx->cutoff);
1666

    
1667
    bit_alloc_init(s);
1668

    
1669
    mdct_init(9);
1670

    
1671
    ret = allocate_buffers(avctx);
1672
    if (ret) {
1673
        ac3_encode_close(avctx);
1674
        return ret;
1675
    }
1676

    
1677
    avctx->coded_frame= avcodec_alloc_frame();
1678

    
1679
    return 0;
1680
}
1681

    
1682

    
1683
#ifdef TEST
1684
/*************************************************************************/
1685
/* TEST */
1686

    
1687
#include "libavutil/lfg.h"
1688

    
1689
#define FN (MDCT_SAMPLES/4)
1690

    
1691

    
1692
static void fft_test(AVLFG *lfg)
1693
{
1694
    IComplex in[FN], in1[FN];
1695
    int k, n, i;
1696
    float sum_re, sum_im, a;
1697

    
1698
    for (i = 0; i < FN; i++) {
1699
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1700
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1701
        in1[i]   = in[i];
1702
    }
1703
    fft(in, 7);
1704

    
1705
    /* do it by hand */
1706
    for (k = 0; k < FN; k++) {
1707
        sum_re = 0;
1708
        sum_im = 0;
1709
        for (n = 0; n < FN; n++) {
1710
            a = -2 * M_PI * (n * k) / FN;
1711
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1712
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1713
        }
1714
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1715
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1716
    }
1717
}
1718

    
1719

    
1720
static void mdct_test(AVLFG *lfg)
1721
{
1722
    int16_t input[MDCT_SAMPLES];
1723
    int32_t output[AC3_MAX_COEFS];
1724
    float input1[MDCT_SAMPLES];
1725
    float output1[AC3_MAX_COEFS];
1726
    float s, a, err, e, emax;
1727
    int i, k, n;
1728

    
1729
    for (i = 0; i < MDCT_SAMPLES; i++) {
1730
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1731
        input1[i] = input[i];
1732
    }
1733

    
1734
    mdct512(output, input);
1735

    
1736
    /* do it by hand */
1737
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1738
        s = 0;
1739
        for (n = 0; n < MDCT_SAMPLES; n++) {
1740
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1741
            s += input1[n] * cos(a);
1742
        }
1743
        output1[k] = -2 * s / MDCT_SAMPLES;
1744
    }
1745

    
1746
    err  = 0;
1747
    emax = 0;
1748
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1749
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1750
        e = output[i] - output1[i];
1751
        if (e > emax)
1752
            emax = e;
1753
        err += e * e;
1754
    }
1755
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1756
}
1757

    
1758

    
1759
int main(void)
1760
{
1761
    AVLFG lfg;
1762

    
1763
    av_log_set_level(AV_LOG_DEBUG);
1764
    mdct_init(9);
1765

    
1766
    fft_test(&lfg);
1767
    mdct_test(&lfg);
1768

    
1769
    return 0;
1770
}
1771
#endif /* TEST */
1772

    
1773

    
1774
AVCodec ac3_encoder = {
1775
    "ac3",
1776
    AVMEDIA_TYPE_AUDIO,
1777
    CODEC_ID_AC3,
1778
    sizeof(AC3EncodeContext),
1779
    ac3_encode_init,
1780
    ac3_encode_frame,
1781
    ac3_encode_close,
1782
    NULL,
1783
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1784
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1785
    .channel_layouts = (const int64_t[]){
1786
        AV_CH_LAYOUT_MONO,
1787
        AV_CH_LAYOUT_STEREO,
1788
        AV_CH_LAYOUT_2_1,
1789
        AV_CH_LAYOUT_SURROUND,
1790
        AV_CH_LAYOUT_2_2,
1791
        AV_CH_LAYOUT_QUAD,
1792
        AV_CH_LAYOUT_4POINT0,
1793
        AV_CH_LAYOUT_5POINT0,
1794
        AV_CH_LAYOUT_5POINT0_BACK,
1795
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1796
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1797
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1798
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1799
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1800
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1801
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1802
        AV_CH_LAYOUT_5POINT1,
1803
        AV_CH_LAYOUT_5POINT1_BACK,
1804
        0 },
1805
};