Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ d7da8080

History | View | Annotate | Download (51.7 KB)

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

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

    
27
//#define DEBUG
28

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

    
36

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

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

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

    
46

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

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

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

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

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

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

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

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

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

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

    
100

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

    
107

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

    
123

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

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

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

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

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

    
157

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

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

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

    
177

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

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

    
189
    fft_init(nbits - 2);
190

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

    
198

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

    
213

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

    
221

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

    
234
    np = 1 << ln;
235

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

    
243
    /* pass 0 */
244

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

    
253
    /* pass 1 */
254

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

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

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

    
293

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

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

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

    
318
    fft(x, MDCT_NBITS - 2);
319

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

    
330

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

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

    
346

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

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

    
361
    return av_log2(v);
362
}
363

    
364

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

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

    
385

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

    
402

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

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

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

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

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

    
429

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

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

    
464

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

    
477

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

    
484

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

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

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

    
521

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

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

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

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

    
553

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

    
568

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

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

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

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

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

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

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

    
620

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

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

    
658
    return frame_bits;
659
}
660

    
661

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

    
677
    compute_exp_strategy(s, exp_strategy, exp);
678

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

    
682

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

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

    
735

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

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

    
769

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

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

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

    
803

    
804
#define SNR_INC1 4
805

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

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

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

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

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

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

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

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

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

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

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

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

    
923
    return 0;
924
}
925

    
926

    
927
/**
928
 * Write the AC-3 frame header to the output bitstream.
929
 */
930
static void output_frame_header(AC3EncodeContext *s)
931
{
932
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
933
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
934
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
935
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
936
    put_bits(&s->pb, 5,  s->bitstream_id);
937
    put_bits(&s->pb, 3,  s->bitstream_mode);
938
    put_bits(&s->pb, 3,  s->channel_mode);
939
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
940
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
941
    if (s->channel_mode & 0x04)
942
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
943
    if (s->channel_mode == AC3_CHMODE_STEREO)
944
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
945
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
946
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
947
    put_bits(&s->pb, 1, 0);         /* no compression control word */
948
    put_bits(&s->pb, 1, 0);         /* no lang code */
949
    put_bits(&s->pb, 1, 0);         /* no audio production info */
950
    put_bits(&s->pb, 1, 0);         /* no copyright */
951
    put_bits(&s->pb, 1, 1);         /* original bitstream */
952
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
953
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
954
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
955
}
956

    
957

    
958
/**
959
 * Symmetric quantization on 'levels' levels.
960
 */
961
static inline int sym_quant(int c, int e, int levels)
962
{
963
    int v;
964

    
965
    if (c >= 0) {
966
        v = (levels * (c << e)) >> 24;
967
        v = (v + 1) >> 1;
968
        v = (levels >> 1) + v;
969
    } else {
970
        v = (levels * ((-c) << e)) >> 24;
971
        v = (v + 1) >> 1;
972
        v = (levels >> 1) - v;
973
    }
974
    assert (v >= 0 && v < levels);
975
    return v;
976
}
977

    
978

    
979
/**
980
 * Asymmetric quantization on 2^qbits levels.
981
 */
982
static inline int asym_quant(int c, int e, int qbits)
983
{
984
    int lshift, m, v;
985

    
986
    lshift = e + qbits - 24;
987
    if (lshift >= 0)
988
        v = c << lshift;
989
    else
990
        v = c >> (-lshift);
991
    /* rounding */
992
    v = (v + 1) >> 1;
993
    m = (1 << (qbits-1));
994
    if (v >= m)
995
        v = m - 1;
996
    assert(v >= -m);
997
    return v & ((1 << qbits)-1);
998
}
999

    
1000

    
1001
/**
1002
 * Write one audio block to the output bitstream.
1003
 */
1004
static void output_audio_block(AC3EncodeContext *s,
1005
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
1006
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1007
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1008
                               int32_t mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1009
                               int8_t exp_shift[AC3_MAX_CHANNELS],
1010
                               int block_num)
1011
{
1012
    int ch, nb_groups, group_size, i, baie, rbnd;
1013
    uint8_t *p;
1014
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1015
    int exp0, exp1;
1016
    int mant1_cnt, mant2_cnt, mant4_cnt;
1017
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
1018
    int delta0, delta1, delta2;
1019

    
1020
    for (ch = 0; ch < s->fbw_channels; ch++)
1021
        put_bits(&s->pb, 1, 0); /* no block switching */
1022
    for (ch = 0; ch < s->fbw_channels; ch++)
1023
        put_bits(&s->pb, 1, 1); /* no dither */
1024
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
1025
    if (!block_num) {
1026
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1027
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1028
    } else {
1029
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1030
    }
1031

    
1032
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1033
        if (!block_num) {
1034
            /* first block must define rematrixing (rematstr) */
1035
            put_bits(&s->pb, 1, 1);
1036

    
1037
            /* dummy rematrixing rematflg(1:4)=0 */
1038
            for (rbnd = 0; rbnd < 4; rbnd++)
1039
                put_bits(&s->pb, 1, 0);
1040
        } else {
1041
            /* no matrixing (but should be used in the future) */
1042
            put_bits(&s->pb, 1, 0);
1043
        }
1044
    }
1045

    
1046
    /* exponent strategy */
1047
    for (ch = 0; ch < s->fbw_channels; ch++)
1048
        put_bits(&s->pb, 2, exp_strategy[ch]);
1049

    
1050
    if (s->lfe_on)
1051
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1052

    
1053
    /* bandwidth */
1054
    for (ch = 0; ch < s->fbw_channels; ch++) {
1055
        if (exp_strategy[ch] != EXP_REUSE)
1056
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1057
    }
1058

    
1059
    /* exponents */
1060
    for (ch = 0; ch < s->channels; ch++) {
1061
        if (exp_strategy[ch] == EXP_REUSE)
1062
            continue;
1063
        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
1064
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1065
        p = encoded_exp[ch];
1066

    
1067
        /* first exponent */
1068
        exp1 = *p++;
1069
        put_bits(&s->pb, 4, exp1);
1070

    
1071
        /* next ones are delta encoded */
1072
        for (i = 0; i < nb_groups; i++) {
1073
            /* merge three delta in one code */
1074
            exp0   = exp1;
1075
            exp1   = p[0];
1076
            p     += group_size;
1077
            delta0 = exp1 - exp0 + 2;
1078

    
1079
            exp0   = exp1;
1080
            exp1   = p[0];
1081
            p     += group_size;
1082
            delta1 = exp1 - exp0 + 2;
1083

    
1084
            exp0   = exp1;
1085
            exp1   = p[0];
1086
            p     += group_size;
1087
            delta2 = exp1 - exp0 + 2;
1088

    
1089
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1090
        }
1091

    
1092
        if (ch != s->lfe_channel)
1093
            put_bits(&s->pb, 2, 0); /* no gain range info */
1094
    }
1095

    
1096
    /* bit allocation info */
1097
    baie = (block_num == 0);
1098
    put_bits(&s->pb, 1, baie);
1099
    if (baie) {
1100
        put_bits(&s->pb, 2, s->slow_decay_code);
1101
        put_bits(&s->pb, 2, s->fast_decay_code);
1102
        put_bits(&s->pb, 2, s->slow_gain_code);
1103
        put_bits(&s->pb, 2, s->db_per_bit_code);
1104
        put_bits(&s->pb, 3, s->floor_code);
1105
    }
1106

    
1107
    /* snr offset */
1108
    put_bits(&s->pb, 1, baie);
1109
    if (baie) {
1110
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1111
        for (ch = 0; ch < s->channels; ch++) {
1112
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1113
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1114
        }
1115
    }
1116

    
1117
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1118
    put_bits(&s->pb, 1, 0); /* no data to skip */
1119

    
1120
    /* mantissa encoding : we use two passes to handle the grouping. A
1121
       one pass method may be faster, but it would necessitate to
1122
       modify the output stream. */
1123

    
1124
    /* first pass: quantize */
1125
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
1126
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1127

    
1128
    for (ch = 0; ch < s->channels; ch++) {
1129
        int b, c, e, v;
1130

    
1131
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1132
            c = mdct_coef[ch][i];
1133
            e = encoded_exp[ch][i] - exp_shift[ch];
1134
            b = bap[ch][i];
1135
            switch (b) {
1136
            case 0:
1137
                v = 0;
1138
                break;
1139
            case 1:
1140
                v = sym_quant(c, e, 3);
1141
                switch (mant1_cnt) {
1142
                case 0:
1143
                    qmant1_ptr = &qmant[ch][i];
1144
                    v = 9 * v;
1145
                    mant1_cnt = 1;
1146
                    break;
1147
                case 1:
1148
                    *qmant1_ptr += 3 * v;
1149
                    mant1_cnt = 2;
1150
                    v = 128;
1151
                    break;
1152
                default:
1153
                    *qmant1_ptr += v;
1154
                    mant1_cnt = 0;
1155
                    v = 128;
1156
                    break;
1157
                }
1158
                break;
1159
            case 2:
1160
                v = sym_quant(c, e, 5);
1161
                switch (mant2_cnt) {
1162
                case 0:
1163
                    qmant2_ptr = &qmant[ch][i];
1164
                    v = 25 * v;
1165
                    mant2_cnt = 1;
1166
                    break;
1167
                case 1:
1168
                    *qmant2_ptr += 5 * v;
1169
                    mant2_cnt = 2;
1170
                    v = 128;
1171
                    break;
1172
                default:
1173
                    *qmant2_ptr += v;
1174
                    mant2_cnt = 0;
1175
                    v = 128;
1176
                    break;
1177
                }
1178
                break;
1179
            case 3:
1180
                v = sym_quant(c, e, 7);
1181
                break;
1182
            case 4:
1183
                v = sym_quant(c, e, 11);
1184
                switch (mant4_cnt) {
1185
                case 0:
1186
                    qmant4_ptr = &qmant[ch][i];
1187
                    v = 11 * v;
1188
                    mant4_cnt = 1;
1189
                    break;
1190
                default:
1191
                    *qmant4_ptr += v;
1192
                    mant4_cnt = 0;
1193
                    v = 128;
1194
                    break;
1195
                }
1196
                break;
1197
            case 5:
1198
                v = sym_quant(c, e, 15);
1199
                break;
1200
            case 14:
1201
                v = asym_quant(c, e, 14);
1202
                break;
1203
            case 15:
1204
                v = asym_quant(c, e, 16);
1205
                break;
1206
            default:
1207
                v = asym_quant(c, e, b - 1);
1208
                break;
1209
            }
1210
            qmant[ch][i] = v;
1211
        }
1212
    }
1213

    
1214
    /* second pass : output the values */
1215
    for (ch = 0; ch < s->channels; ch++) {
1216
        int b, q;
1217

    
1218
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1219
            q = qmant[ch][i];
1220
            b = bap[ch][i];
1221
            switch (b) {
1222
            case 0:                                         break;
1223
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1224
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1225
            case 3:               put_bits(&s->pb,   3, q); break;
1226
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1227
            case 14:              put_bits(&s->pb,  14, q); break;
1228
            case 15:              put_bits(&s->pb,  16, q); break;
1229
            default:              put_bits(&s->pb, b-1, q); break;
1230
            }
1231
        }
1232
    }
1233
}
1234

    
1235

    
1236
/** CRC-16 Polynomial */
1237
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1238

    
1239

    
1240
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1241
{
1242
    unsigned int c;
1243

    
1244
    c = 0;
1245
    while (a) {
1246
        if (a & 1)
1247
            c ^= b;
1248
        a = a >> 1;
1249
        b = b << 1;
1250
        if (b & (1 << 16))
1251
            b ^= poly;
1252
    }
1253
    return c;
1254
}
1255

    
1256

    
1257
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1258
{
1259
    unsigned int r;
1260
    r = 1;
1261
    while (n) {
1262
        if (n & 1)
1263
            r = mul_poly(r, a, poly);
1264
        a = mul_poly(a, a, poly);
1265
        n >>= 1;
1266
    }
1267
    return r;
1268
}
1269

    
1270

    
1271
/**
1272
 * Fill the end of the frame with 0's and compute the two CRCs.
1273
 */
1274
static void output_frame_end(AC3EncodeContext *s)
1275
{
1276
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1277
    uint8_t *frame;
1278

    
1279
    frame_size = s->frame_size; /* frame size in words */
1280
    /* align to 8 bits */
1281
    flush_put_bits(&s->pb);
1282
    /* add zero bytes to reach the frame size */
1283
    frame = s->pb.buf;
1284
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1285
    assert(pad_bytes >= 0);
1286
    if (pad_bytes > 0)
1287
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1288

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

    
1293
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1294
                             frame + 4, frame_size_58 - 4));
1295

    
1296
    /* XXX: could precompute crc_inv */
1297
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1298
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1299
    AV_WB16(frame + 2, crc1);
1300

    
1301
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1302
                             frame + frame_size_58,
1303
                             frame_size - frame_size_58 - 2));
1304
    AV_WB16(frame + frame_size - 2, crc2);
1305
}
1306

    
1307

    
1308
/**
1309
 * Write the frame to the output bitstream.
1310
 */
1311
static void output_frame(AC3EncodeContext *s,
1312
                         unsigned char *frame,
1313
                         uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1314
                         uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1315
                         uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1316
                         int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1317
                         int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS])
1318
{
1319
    int blk;
1320

    
1321
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1322

    
1323
    output_frame_header(s);
1324

    
1325
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1326
        output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
1327
                           bap[blk], mdct_coef[blk], exp_shift[blk], blk);
1328
    }
1329

    
1330
    output_frame_end(s);
1331
}
1332

    
1333

    
1334
/**
1335
 * Encode a single AC-3 frame.
1336
 */
1337
static int ac3_encode_frame(AVCodecContext *avctx,
1338
                            unsigned char *frame, int buf_size, void *data)
1339
{
1340
    AC3EncodeContext *s = avctx->priv_data;
1341
    const int16_t *samples = data;
1342
    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
1343
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1344
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1345
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1346
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1347
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1348
    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1349
    int frame_bits;
1350

    
1351
    if (s->bit_alloc.sr_code == 1)
1352
        adjust_frame_size(s);
1353

    
1354
    deinterleave_input_samples(s, samples, planar_samples);
1355

    
1356
    apply_mdct(s, planar_samples, exp_shift, mdct_coef);
1357

    
1358
    frame_bits = process_exponents(s, mdct_coef, exp_shift, exp, exp_strategy, encoded_exp);
1359

    
1360
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1361

    
1362
    output_frame(s, frame, exp_strategy, encoded_exp, bap, mdct_coef, exp_shift);
1363

    
1364
    return s->frame_size;
1365
}
1366

    
1367

    
1368
/**
1369
 * Finalize encoding and free any memory allocated by the encoder.
1370
 */
1371
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1372
{
1373
    av_freep(&avctx->coded_frame);
1374
    return 0;
1375
}
1376

    
1377

    
1378
/**
1379
 * Set channel information during initialization.
1380
 */
1381
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1382
                                    int64_t *channel_layout)
1383
{
1384
    int ch_layout;
1385

    
1386
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1387
        return AVERROR(EINVAL);
1388
    if ((uint64_t)*channel_layout > 0x7FF)
1389
        return AVERROR(EINVAL);
1390
    ch_layout = *channel_layout;
1391
    if (!ch_layout)
1392
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1393
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1394
        return AVERROR(EINVAL);
1395

    
1396
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1397
    s->channels     = channels;
1398
    s->fbw_channels = channels - s->lfe_on;
1399
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1400
    if (s->lfe_on)
1401
        ch_layout -= AV_CH_LOW_FREQUENCY;
1402

    
1403
    switch (ch_layout) {
1404
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1405
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1406
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1407
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1408
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1409
    case AV_CH_LAYOUT_QUAD:
1410
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1411
    case AV_CH_LAYOUT_5POINT0:
1412
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1413
    default:
1414
        return AVERROR(EINVAL);
1415
    }
1416

    
1417
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1418
    *channel_layout = ch_layout;
1419
    if (s->lfe_on)
1420
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1421

    
1422
    return 0;
1423
}
1424

    
1425

    
1426
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1427
{
1428
    int i, ret;
1429

    
1430
    /* validate channel layout */
1431
    if (!avctx->channel_layout) {
1432
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1433
                                      "encoder will guess the layout, but it "
1434
                                      "might be incorrect.\n");
1435
    }
1436
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1437
    if (ret) {
1438
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1439
        return ret;
1440
    }
1441

    
1442
    /* validate sample rate */
1443
    for (i = 0; i < 9; i++) {
1444
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1445
            break;
1446
    }
1447
    if (i == 9) {
1448
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1449
        return AVERROR(EINVAL);
1450
    }
1451
    s->sample_rate        = avctx->sample_rate;
1452
    s->bit_alloc.sr_shift = i % 3;
1453
    s->bit_alloc.sr_code  = i / 3;
1454

    
1455
    /* validate bit rate */
1456
    for (i = 0; i < 19; i++) {
1457
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1458
            break;
1459
    }
1460
    if (i == 19) {
1461
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1462
        return AVERROR(EINVAL);
1463
    }
1464
    s->bit_rate        = avctx->bit_rate;
1465
    s->frame_size_code = i << 1;
1466

    
1467
    return 0;
1468
}
1469

    
1470

    
1471
/**
1472
 * Set bandwidth for all channels.
1473
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1474
 * default value will be used.
1475
 */
1476
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1477
{
1478
    int ch, bw_code;
1479

    
1480
    if (cutoff) {
1481
        /* calculate bandwidth based on user-specified cutoff frequency */
1482
        int fbw_coeffs;
1483
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1484
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1485
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1486
    } else {
1487
        /* use default bandwidth setting */
1488
        /* XXX: should compute the bandwidth according to the frame
1489
           size, so that we avoid annoying high frequency artifacts */
1490
        bw_code = 50;
1491
    }
1492

    
1493
    /* set number of coefficients for each channel */
1494
    for (ch = 0; ch < s->fbw_channels; ch++) {
1495
        s->bandwidth_code[ch] = bw_code;
1496
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1497
    }
1498
    if (s->lfe_on)
1499
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1500
}
1501

    
1502

    
1503
/**
1504
 * Initialize the encoder.
1505
 */
1506
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1507
{
1508
    AC3EncodeContext *s = avctx->priv_data;
1509
    int ret;
1510

    
1511
    avctx->frame_size = AC3_FRAME_SIZE;
1512

    
1513
    ac3_common_init();
1514

    
1515
    ret = validate_options(avctx, s);
1516
    if (ret)
1517
        return ret;
1518

    
1519
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1520
    s->bitstream_mode = 0; /* complete main audio service */
1521

    
1522
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1523
    s->bits_written    = 0;
1524
    s->samples_written = 0;
1525
    s->frame_size      = s->frame_size_min;
1526

    
1527
    set_bandwidth(s, avctx->cutoff);
1528

    
1529
    /* initial snr offset */
1530
    s->coarse_snr_offset = 40;
1531

    
1532
    mdct_init(9);
1533

    
1534
    avctx->coded_frame= avcodec_alloc_frame();
1535
    avctx->coded_frame->key_frame= 1;
1536

    
1537
    return 0;
1538
}
1539

    
1540

    
1541
#ifdef TEST
1542
/*************************************************************************/
1543
/* TEST */
1544

    
1545
#include "libavutil/lfg.h"
1546

    
1547
#define FN (MDCT_SAMPLES/4)
1548

    
1549

    
1550
static void fft_test(AVLFG *lfg)
1551
{
1552
    IComplex in[FN], in1[FN];
1553
    int k, n, i;
1554
    float sum_re, sum_im, a;
1555

    
1556
    for (i = 0; i < FN; i++) {
1557
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1558
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1559
        in1[i]   = in[i];
1560
    }
1561
    fft(in, 7);
1562

    
1563
    /* do it by hand */
1564
    for (k = 0; k < FN; k++) {
1565
        sum_re = 0;
1566
        sum_im = 0;
1567
        for (n = 0; n < FN; n++) {
1568
            a = -2 * M_PI * (n * k) / FN;
1569
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1570
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1571
        }
1572
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1573
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1574
    }
1575
}
1576

    
1577

    
1578
static void mdct_test(AVLFG *lfg)
1579
{
1580
    int16_t input[MDCT_SAMPLES];
1581
    int32_t output[AC3_MAX_COEFS];
1582
    float input1[MDCT_SAMPLES];
1583
    float output1[AC3_MAX_COEFS];
1584
    float s, a, err, e, emax;
1585
    int i, k, n;
1586

    
1587
    for (i = 0; i < MDCT_SAMPLES; i++) {
1588
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1589
        input1[i] = input[i];
1590
    }
1591

    
1592
    mdct512(output, input);
1593

    
1594
    /* do it by hand */
1595
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1596
        s = 0;
1597
        for (n = 0; n < MDCT_SAMPLES; n++) {
1598
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1599
            s += input1[n] * cos(a);
1600
        }
1601
        output1[k] = -2 * s / MDCT_SAMPLES;
1602
    }
1603

    
1604
    err  = 0;
1605
    emax = 0;
1606
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1607
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1608
        e = output[i] - output1[i];
1609
        if (e > emax)
1610
            emax = e;
1611
        err += e * e;
1612
    }
1613
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1614
}
1615

    
1616

    
1617
int main(void)
1618
{
1619
    AVLFG lfg;
1620

    
1621
    av_log_set_level(AV_LOG_DEBUG);
1622
    mdct_init(9);
1623

    
1624
    fft_test(&lfg);
1625
    mdct_test(&lfg);
1626

    
1627
    return 0;
1628
}
1629
#endif /* TEST */
1630

    
1631

    
1632
AVCodec ac3_encoder = {
1633
    "ac3",
1634
    AVMEDIA_TYPE_AUDIO,
1635
    CODEC_ID_AC3,
1636
    sizeof(AC3EncodeContext),
1637
    ac3_encode_init,
1638
    ac3_encode_frame,
1639
    ac3_encode_close,
1640
    NULL,
1641
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1642
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1643
    .channel_layouts = (const int64_t[]){
1644
        AV_CH_LAYOUT_MONO,
1645
        AV_CH_LAYOUT_STEREO,
1646
        AV_CH_LAYOUT_2_1,
1647
        AV_CH_LAYOUT_SURROUND,
1648
        AV_CH_LAYOUT_2_2,
1649
        AV_CH_LAYOUT_QUAD,
1650
        AV_CH_LAYOUT_4POINT0,
1651
        AV_CH_LAYOUT_5POINT0,
1652
        AV_CH_LAYOUT_5POINT0_BACK,
1653
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1654
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1655
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1656
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1657
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1658
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1659
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1660
        AV_CH_LAYOUT_5POINT1,
1661
        AV_CH_LAYOUT_5POINT1_BACK,
1662
        0 },
1663
};