Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 1fda2c10

History | View | Annotate | Download (42.2 KB)

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

    
22
/**
23
 * @file
24
 * The simplest AC-3 encoder.
25
 */
26
//#define DEBUG
27
//#define DEBUG_BITALLOC
28
#include "libavcore/audioconvert.h"
29
#include "libavutil/crc.h"
30
#include "avcodec.h"
31
#include "libavutil/common.h" /* for av_reverse */
32
#include "put_bits.h"
33
#include "ac3.h"
34
#include "audioconvert.h"
35

    
36
typedef struct AC3EncodeContext {
37
    PutBitContext pb;
38

    
39
    int bitstream_id;
40
    int bitstream_mode;
41

    
42
    int bit_rate;
43
    int sample_rate;
44

    
45
    int frame_size_min; /* minimum frame size in case rounding is necessary */
46
    int frame_size; /* current frame size in words */
47
    int frame_size_code;
48
    int bits_written;
49
    int samples_written;
50

    
51
    int fbw_channels;
52
    int channels;
53
    int lfe_on;
54
    int lfe_channel;
55
    int channel_mode;
56
    const uint8_t *channel_map;
57

    
58
    int bandwidth_code[AC3_MAX_CHANNELS];
59
    int nb_coefs[AC3_MAX_CHANNELS];
60

    
61
    /* bitrate allocation control */
62
    int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
63
    AC3BitAllocParameters bit_alloc;
64
    int coarse_snr_offset;
65
    int fast_gain_code[AC3_MAX_CHANNELS];
66
    int fine_snr_offset[AC3_MAX_CHANNELS];
67

    
68
    /* mantissa encoding */
69
    int mant1_cnt, mant2_cnt, mant4_cnt;
70

    
71
    int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE];
72
} AC3EncodeContext;
73

    
74
static int16_t costab[64];
75
static int16_t sintab[64];
76
static int16_t xcos1[128];
77
static int16_t xsin1[128];
78

    
79
#define MDCT_NBITS 9
80
#define MDCT_SAMPLES (1 << MDCT_NBITS)
81

    
82
/* new exponents are sent if their Norm 1 exceed this number */
83
#define EXP_DIFF_THRESHOLD 1000
84

    
85
static inline int16_t fix15(float a)
86
{
87
    int v;
88
    v = (int)(a * (float)(1 << 15));
89
    if (v < -32767)
90
        v = -32767;
91
    else if (v > 32767)
92
        v = 32767;
93
    return v;
94
}
95

    
96
typedef struct IComplex {
97
    int16_t re,im;
98
} IComplex;
99

    
100
static av_cold void fft_init(int ln)
101
{
102
    int i, n;
103
    float alpha;
104

    
105
    n = 1 << ln;
106

    
107
    for(i=0;i<(n/2);i++) {
108
        alpha = 2 * M_PI * (float)i / (float)n;
109
        costab[i] = fix15(cos(alpha));
110
        sintab[i] = fix15(sin(alpha));
111
    }
112
}
113

    
114
/* butter fly op */
115
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
116
{\
117
  int ax, ay, bx, by;\
118
  bx=pre1;\
119
  by=pim1;\
120
  ax=qre1;\
121
  ay=qim1;\
122
  pre = (bx + ax) >> 1;\
123
  pim = (by + ay) >> 1;\
124
  qre = (bx - ax) >> 1;\
125
  qim = (by - ay) >> 1;\
126
}
127

    
128
#define CMUL(pre, pim, are, aim, bre, bim) \
129
{\
130
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
131
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
132
}
133

    
134

    
135
/* do a 2^n point complex fft on 2^ln points. */
136
static void fft(IComplex *z, int ln)
137
{
138
    int        j, l, np, np2;
139
    int        nblocks, nloops;
140
    register IComplex *p,*q;
141
    int tmp_re, tmp_im;
142

    
143
    np = 1 << ln;
144

    
145
    /* reverse */
146
    for(j=0;j<np;j++) {
147
        int k = av_reverse[j] >> (8 - ln);
148
        if (k < j)
149
            FFSWAP(IComplex, z[k], z[j]);
150
    }
151

    
152
    /* pass 0 */
153

    
154
    p=&z[0];
155
    j=(np >> 1);
156
    do {
157
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
158
           p[0].re, p[0].im, p[1].re, p[1].im);
159
        p+=2;
160
    } while (--j != 0);
161

    
162
    /* pass 1 */
163

    
164
    p=&z[0];
165
    j=np >> 2;
166
    do {
167
        BF(p[0].re, p[0].im, p[2].re, p[2].im,
168
           p[0].re, p[0].im, p[2].re, p[2].im);
169
        BF(p[1].re, p[1].im, p[3].re, p[3].im,
170
           p[1].re, p[1].im, p[3].im, -p[3].re);
171
        p+=4;
172
    } while (--j != 0);
173

    
174
    /* pass 2 .. ln-1 */
175

    
176
    nblocks = np >> 3;
177
    nloops = 1 << 2;
178
    np2 = np >> 1;
179
    do {
180
        p = z;
181
        q = z + nloops;
182
        for (j = 0; j < nblocks; ++j) {
183

    
184
            BF(p->re, p->im, q->re, q->im,
185
               p->re, p->im, q->re, q->im);
186

    
187
            p++;
188
            q++;
189
            for(l = nblocks; l < np2; l += nblocks) {
190
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
191
                BF(p->re, p->im, q->re, q->im,
192
                   p->re, p->im, tmp_re, tmp_im);
193
                p++;
194
                q++;
195
            }
196
            p += nloops;
197
            q += nloops;
198
        }
199
        nblocks = nblocks >> 1;
200
        nloops = nloops << 1;
201
    } while (nblocks != 0);
202
}
203

    
204
/* do a 512 point mdct */
205
static void mdct512(int32_t *out, int16_t *in)
206
{
207
    int i, re, im, re1, im1;
208
    int16_t rot[MDCT_SAMPLES];
209
    IComplex x[MDCT_SAMPLES/4];
210

    
211
    /* shift to simplify computations */
212
    for(i=0;i<MDCT_SAMPLES/4;i++)
213
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
214
    for(i=MDCT_SAMPLES/4;i<MDCT_SAMPLES;i++)
215
        rot[i] = in[i - MDCT_SAMPLES/4];
216

    
217
    /* pre rotation */
218
    for(i=0;i<MDCT_SAMPLES/4;i++) {
219
        re = ((int)rot[2*i] - (int)rot[MDCT_SAMPLES-1-2*i]) >> 1;
220
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
221
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
222
    }
223

    
224
    fft(x, MDCT_NBITS - 2);
225

    
226
    /* post rotation */
227
    for(i=0;i<MDCT_SAMPLES/4;i++) {
228
        re = x[i].re;
229
        im = x[i].im;
230
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
231
        out[2*i] = im1;
232
        out[MDCT_SAMPLES/2-1-2*i] = re1;
233
    }
234
}
235

    
236
/* XXX: use another norm ? */
237
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
238
{
239
    int sum, i;
240
    sum = 0;
241
    for(i=0;i<n;i++) {
242
        sum += abs(exp1[i] - exp2[i]);
243
    }
244
    return sum;
245
}
246

    
247
static void compute_exp_strategy(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
248
                                 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
249
                                 int ch, int is_lfe)
250
{
251
    int i, j;
252
    int exp_diff;
253

    
254
    /* estimate if the exponent variation & decide if they should be
255
       reused in the next frame */
256
    exp_strategy[0][ch] = EXP_NEW;
257
    for(i=1;i<AC3_MAX_BLOCKS;i++) {
258
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], AC3_MAX_COEFS);
259
        dprintf(NULL, "exp_diff=%d\n", exp_diff);
260
        if (exp_diff > EXP_DIFF_THRESHOLD)
261
            exp_strategy[i][ch] = EXP_NEW;
262
        else
263
            exp_strategy[i][ch] = EXP_REUSE;
264
    }
265
    if (is_lfe)
266
        return;
267

    
268
    /* now select the encoding strategy type : if exponents are often
269
       recoded, we use a coarse encoding */
270
    i = 0;
271
    while (i < AC3_MAX_BLOCKS) {
272
        j = i + 1;
273
        while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
274
            j++;
275
        switch(j - i) {
276
        case 1:
277
            exp_strategy[i][ch] = EXP_D45;
278
            break;
279
        case 2:
280
        case 3:
281
            exp_strategy[i][ch] = EXP_D25;
282
            break;
283
        default:
284
            exp_strategy[i][ch] = EXP_D15;
285
            break;
286
        }
287
        i = j;
288
    }
289
}
290

    
291
/* set exp[i] to min(exp[i], exp1[i]) */
292
static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
293
{
294
    int i;
295

    
296
    for(i=0;i<n;i++) {
297
        if (exp1[i] < exp[i])
298
            exp[i] = exp1[i];
299
    }
300
}
301

    
302
/* update the exponents so that they are the ones the decoder will
303
   decode. Return the number of bits used to code the exponents */
304
static int encode_exp(uint8_t encoded_exp[AC3_MAX_COEFS],
305
                      uint8_t exp[AC3_MAX_COEFS],
306
                      int nb_exps,
307
                      int exp_strategy)
308
{
309
    int group_size, nb_groups, i, j, k, exp_min;
310
    uint8_t exp1[AC3_MAX_COEFS];
311

    
312
    switch(exp_strategy) {
313
    case EXP_D15:
314
        group_size = 1;
315
        break;
316
    case EXP_D25:
317
        group_size = 2;
318
        break;
319
    default:
320
    case EXP_D45:
321
        group_size = 4;
322
        break;
323
    }
324
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
325

    
326
    /* for each group, compute the minimum exponent */
327
    exp1[0] = exp[0]; /* DC exponent is handled separately */
328
    k = 1;
329
    for(i=1;i<=nb_groups;i++) {
330
        exp_min = exp[k];
331
        assert(exp_min >= 0 && exp_min <= 24);
332
        for(j=1;j<group_size;j++) {
333
            if (exp[k+j] < exp_min)
334
                exp_min = exp[k+j];
335
        }
336
        exp1[i] = exp_min;
337
        k += group_size;
338
    }
339

    
340
    /* constraint for DC exponent */
341
    if (exp1[0] > 15)
342
        exp1[0] = 15;
343

    
344
    /* Decrease the delta between each groups to within 2
345
     * so that they can be differentially encoded */
346
    for (i=1;i<=nb_groups;i++)
347
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
348
    for (i=nb_groups-1;i>=0;i--)
349
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
350

    
351
    /* now we have the exponent values the decoder will see */
352
    encoded_exp[0] = exp1[0];
353
    k = 1;
354
    for(i=1;i<=nb_groups;i++) {
355
        for(j=0;j<group_size;j++) {
356
            encoded_exp[k+j] = exp1[i];
357
        }
358
        k += group_size;
359
    }
360

    
361
#if defined(DEBUG)
362
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
363
    for(i=0;i<=nb_groups * group_size;i++) {
364
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
365
    }
366
    av_log(NULL, AV_LOG_DEBUG, "\n");
367
#endif
368

    
369
    return 4 + (nb_groups / 3) * 7;
370
}
371

    
372
/* return the size in bits taken by the mantissa */
373
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
374
{
375
    int bits, mant, i;
376

    
377
    bits = 0;
378
    for(i=0;i<nb_coefs;i++) {
379
        mant = m[i];
380
        switch(mant) {
381
        case 0:
382
            /* nothing */
383
            break;
384
        case 1:
385
            /* 3 mantissa in 5 bits */
386
            if (s->mant1_cnt == 0)
387
                bits += 5;
388
            if (++s->mant1_cnt == 3)
389
                s->mant1_cnt = 0;
390
            break;
391
        case 2:
392
            /* 3 mantissa in 7 bits */
393
            if (s->mant2_cnt == 0)
394
                bits += 7;
395
            if (++s->mant2_cnt == 3)
396
                s->mant2_cnt = 0;
397
            break;
398
        case 3:
399
            bits += 3;
400
            break;
401
        case 4:
402
            /* 2 mantissa in 7 bits */
403
            if (s->mant4_cnt == 0)
404
                bits += 7;
405
            if (++s->mant4_cnt == 2)
406
                s->mant4_cnt = 0;
407
            break;
408
        case 14:
409
            bits += 14;
410
            break;
411
        case 15:
412
            bits += 16;
413
            break;
414
        default:
415
            bits += mant - 1;
416
            break;
417
        }
418
    }
419
    return bits;
420
}
421

    
422

    
423
static void bit_alloc_masking(AC3EncodeContext *s,
424
                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
425
                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
426
                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
427
                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50])
428
{
429
    int blk, ch;
430
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
431

    
432
    for(blk=0; blk<AC3_MAX_BLOCKS; blk++) {
433
        for(ch=0;ch<s->channels;ch++) {
434
            if(exp_strategy[blk][ch] == EXP_REUSE) {
435
                memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*sizeof(int16_t));
436
                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
437
            } else {
438
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
439
                                          s->nb_coefs[ch],
440
                                          psd[blk][ch], band_psd[blk][ch]);
441
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
442
                                           0, s->nb_coefs[ch],
443
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
444
                                           ch == s->lfe_channel,
445
                                           DBA_NONE, 0, NULL, NULL, NULL,
446
                                           mask[blk][ch]);
447
            }
448
        }
449
    }
450
}
451

    
452
static int bit_alloc(AC3EncodeContext *s,
453
                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50],
454
                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
455
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
456
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
457
{
458
    int i, ch;
459
    int snr_offset;
460

    
461
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
462

    
463
    /* compute size */
464
    for(i=0;i<AC3_MAX_BLOCKS;i++) {
465
        s->mant1_cnt = 0;
466
        s->mant2_cnt = 0;
467
        s->mant4_cnt = 0;
468
        for(ch=0;ch<s->channels;ch++) {
469
            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
470
                                      s->nb_coefs[ch], snr_offset,
471
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
472
                                      bap[i][ch]);
473
            frame_bits += compute_mantissa_size(s, bap[i][ch],
474
                                                 s->nb_coefs[ch]);
475
        }
476
    }
477
#if 0
478
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
479
           coarse_snr_offset, fine_snr_offset, frame_bits,
480
           16 * s->frame_size - ((frame_bits + 7) & ~7));
481
#endif
482
    return 16 * s->frame_size - frame_bits;
483
}
484

    
485
#define SNR_INC1 4
486

    
487
static int compute_bit_allocation(AC3EncodeContext *s,
488
                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
489
                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
490
                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
491
                                  int frame_bits)
492
{
493
    int i, ch;
494
    int coarse_snr_offset, fine_snr_offset;
495
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
496
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
497
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
498
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
499

    
500
    /* init default parameters */
501
    s->slow_decay_code = 2;
502
    s->fast_decay_code = 1;
503
    s->slow_gain_code = 1;
504
    s->db_per_bit_code = 2;
505
    s->floor_code = 4;
506
    for(ch=0;ch<s->channels;ch++)
507
        s->fast_gain_code[ch] = 4;
508

    
509
    /* compute real values */
510
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
511
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
512
    s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
513
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
514
    s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
515

    
516
    /* header size */
517
    frame_bits += 65;
518
    // if (s->channel_mode == 2)
519
    //    frame_bits += 2;
520
    frame_bits += frame_bits_inc[s->channel_mode];
521

    
522
    /* audio blocks */
523
    for(i=0;i<AC3_MAX_BLOCKS;i++) {
524
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
525
        if (s->channel_mode == AC3_CHMODE_STEREO) {
526
            frame_bits++; /* rematstr */
527
            if(i==0) frame_bits += 4;
528
        }
529
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
530
        if (s->lfe_on)
531
            frame_bits++; /* lfeexpstr */
532
        for(ch=0;ch<s->fbw_channels;ch++) {
533
            if (exp_strategy[i][ch] != EXP_REUSE)
534
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
535
        }
536
        frame_bits++; /* baie */
537
        frame_bits++; /* snr */
538
        frame_bits += 2; /* delta / skip */
539
    }
540
    frame_bits++; /* cplinu for block 0 */
541
    /* bit alloc info */
542
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
543
    /* csnroffset[6] */
544
    /* (fsnoffset[4] + fgaincod[4]) * c */
545
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
546

    
547
    /* auxdatae, crcrsv */
548
    frame_bits += 2;
549

    
550
    /* CRC */
551
    frame_bits += 16;
552

    
553
    /* calculate psd and masking curve before doing bit allocation */
554
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
555

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

    
559
    coarse_snr_offset = s->coarse_snr_offset;
560
    while (coarse_snr_offset >= 0 &&
561
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
562
        coarse_snr_offset -= SNR_INC1;
563
    if (coarse_snr_offset < 0) {
564
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
565
        return -1;
566
    }
567
    while ((coarse_snr_offset + SNR_INC1) <= 63 &&
568
           bit_alloc(s, mask, psd, bap1, frame_bits,
569
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
570
        coarse_snr_offset += SNR_INC1;
571
        memcpy(bap, bap1, sizeof(bap1));
572
    }
573
    while ((coarse_snr_offset + 1) <= 63 &&
574
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
575
        coarse_snr_offset++;
576
        memcpy(bap, bap1, sizeof(bap1));
577
    }
578

    
579
    fine_snr_offset = 0;
580
    while ((fine_snr_offset + SNR_INC1) <= 15 &&
581
           bit_alloc(s, mask, psd, bap1, frame_bits,
582
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
583
        fine_snr_offset += SNR_INC1;
584
        memcpy(bap, bap1, sizeof(bap1));
585
    }
586
    while ((fine_snr_offset + 1) <= 15 &&
587
           bit_alloc(s, mask, psd, bap1, frame_bits,
588
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
589
        fine_snr_offset++;
590
        memcpy(bap, bap1, sizeof(bap1));
591
    }
592

    
593
    s->coarse_snr_offset = coarse_snr_offset;
594
    for(ch=0;ch<s->channels;ch++)
595
        s->fine_snr_offset[ch] = fine_snr_offset;
596
#if defined(DEBUG_BITALLOC)
597
    {
598
        int j;
599

    
600
        for(i=0;i<6;i++) {
601
            for(ch=0;ch<s->channels;ch++) {
602
                printf("Block #%d Ch%d:\n", i, ch);
603
                printf("bap=");
604
                for(j=0;j<s->nb_coefs[ch];j++) {
605
                    printf("%d ",bap[i][ch][j]);
606
                }
607
                printf("\n");
608
            }
609
        }
610
    }
611
#endif
612
    return 0;
613
}
614

    
615
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
616
                                    int64_t *channel_layout)
617
{
618
    int ch_layout;
619

    
620
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
621
        return -1;
622
    if ((uint64_t)*channel_layout > 0x7FF)
623
        return -1;
624
    ch_layout = *channel_layout;
625
    if (!ch_layout)
626
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
627
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
628
        return -1;
629

    
630
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
631
    s->channels     = channels;
632
    s->fbw_channels = channels - s->lfe_on;
633
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
634
    if (s->lfe_on)
635
        ch_layout -= AV_CH_LOW_FREQUENCY;
636

    
637
    switch (ch_layout) {
638
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
639
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
640
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
641
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
642
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
643
    case AV_CH_LAYOUT_QUAD:
644
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
645
    case AV_CH_LAYOUT_5POINT0:
646
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
647
    default:
648
        return -1;
649
    }
650

    
651
    s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
652
    *channel_layout = ch_layout;
653
    if (s->lfe_on)
654
        *channel_layout |= AV_CH_LOW_FREQUENCY;
655

    
656
    return 0;
657
}
658

    
659
static av_cold int AC3_encode_init(AVCodecContext *avctx)
660
{
661
    int freq = avctx->sample_rate;
662
    int bitrate = avctx->bit_rate;
663
    AC3EncodeContext *s = avctx->priv_data;
664
    int i, j, ch;
665
    float alpha;
666
    int bw_code;
667

    
668
    avctx->frame_size = AC3_FRAME_SIZE;
669

    
670
    ac3_common_init();
671

    
672
    if (!avctx->channel_layout) {
673
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
674
                                      "encoder will guess the layout, but it "
675
                                      "might be incorrect.\n");
676
    }
677
    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
678
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
679
        return -1;
680
    }
681

    
682
    /* frequency */
683
    for(i=0;i<3;i++) {
684
        for(j=0;j<3;j++)
685
            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
686
                goto found;
687
    }
688
    return -1;
689
 found:
690
    s->sample_rate = freq;
691
    s->bit_alloc.sr_shift = i;
692
    s->bit_alloc.sr_code = j;
693
    s->bitstream_id = 8 + s->bit_alloc.sr_shift;
694
    s->bitstream_mode = 0; /* complete main audio service */
695

    
696
    /* bitrate & frame size */
697
    for(i=0;i<19;i++) {
698
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == bitrate)
699
            break;
700
    }
701
    if (i == 19)
702
        return -1;
703
    s->bit_rate = bitrate;
704
    s->frame_size_code = i << 1;
705
    s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
706
    s->bits_written = 0;
707
    s->samples_written = 0;
708
    s->frame_size = s->frame_size_min;
709

    
710
    /* bit allocation init */
711
    if(avctx->cutoff) {
712
        /* calculate bandwidth based on user-specified cutoff frequency */
713
        int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
714
        int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
715
        bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
716
    } else {
717
        /* use default bandwidth setting */
718
        /* XXX: should compute the bandwidth according to the frame
719
           size, so that we avoid annoying high frequency artifacts */
720
        bw_code = 50;
721
    }
722
    for(ch=0;ch<s->fbw_channels;ch++) {
723
        /* bandwidth for each channel */
724
        s->bandwidth_code[ch] = bw_code;
725
        s->nb_coefs[ch] = bw_code * 3 + 73;
726
    }
727
    if (s->lfe_on) {
728
        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
729
    }
730
    /* initial snr offset */
731
    s->coarse_snr_offset = 40;
732

    
733
    /* mdct init */
734
    fft_init(MDCT_NBITS - 2);
735
    for(i=0;i<MDCT_SAMPLES/4;i++) {
736
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)MDCT_SAMPLES;
737
        xcos1[i] = fix15(-cos(alpha));
738
        xsin1[i] = fix15(-sin(alpha));
739
    }
740

    
741
    avctx->coded_frame= avcodec_alloc_frame();
742
    avctx->coded_frame->key_frame= 1;
743

    
744
    return 0;
745
}
746

    
747
/* output the AC-3 frame header */
748
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
749
{
750
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
751

    
752
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
753
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
754
    put_bits(&s->pb, 2, s->bit_alloc.sr_code);
755
    put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
756
    put_bits(&s->pb, 5, s->bitstream_id);
757
    put_bits(&s->pb, 3, s->bitstream_mode);
758
    put_bits(&s->pb, 3, s->channel_mode);
759
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
760
        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
761
    if (s->channel_mode & 0x04)
762
        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
763
    if (s->channel_mode == AC3_CHMODE_STEREO)
764
        put_bits(&s->pb, 2, 0); /* surround not indicated */
765
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
766
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
767
    put_bits(&s->pb, 1, 0); /* no compression control word */
768
    put_bits(&s->pb, 1, 0); /* no lang code */
769
    put_bits(&s->pb, 1, 0); /* no audio production info */
770
    put_bits(&s->pb, 1, 0); /* no copyright */
771
    put_bits(&s->pb, 1, 1); /* original bitstream */
772
    put_bits(&s->pb, 1, 0); /* no time code 1 */
773
    put_bits(&s->pb, 1, 0); /* no time code 2 */
774
    put_bits(&s->pb, 1, 0); /* no additional bit stream info */
775
}
776

    
777
/* symetric quantization on 'levels' levels */
778
static inline int sym_quant(int c, int e, int levels)
779
{
780
    int v;
781

    
782
    if (c >= 0) {
783
        v = (levels * (c << e)) >> 24;
784
        v = (v + 1) >> 1;
785
        v = (levels >> 1) + v;
786
    } else {
787
        v = (levels * ((-c) << e)) >> 24;
788
        v = (v + 1) >> 1;
789
        v = (levels >> 1) - v;
790
    }
791
    assert (v >= 0 && v < levels);
792
    return v;
793
}
794

    
795
/* asymetric quantization on 2^qbits levels */
796
static inline int asym_quant(int c, int e, int qbits)
797
{
798
    int lshift, m, v;
799

    
800
    lshift = e + qbits - 24;
801
    if (lshift >= 0)
802
        v = c << lshift;
803
    else
804
        v = c >> (-lshift);
805
    /* rounding */
806
    v = (v + 1) >> 1;
807
    m = (1 << (qbits-1));
808
    if (v >= m)
809
        v = m - 1;
810
    assert(v >= -m);
811
    return v & ((1 << qbits)-1);
812
}
813

    
814
/* Output one audio block. There are AC3_MAX_BLOCKS audio blocks in one AC-3
815
   frame */
816
static void output_audio_block(AC3EncodeContext *s,
817
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
818
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
819
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
820
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
821
                               int8_t global_exp[AC3_MAX_CHANNELS],
822
                               int block_num)
823
{
824
    int ch, nb_groups, group_size, i, baie, rbnd;
825
    uint8_t *p;
826
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
827
    int exp0, exp1;
828
    int mant1_cnt, mant2_cnt, mant4_cnt;
829
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
830
    int delta0, delta1, delta2;
831

    
832
    for(ch=0;ch<s->fbw_channels;ch++)
833
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
834
    for(ch=0;ch<s->fbw_channels;ch++)
835
        put_bits(&s->pb, 1, 1); /* no dither */
836
    put_bits(&s->pb, 1, 0); /* no dynamic range */
837
    if (block_num == 0) {
838
        /* for block 0, even if no coupling, we must say it. This is a
839
           waste of bit :-) */
840
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
841
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
842
    } else {
843
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
844
    }
845

    
846
    if (s->channel_mode == AC3_CHMODE_STEREO)
847
      {
848
        if(block_num==0)
849
          {
850
            /* first block must define rematrixing (rematstr)  */
851
            put_bits(&s->pb, 1, 1);
852

    
853
            /* dummy rematrixing rematflg(1:4)=0 */
854
            for (rbnd=0;rbnd<4;rbnd++)
855
              put_bits(&s->pb, 1, 0);
856
          }
857
        else
858
          {
859
            /* no matrixing (but should be used in the future) */
860
            put_bits(&s->pb, 1, 0);
861
          }
862
      }
863

    
864
#if defined(DEBUG)
865
    {
866
      static int count = 0;
867
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
868
    }
869
#endif
870
    /* exponent strategy */
871
    for(ch=0;ch<s->fbw_channels;ch++) {
872
        put_bits(&s->pb, 2, exp_strategy[ch]);
873
    }
874

    
875
    if (s->lfe_on) {
876
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
877
    }
878

    
879
    for(ch=0;ch<s->fbw_channels;ch++) {
880
        if (exp_strategy[ch] != EXP_REUSE)
881
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
882
    }
883

    
884
    /* exponents */
885
    for (ch = 0; ch < s->channels; ch++) {
886
        switch(exp_strategy[ch]) {
887
        case EXP_REUSE:
888
            continue;
889
        case EXP_D15:
890
            group_size = 1;
891
            break;
892
        case EXP_D25:
893
            group_size = 2;
894
            break;
895
        default:
896
        case EXP_D45:
897
            group_size = 4;
898
            break;
899
        }
900
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
901
        p = encoded_exp[ch];
902

    
903
        /* first exponent */
904
        exp1 = *p++;
905
        put_bits(&s->pb, 4, exp1);
906

    
907
        /* next ones are delta encoded */
908
        for(i=0;i<nb_groups;i++) {
909
            /* merge three delta in one code */
910
            exp0 = exp1;
911
            exp1 = p[0];
912
            p += group_size;
913
            delta0 = exp1 - exp0 + 2;
914

    
915
            exp0 = exp1;
916
            exp1 = p[0];
917
            p += group_size;
918
            delta1 = exp1 - exp0 + 2;
919

    
920
            exp0 = exp1;
921
            exp1 = p[0];
922
            p += group_size;
923
            delta2 = exp1 - exp0 + 2;
924

    
925
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
926
        }
927

    
928
        if (ch != s->lfe_channel)
929
            put_bits(&s->pb, 2, 0); /* no gain range info */
930
    }
931

    
932
    /* bit allocation info */
933
    baie = (block_num == 0);
934
    put_bits(&s->pb, 1, baie);
935
    if (baie) {
936
        put_bits(&s->pb, 2, s->slow_decay_code);
937
        put_bits(&s->pb, 2, s->fast_decay_code);
938
        put_bits(&s->pb, 2, s->slow_gain_code);
939
        put_bits(&s->pb, 2, s->db_per_bit_code);
940
        put_bits(&s->pb, 3, s->floor_code);
941
    }
942

    
943
    /* snr offset */
944
    put_bits(&s->pb, 1, baie); /* always present with bai */
945
    if (baie) {
946
        put_bits(&s->pb, 6, s->coarse_snr_offset);
947
        for(ch=0;ch<s->channels;ch++) {
948
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
949
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
950
        }
951
    }
952

    
953
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
954
    put_bits(&s->pb, 1, 0); /* no data to skip */
955

    
956
    /* mantissa encoding : we use two passes to handle the grouping. A
957
       one pass method may be faster, but it would necessitate to
958
       modify the output stream. */
959

    
960
    /* first pass: quantize */
961
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
962
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
963

    
964
    for (ch = 0; ch < s->channels; ch++) {
965
        int b, c, e, v;
966

    
967
        for(i=0;i<s->nb_coefs[ch];i++) {
968
            c = mdct_coefs[ch][i];
969
            e = encoded_exp[ch][i] - global_exp[ch];
970
            b = bap[ch][i];
971
            switch(b) {
972
            case 0:
973
                v = 0;
974
                break;
975
            case 1:
976
                v = sym_quant(c, e, 3);
977
                switch(mant1_cnt) {
978
                case 0:
979
                    qmant1_ptr = &qmant[ch][i];
980
                    v = 9 * v;
981
                    mant1_cnt = 1;
982
                    break;
983
                case 1:
984
                    *qmant1_ptr += 3 * v;
985
                    mant1_cnt = 2;
986
                    v = 128;
987
                    break;
988
                default:
989
                    *qmant1_ptr += v;
990
                    mant1_cnt = 0;
991
                    v = 128;
992
                    break;
993
                }
994
                break;
995
            case 2:
996
                v = sym_quant(c, e, 5);
997
                switch(mant2_cnt) {
998
                case 0:
999
                    qmant2_ptr = &qmant[ch][i];
1000
                    v = 25 * v;
1001
                    mant2_cnt = 1;
1002
                    break;
1003
                case 1:
1004
                    *qmant2_ptr += 5 * v;
1005
                    mant2_cnt = 2;
1006
                    v = 128;
1007
                    break;
1008
                default:
1009
                    *qmant2_ptr += v;
1010
                    mant2_cnt = 0;
1011
                    v = 128;
1012
                    break;
1013
                }
1014
                break;
1015
            case 3:
1016
                v = sym_quant(c, e, 7);
1017
                break;
1018
            case 4:
1019
                v = sym_quant(c, e, 11);
1020
                switch(mant4_cnt) {
1021
                case 0:
1022
                    qmant4_ptr = &qmant[ch][i];
1023
                    v = 11 * v;
1024
                    mant4_cnt = 1;
1025
                    break;
1026
                default:
1027
                    *qmant4_ptr += v;
1028
                    mant4_cnt = 0;
1029
                    v = 128;
1030
                    break;
1031
                }
1032
                break;
1033
            case 5:
1034
                v = sym_quant(c, e, 15);
1035
                break;
1036
            case 14:
1037
                v = asym_quant(c, e, 14);
1038
                break;
1039
            case 15:
1040
                v = asym_quant(c, e, 16);
1041
                break;
1042
            default:
1043
                v = asym_quant(c, e, b - 1);
1044
                break;
1045
            }
1046
            qmant[ch][i] = v;
1047
        }
1048
    }
1049

    
1050
    /* second pass : output the values */
1051
    for (ch = 0; ch < s->channels; ch++) {
1052
        int b, q;
1053

    
1054
        for(i=0;i<s->nb_coefs[ch];i++) {
1055
            q = qmant[ch][i];
1056
            b = bap[ch][i];
1057
            switch(b) {
1058
            case 0:
1059
                break;
1060
            case 1:
1061
                if (q != 128)
1062
                    put_bits(&s->pb, 5, q);
1063
                break;
1064
            case 2:
1065
                if (q != 128)
1066
                    put_bits(&s->pb, 7, q);
1067
                break;
1068
            case 3:
1069
                put_bits(&s->pb, 3, q);
1070
                break;
1071
            case 4:
1072
                if (q != 128)
1073
                    put_bits(&s->pb, 7, q);
1074
                break;
1075
            case 14:
1076
                put_bits(&s->pb, 14, q);
1077
                break;
1078
            case 15:
1079
                put_bits(&s->pb, 16, q);
1080
                break;
1081
            default:
1082
                put_bits(&s->pb, b - 1, q);
1083
                break;
1084
            }
1085
        }
1086
    }
1087
}
1088

    
1089
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1090

    
1091
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1092
{
1093
    unsigned int c;
1094

    
1095
    c = 0;
1096
    while (a) {
1097
        if (a & 1)
1098
            c ^= b;
1099
        a = a >> 1;
1100
        b = b << 1;
1101
        if (b & (1 << 16))
1102
            b ^= poly;
1103
    }
1104
    return c;
1105
}
1106

    
1107
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1108
{
1109
    unsigned int r;
1110
    r = 1;
1111
    while (n) {
1112
        if (n & 1)
1113
            r = mul_poly(r, a, poly);
1114
        a = mul_poly(a, a, poly);
1115
        n >>= 1;
1116
    }
1117
    return r;
1118
}
1119

    
1120

    
1121
/* compute log2(max(abs(tab[]))) */
1122
static int log2_tab(int16_t *tab, int n)
1123
{
1124
    int i, v;
1125

    
1126
    v = 0;
1127
    for(i=0;i<n;i++) {
1128
        v |= abs(tab[i]);
1129
    }
1130
    return av_log2(v);
1131
}
1132

    
1133
static void lshift_tab(int16_t *tab, int n, int lshift)
1134
{
1135
    int i;
1136

    
1137
    if (lshift > 0) {
1138
        for(i=0;i<n;i++) {
1139
            tab[i] <<= lshift;
1140
        }
1141
    } else if (lshift < 0) {
1142
        lshift = -lshift;
1143
        for(i=0;i<n;i++) {
1144
            tab[i] >>= lshift;
1145
        }
1146
    }
1147
}
1148

    
1149
/* fill the end of the frame and compute the two crcs */
1150
static int output_frame_end(AC3EncodeContext *s)
1151
{
1152
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1153
    uint8_t *frame;
1154

    
1155
    frame_size = s->frame_size; /* frame size in words */
1156
    /* align to 8 bits */
1157
    flush_put_bits(&s->pb);
1158
    /* add zero bytes to reach the frame size */
1159
    frame = s->pb.buf;
1160
    n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1161
    assert(n >= 0);
1162
    if(n>0)
1163
      memset(put_bits_ptr(&s->pb), 0, n);
1164

    
1165
    /* Now we must compute both crcs : this is not so easy for crc1
1166
       because it is at the beginning of the data... */
1167
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1168
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1169
                           frame + 4, 2 * frame_size_58 - 4));
1170
    /* XXX: could precompute crc_inv */
1171
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1172
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1173
    AV_WB16(frame+2,crc1);
1174

    
1175
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1176
                           frame + 2 * frame_size_58,
1177
                           (frame_size - frame_size_58) * 2 - 2));
1178
    AV_WB16(frame+2*frame_size-2,crc2);
1179

    
1180
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1181
    return frame_size * 2;
1182
}
1183

    
1184
static int AC3_encode_frame(AVCodecContext *avctx,
1185
                            unsigned char *frame, int buf_size, void *data)
1186
{
1187
    AC3EncodeContext *s = avctx->priv_data;
1188
    const int16_t *samples = data;
1189
    int i, j, k, v, ch;
1190
    int16_t input_samples[AC3_WINDOW_SIZE];
1191
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1192
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1193
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1194
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1195
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1196
    int8_t exp_samples[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1197
    int frame_bits;
1198

    
1199
    frame_bits = 0;
1200
    for(ch=0;ch<s->channels;ch++) {
1201
        int ich = s->channel_map[ch];
1202
        /* fixed mdct to the six sub blocks & exponent computation */
1203
        for(i=0;i<AC3_MAX_BLOCKS;i++) {
1204
            const int16_t *sptr;
1205
            int sinc;
1206

    
1207
            /* compute input samples */
1208
            memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
1209
            sinc = s->channels;
1210
            sptr = samples + (sinc * AC3_BLOCK_SIZE * i) + ich;
1211
            for(j=0;j<AC3_BLOCK_SIZE;j++) {
1212
                v = *sptr;
1213
                input_samples[j + AC3_BLOCK_SIZE] = v;
1214
                s->last_samples[ich][j] = v;
1215
                sptr += sinc;
1216
            }
1217

    
1218
            /* apply the MDCT window */
1219
            for(j=0;j<AC3_BLOCK_SIZE;j++) {
1220
                input_samples[j] = MUL16(input_samples[j],
1221
                                         ff_ac3_window[j]) >> 15;
1222
                input_samples[AC3_WINDOW_SIZE-j-1] = MUL16(input_samples[AC3_WINDOW_SIZE-j-1],
1223
                                             ff_ac3_window[j]) >> 15;
1224
            }
1225

    
1226
            /* Normalize the samples to use the maximum available
1227
               precision */
1228
            v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
1229
            if (v < 0)
1230
                v = 0;
1231
            exp_samples[i][ch] = v - 9;
1232
            lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
1233

    
1234
            /* do the MDCT */
1235
            mdct512(mdct_coef[i][ch], input_samples);
1236

    
1237
            /* compute "exponents". We take into account the
1238
               normalization there */
1239
            for(j=0;j<AC3_MAX_COEFS;j++) {
1240
                int e;
1241
                v = abs(mdct_coef[i][ch][j]);
1242
                if (v == 0)
1243
                    e = 24;
1244
                else {
1245
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1246
                    if (e >= 24) {
1247
                        e = 24;
1248
                        mdct_coef[i][ch][j] = 0;
1249
                    }
1250
                }
1251
                exp[i][ch][j] = e;
1252
            }
1253
        }
1254

    
1255
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1256

    
1257
        /* compute the exponents as the decoder will see them. The
1258
           EXP_REUSE case must be handled carefully : we select the
1259
           min of the exponents */
1260
        i = 0;
1261
        while (i < AC3_MAX_BLOCKS) {
1262
            j = i + 1;
1263
            while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1264
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1265
                j++;
1266
            }
1267
            frame_bits += encode_exp(encoded_exp[i][ch],
1268
                                     exp[i][ch], s->nb_coefs[ch],
1269
                                     exp_strategy[i][ch]);
1270
            /* copy encoded exponents for reuse case */
1271
            for(k=i+1;k<j;k++) {
1272
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1273
                       s->nb_coefs[ch] * sizeof(uint8_t));
1274
            }
1275
            i = j;
1276
        }
1277
    }
1278

    
1279
    /* adjust for fractional frame sizes */
1280
    while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1281
        s->bits_written -= s->bit_rate;
1282
        s->samples_written -= s->sample_rate;
1283
    }
1284
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1285
    s->bits_written += s->frame_size * 16;
1286
    s->samples_written += AC3_FRAME_SIZE;
1287

    
1288
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1289
    /* everything is known... let's output the frame */
1290
    output_frame_header(s, frame);
1291

    
1292
    for(i=0;i<AC3_MAX_BLOCKS;i++) {
1293
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1294
                           bap[i], mdct_coef[i], exp_samples[i], i);
1295
    }
1296
    return output_frame_end(s);
1297
}
1298

    
1299
static av_cold int AC3_encode_close(AVCodecContext *avctx)
1300
{
1301
    av_freep(&avctx->coded_frame);
1302
    return 0;
1303
}
1304

    
1305
#if 0
1306
/*************************************************************************/
1307
/* TEST */
1308

1309
#undef random
1310
#define FN (N/4)
1311

1312
void fft_test(void)
1313
{
1314
    IComplex in[FN], in1[FN];
1315
    int k, n, i;
1316
    float sum_re, sum_im, a;
1317

1318
    /* FFT test */
1319

1320
    for(i=0;i<FN;i++) {
1321
        in[i].re = random() % 65535 - 32767;
1322
        in[i].im = random() % 65535 - 32767;
1323
        in1[i] = in[i];
1324
    }
1325
    fft(in, 7);
1326

1327
    /* do it by hand */
1328
    for(k=0;k<FN;k++) {
1329
        sum_re = 0;
1330
        sum_im = 0;
1331
        for(n=0;n<FN;n++) {
1332
            a = -2 * M_PI * (n * k) / FN;
1333
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1334
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1335
        }
1336
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1337
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1338
    }
1339
}
1340

1341
void mdct_test(void)
1342
{
1343
    int16_t input[N];
1344
    int32_t output[N/2];
1345
    float input1[N];
1346
    float output1[N/2];
1347
    float s, a, err, e, emax;
1348
    int i, k, n;
1349

1350
    for(i=0;i<N;i++) {
1351
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1352
        input1[i] = input[i];
1353
    }
1354

1355
    mdct512(output, input);
1356

1357
    /* do it by hand */
1358
    for(k=0;k<N/2;k++) {
1359
        s = 0;
1360
        for(n=0;n<N;n++) {
1361
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1362
            s += input1[n] * cos(a);
1363
        }
1364
        output1[k] = -2 * s / N;
1365
    }
1366

1367
    err = 0;
1368
    emax = 0;
1369
    for(i=0;i<N/2;i++) {
1370
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1371
        e = output[i] - output1[i];
1372
        if (e > emax)
1373
            emax = e;
1374
        err += e * e;
1375
    }
1376
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1377
}
1378

1379
void test_ac3(void)
1380
{
1381
    AC3EncodeContext ctx;
1382
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1383
    int16_t samples[AC3_FRAME_SIZE];
1384
    int ret, i;
1385

1386
    AC3_encode_init(&ctx, 44100, 64000, 1);
1387

1388
    fft_test();
1389
    mdct_test();
1390

1391
    for(i=0;i<AC3_FRAME_SIZE;i++)
1392
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1393
    ret = AC3_encode_frame(&ctx, frame, samples);
1394
    printf("ret=%d\n", ret);
1395
}
1396
#endif
1397

    
1398
AVCodec ac3_encoder = {
1399
    "ac3",
1400
    AVMEDIA_TYPE_AUDIO,
1401
    CODEC_ID_AC3,
1402
    sizeof(AC3EncodeContext),
1403
    AC3_encode_init,
1404
    AC3_encode_frame,
1405
    AC3_encode_close,
1406
    NULL,
1407
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1408
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1409
    .channel_layouts = (const int64_t[]){
1410
        AV_CH_LAYOUT_MONO,
1411
        AV_CH_LAYOUT_STEREO,
1412
        AV_CH_LAYOUT_2_1,
1413
        AV_CH_LAYOUT_SURROUND,
1414
        AV_CH_LAYOUT_2_2,
1415
        AV_CH_LAYOUT_QUAD,
1416
        AV_CH_LAYOUT_4POINT0,
1417
        AV_CH_LAYOUT_5POINT0,
1418
        AV_CH_LAYOUT_5POINT0_BACK,
1419
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1420
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1421
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1422
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1423
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1424
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1425
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1426
        AV_CH_LAYOUT_5POINT1,
1427
        AV_CH_LAYOUT_5POINT1_BACK,
1428
        0 },
1429
};