Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ ad1ea1f1

History | View | Annotate | Download (38.3 KB)

1 de6d9b64 Fabrice Bellard
/*
2
 * The simplest AC3 encoder
3 ff4ec49e Fabrice Bellard
 * Copyright (c) 2000 Fabrice Bellard.
4 de6d9b64 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 ff4ec49e Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 de6d9b64 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ff4ec49e Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 de6d9b64 Fabrice Bellard
 *
17 ff4ec49e Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 de6d9b64 Fabrice Bellard
 */
21 983e3246 Michael Niedermayer
22
/**
23
 * @file ac3enc.c
24
 * The simplest AC3 encoder.
25
 */
26 1a565432 Fabrice Bellard
//#define DEBUG
27
//#define DEBUG_BITALLOC
28 de6d9b64 Fabrice Bellard
#include "avcodec.h"
29 caa336b4 Michael Niedermayer
#include "bitstream.h"
30 e027d0a8 Michael Niedermayer
#include "crc.h"
31 6107fa87 Fabrice Bellard
#include "ac3.h"
32
33
typedef struct AC3EncodeContext {
34
    PutBitContext pb;
35
    int nb_channels;
36
    int nb_all_channels;
37
    int lfe_channel;
38
    int bit_rate;
39 5c91a675 Zdenek Kabelac
    unsigned int sample_rate;
40
    unsigned int bsid;
41
    unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
42
    unsigned int frame_size; /* current frame size in words */
43 f760b70f Justin Ruggles
    unsigned int bits_written;
44
    unsigned int samples_written;
45 6107fa87 Fabrice Bellard
    int halfratecod;
46 5c91a675 Zdenek Kabelac
    unsigned int frmsizecod;
47
    unsigned int fscod; /* frequency */
48
    unsigned int acmod;
49 6107fa87 Fabrice Bellard
    int lfe;
50 5c91a675 Zdenek Kabelac
    unsigned int bsmod;
51 6107fa87 Fabrice Bellard
    short last_samples[AC3_MAX_CHANNELS][256];
52 5c91a675 Zdenek Kabelac
    unsigned int chbwcod[AC3_MAX_CHANNELS];
53 6107fa87 Fabrice Bellard
    int nb_coefs[AC3_MAX_CHANNELS];
54 115329f1 Diego Biurrun
55 6107fa87 Fabrice Bellard
    /* bitrate allocation control */
56 115329f1 Diego Biurrun
    int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
57 6107fa87 Fabrice Bellard
    AC3BitAllocParameters bit_alloc;
58
    int csnroffst;
59
    int fgaincod[AC3_MAX_CHANNELS];
60
    int fsnroffst[AC3_MAX_CHANNELS];
61
    /* mantissa encoding */
62
    int mant1_cnt, mant2_cnt, mant4_cnt;
63
} AC3EncodeContext;
64 de6d9b64 Fabrice Bellard
65 4258a0a3 Justin Ruggles
static int16_t costab[64];
66
static int16_t sintab[64];
67
static int16_t fft_rev[512];
68
static int16_t xcos1[128];
69
static int16_t xsin1[128];
70 de6d9b64 Fabrice Bellard
71
#define MDCT_NBITS 9
72
#define N         (1 << MDCT_NBITS)
73
74
/* new exponents are sent if their Norm 1 exceed this number */
75
#define EXP_DIFF_THRESHOLD 1000
76
77
static void fft_init(int ln);
78
79 0c1a9eda Zdenek Kabelac
static inline int16_t fix15(float a)
80 de6d9b64 Fabrice Bellard
{
81
    int v;
82
    v = (int)(a * (float)(1 << 15));
83
    if (v < -32767)
84
        v = -32767;
85 115329f1 Diego Biurrun
    else if (v > 32767)
86 de6d9b64 Fabrice Bellard
        v = 32767;
87
    return v;
88
}
89
90
typedef struct IComplex {
91
    short re,im;
92
} IComplex;
93
94
static void fft_init(int ln)
95
{
96
    int i, j, m, n;
97
    float alpha;
98
99
    n = 1 << ln;
100
101
    for(i=0;i<(n/2);i++) {
102
        alpha = 2 * M_PI * (float)i / (float)n;
103
        costab[i] = fix15(cos(alpha));
104
        sintab[i] = fix15(sin(alpha));
105
    }
106
107
    for(i=0;i<n;i++) {
108
        m=0;
109
        for(j=0;j<ln;j++) {
110
            m |= ((i >> j) & 1) << (ln-j-1);
111
        }
112
        fft_rev[i]=m;
113
    }
114
}
115
116
/* butter fly op */
117
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
118
{\
119
  int ax, ay, bx, by;\
120
  bx=pre1;\
121
  by=pim1;\
122
  ax=qre1;\
123
  ay=qim1;\
124
  pre = (bx + ax) >> 1;\
125
  pim = (by + ay) >> 1;\
126
  qre = (bx - ax) >> 1;\
127
  qim = (by - ay) >> 1;\
128
}
129
130
#define MUL16(a,b) ((a) * (b))
131
132
#define CMUL(pre, pim, are, aim, bre, bim) \
133
{\
134
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
135
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
136
}
137
138
139
/* do a 2^n point complex fft on 2^ln points. */
140
static void fft(IComplex *z, int ln)
141
{
142 bb270c08 Diego Biurrun
    int        j, l, np, np2;
143
    int        nblocks, nloops;
144 de6d9b64 Fabrice Bellard
    register IComplex *p,*q;
145
    int tmp_re, tmp_im;
146
147
    np = 1 << ln;
148
149
    /* reverse */
150
    for(j=0;j<np;j++) {
151
        int k;
152
        IComplex tmp;
153
        k = fft_rev[j];
154
        if (k < j) {
155
            tmp = z[k];
156
            z[k] = z[j];
157
            z[j] = tmp;
158
        }
159
    }
160
161
    /* pass 0 */
162
163
    p=&z[0];
164
    j=(np >> 1);
165
    do {
166 115329f1 Diego Biurrun
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
167 de6d9b64 Fabrice Bellard
           p[0].re, p[0].im, p[1].re, p[1].im);
168
        p+=2;
169
    } while (--j != 0);
170
171
    /* pass 1 */
172
173
    p=&z[0];
174
    j=np >> 2;
175
    do {
176 115329f1 Diego Biurrun
        BF(p[0].re, p[0].im, p[2].re, p[2].im,
177 de6d9b64 Fabrice Bellard
           p[0].re, p[0].im, p[2].re, p[2].im);
178 115329f1 Diego Biurrun
        BF(p[1].re, p[1].im, p[3].re, p[3].im,
179 de6d9b64 Fabrice Bellard
           p[1].re, p[1].im, p[3].im, -p[3].re);
180
        p+=4;
181
    } while (--j != 0);
182
183
    /* pass 2 .. ln-1 */
184
185
    nblocks = np >> 3;
186
    nloops = 1 << 2;
187
    np2 = np >> 1;
188
    do {
189
        p = z;
190
        q = z + nloops;
191
        for (j = 0; j < nblocks; ++j) {
192
193
            BF(p->re, p->im, q->re, q->im,
194
               p->re, p->im, q->re, q->im);
195 115329f1 Diego Biurrun
196 de6d9b64 Fabrice Bellard
            p++;
197
            q++;
198
            for(l = nblocks; l < np2; l += nblocks) {
199
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
200
                BF(p->re, p->im, q->re, q->im,
201
                   p->re, p->im, tmp_re, tmp_im);
202
                p++;
203
                q++;
204
            }
205
            p += nloops;
206
            q += nloops;
207
        }
208
        nblocks = nblocks >> 1;
209
        nloops = nloops << 1;
210
    } while (nblocks != 0);
211
}
212
213
/* do a 512 point mdct */
214 0c1a9eda Zdenek Kabelac
static void mdct512(int32_t *out, int16_t *in)
215 de6d9b64 Fabrice Bellard
{
216
    int i, re, im, re1, im1;
217 115329f1 Diego Biurrun
    int16_t rot[N];
218 de6d9b64 Fabrice Bellard
    IComplex x[N/4];
219
220
    /* shift to simplify computations */
221
    for(i=0;i<N/4;i++)
222
        rot[i] = -in[i + 3*N/4];
223
    for(i=N/4;i<N;i++)
224
        rot[i] = in[i - N/4];
225 115329f1 Diego Biurrun
226 de6d9b64 Fabrice Bellard
    /* pre rotation */
227
    for(i=0;i<N/4;i++) {
228
        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
229
        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
230
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
231
    }
232
233
    fft(x, MDCT_NBITS - 2);
234 115329f1 Diego Biurrun
235 de6d9b64 Fabrice Bellard
    /* post rotation */
236
    for(i=0;i<N/4;i++) {
237
        re = x[i].re;
238
        im = x[i].im;
239
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
240
        out[2*i] = im1;
241
        out[N/2-1-2*i] = re1;
242
    }
243
}
244
245
/* XXX: use another norm ? */
246 0c1a9eda Zdenek Kabelac
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
247 de6d9b64 Fabrice Bellard
{
248
    int sum, i;
249
    sum = 0;
250
    for(i=0;i<n;i++) {
251
        sum += abs(exp1[i] - exp2[i]);
252
    }
253
    return sum;
254
}
255
256 0c1a9eda Zdenek Kabelac
static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
257
                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
258 30b68f33 Zdenek Kabelac
                                 int ch, int is_lfe)
259 de6d9b64 Fabrice Bellard
{
260
    int i, j;
261
    int exp_diff;
262 115329f1 Diego Biurrun
263 de6d9b64 Fabrice Bellard
    /* estimate if the exponent variation & decide if they should be
264
       reused in the next frame */
265
    exp_strategy[0][ch] = EXP_NEW;
266
    for(i=1;i<NB_BLOCKS;i++) {
267
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
268 115329f1 Diego Biurrun
#ifdef DEBUG
269 3d0ef6dd Michael Niedermayer
        av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
270 de6d9b64 Fabrice Bellard
#endif
271
        if (exp_diff > EXP_DIFF_THRESHOLD)
272
            exp_strategy[i][ch] = EXP_NEW;
273
        else
274
            exp_strategy[i][ch] = EXP_REUSE;
275
    }
276 30b68f33 Zdenek Kabelac
    if (is_lfe)
277 bb270c08 Diego Biurrun
        return;
278 30b68f33 Zdenek Kabelac
279 de6d9b64 Fabrice Bellard
    /* now select the encoding strategy type : if exponents are often
280
       recoded, we use a coarse encoding */
281
    i = 0;
282
    while (i < NB_BLOCKS) {
283
        j = i + 1;
284
        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
285
            j++;
286
        switch(j - i) {
287
        case 1:
288
            exp_strategy[i][ch] = EXP_D45;
289
            break;
290
        case 2:
291
        case 3:
292
            exp_strategy[i][ch] = EXP_D25;
293
            break;
294
        default:
295
            exp_strategy[i][ch] = EXP_D15;
296
            break;
297
        }
298 bb270c08 Diego Biurrun
        i = j;
299 de6d9b64 Fabrice Bellard
    }
300
}
301
302
/* set exp[i] to min(exp[i], exp1[i]) */
303 0c1a9eda Zdenek Kabelac
static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
304 de6d9b64 Fabrice Bellard
{
305
    int i;
306
307
    for(i=0;i<n;i++) {
308
        if (exp1[i] < exp[i])
309
            exp[i] = exp1[i];
310
    }
311
}
312 115329f1 Diego Biurrun
313 de6d9b64 Fabrice Bellard
/* update the exponents so that they are the ones the decoder will
314
   decode. Return the number of bits used to code the exponents */
315 115329f1 Diego Biurrun
static int encode_exp(uint8_t encoded_exp[N/2],
316
                      uint8_t exp[N/2],
317 de6d9b64 Fabrice Bellard
                      int nb_exps,
318
                      int exp_strategy)
319
{
320 e44cad52 Jeff Muizelaar
    int group_size, nb_groups, i, j, k, exp_min;
321 0c1a9eda Zdenek Kabelac
    uint8_t exp1[N/2];
322 de6d9b64 Fabrice Bellard
323
    switch(exp_strategy) {
324
    case EXP_D15:
325
        group_size = 1;
326
        break;
327
    case EXP_D25:
328
        group_size = 2;
329
        break;
330
    default:
331
    case EXP_D45:
332
        group_size = 4;
333
        break;
334
    }
335
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
336
337
    /* for each group, compute the minimum exponent */
338
    exp1[0] = exp[0]; /* DC exponent is handled separately */
339
    k = 1;
340
    for(i=1;i<=nb_groups;i++) {
341
        exp_min = exp[k];
342
        assert(exp_min >= 0 && exp_min <= 24);
343
        for(j=1;j<group_size;j++) {
344
            if (exp[k+j] < exp_min)
345
                exp_min = exp[k+j];
346
        }
347
        exp1[i] = exp_min;
348
        k += group_size;
349
    }
350
351
    /* constraint for DC exponent */
352
    if (exp1[0] > 15)
353
        exp1[0] = 15;
354
355 e44cad52 Jeff Muizelaar
    /* Decrease the delta between each groups to within 2
356
     * so that they can be differentially encoded */
357
    for (i=1;i<=nb_groups;i++)
358 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
359 e44cad52 Jeff Muizelaar
    for (i=nb_groups-1;i>=0;i--)
360 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
361 e44cad52 Jeff Muizelaar
362 de6d9b64 Fabrice Bellard
    /* now we have the exponent values the decoder will see */
363
    encoded_exp[0] = exp1[0];
364
    k = 1;
365
    for(i=1;i<=nb_groups;i++) {
366
        for(j=0;j<group_size;j++) {
367
            encoded_exp[k+j] = exp1[i];
368
        }
369
        k += group_size;
370
    }
371 115329f1 Diego Biurrun
372 de6d9b64 Fabrice Bellard
#if defined(DEBUG)
373 3d0ef6dd Michael Niedermayer
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
374 de6d9b64 Fabrice Bellard
    for(i=0;i<=nb_groups * group_size;i++) {
375 3d0ef6dd Michael Niedermayer
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
376 de6d9b64 Fabrice Bellard
    }
377 3d0ef6dd Michael Niedermayer
    av_log(NULL, AV_LOG_DEBUG, "\n");
378 de6d9b64 Fabrice Bellard
#endif
379
380
    return 4 + (nb_groups / 3) * 7;
381
}
382
383
/* return the size in bits taken by the mantissa */
384 0c1a9eda Zdenek Kabelac
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
385 de6d9b64 Fabrice Bellard
{
386
    int bits, mant, i;
387
388
    bits = 0;
389
    for(i=0;i<nb_coefs;i++) {
390
        mant = m[i];
391
        switch(mant) {
392
        case 0:
393
            /* nothing */
394
            break;
395
        case 1:
396
            /* 3 mantissa in 5 bits */
397 115329f1 Diego Biurrun
            if (s->mant1_cnt == 0)
398 de6d9b64 Fabrice Bellard
                bits += 5;
399
            if (++s->mant1_cnt == 3)
400
                s->mant1_cnt = 0;
401
            break;
402
        case 2:
403
            /* 3 mantissa in 7 bits */
404 115329f1 Diego Biurrun
            if (s->mant2_cnt == 0)
405 de6d9b64 Fabrice Bellard
                bits += 7;
406
            if (++s->mant2_cnt == 3)
407
                s->mant2_cnt = 0;
408
            break;
409
        case 3:
410
            bits += 3;
411
            break;
412
        case 4:
413
            /* 2 mantissa in 7 bits */
414
            if (s->mant4_cnt == 0)
415
                bits += 7;
416 115329f1 Diego Biurrun
            if (++s->mant4_cnt == 2)
417 de6d9b64 Fabrice Bellard
                s->mant4_cnt = 0;
418
            break;
419
        case 14:
420
            bits += 14;
421
            break;
422
        case 15:
423
            bits += 16;
424
            break;
425
        default:
426
            bits += mant - 1;
427
            break;
428
        }
429
    }
430
    return bits;
431
}
432
433
434 bbd16dea Justin Ruggles
static void bit_alloc_masking(AC3EncodeContext *s,
435
                              uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
436
                              uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
437
                              int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
438
                              int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
439
{
440
    int blk, ch;
441
    int16_t bndpsd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
442
443
    for(blk=0; blk<NB_BLOCKS; blk++) {
444
        for(ch=0;ch<s->nb_all_channels;ch++) {
445
            if(exp_strategy[blk][ch] == EXP_REUSE) {
446
                memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
447
                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
448
            } else {
449
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
450
                                          s->nb_coefs[ch],
451
                                          psd[blk][ch], bndpsd[blk][ch]);
452
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, bndpsd[blk][ch],
453
                                           0, s->nb_coefs[ch],
454
                                           ff_fgaintab[s->fgaincod[ch]],
455
                                           ch == s->lfe_channel,
456
                                           2, 0, NULL, NULL, NULL,
457
                                           mask[blk][ch]);
458
            }
459
        }
460
    }
461
}
462
463 de6d9b64 Fabrice Bellard
static int bit_alloc(AC3EncodeContext *s,
464 bbd16dea Justin Ruggles
                     int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
465
                     int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
466 0c1a9eda Zdenek Kabelac
                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
467 de6d9b64 Fabrice Bellard
                     int frame_bits, int csnroffst, int fsnroffst)
468
{
469
    int i, ch;
470 319708da Justin Ruggles
    int snroffset;
471
472
    snroffset = (((csnroffst - 15) << 4) + fsnroffst) << 2;
473 de6d9b64 Fabrice Bellard
474
    /* compute size */
475
    for(i=0;i<NB_BLOCKS;i++) {
476
        s->mant1_cnt = 0;
477
        s->mant2_cnt = 0;
478
        s->mant4_cnt = 0;
479 30b68f33 Zdenek Kabelac
        for(ch=0;ch<s->nb_all_channels;ch++) {
480 d971a5fa Justin Ruggles
            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
481
                                      s->nb_coefs[ch], snroffset,
482 bbd16dea Justin Ruggles
                                      s->bit_alloc.floor, bap[i][ch]);
483 115329f1 Diego Biurrun
            frame_bits += compute_mantissa_size(s, bap[i][ch],
484 de6d9b64 Fabrice Bellard
                                                 s->nb_coefs[ch]);
485
        }
486
    }
487
#if 0
488 115329f1 Diego Biurrun
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
489
           csnroffst, fsnroffst, frame_bits,
490 de6d9b64 Fabrice Bellard
           16 * s->frame_size - ((frame_bits + 7) & ~7));
491
#endif
492
    return 16 * s->frame_size - frame_bits;
493
}
494
495
#define SNR_INC1 4
496
497
static int compute_bit_allocation(AC3EncodeContext *s,
498 0c1a9eda Zdenek Kabelac
                                  uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
499
                                  uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
500
                                  uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
501 de6d9b64 Fabrice Bellard
                                  int frame_bits)
502
{
503
    int i, ch;
504
    int csnroffst, fsnroffst;
505 0c1a9eda Zdenek Kabelac
    uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
506 bbd16dea Justin Ruggles
    int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
507
    int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
508 30b68f33 Zdenek Kabelac
    static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
509 de6d9b64 Fabrice Bellard
510
    /* init default parameters */
511
    s->sdecaycod = 2;
512
    s->fdecaycod = 1;
513
    s->sgaincod = 1;
514
    s->dbkneecod = 2;
515
    s->floorcod = 4;
516 115329f1 Diego Biurrun
    for(ch=0;ch<s->nb_all_channels;ch++)
517 de6d9b64 Fabrice Bellard
        s->fgaincod[ch] = 4;
518 115329f1 Diego Biurrun
519 de6d9b64 Fabrice Bellard
    /* compute real values */
520 6107fa87 Fabrice Bellard
    s->bit_alloc.fscod = s->fscod;
521
    s->bit_alloc.halfratecod = s->halfratecod;
522 4258a0a3 Justin Ruggles
    s->bit_alloc.sdecay = ff_sdecaytab[s->sdecaycod] >> s->halfratecod;
523
    s->bit_alloc.fdecay = ff_fdecaytab[s->fdecaycod] >> s->halfratecod;
524
    s->bit_alloc.sgain = ff_sgaintab[s->sgaincod];
525
    s->bit_alloc.dbknee = ff_dbkneetab[s->dbkneecod];
526
    s->bit_alloc.floor = ff_floortab[s->floorcod];
527 115329f1 Diego Biurrun
528 de6d9b64 Fabrice Bellard
    /* header size */
529
    frame_bits += 65;
530 30b68f33 Zdenek Kabelac
    // if (s->acmod == 2)
531
    //    frame_bits += 2;
532
    frame_bits += frame_bits_inc[s->acmod];
533 de6d9b64 Fabrice Bellard
534
    /* audio blocks */
535
    for(i=0;i<NB_BLOCKS;i++) {
536 30b68f33 Zdenek Kabelac
        frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
537 132041f0 Justin Ruggles
        if (s->acmod == 2) {
538 30b68f33 Zdenek Kabelac
            frame_bits++; /* rematstr */
539 132041f0 Justin Ruggles
            if(i==0) frame_bits += 4;
540
        }
541 30b68f33 Zdenek Kabelac
        frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
542 bb270c08 Diego Biurrun
        if (s->lfe)
543
            frame_bits++; /* lfeexpstr */
544 de6d9b64 Fabrice Bellard
        for(ch=0;ch<s->nb_channels;ch++) {
545
            if (exp_strategy[i][ch] != EXP_REUSE)
546 30b68f33 Zdenek Kabelac
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
547 de6d9b64 Fabrice Bellard
        }
548
        frame_bits++; /* baie */
549
        frame_bits++; /* snr */
550
        frame_bits += 2; /* delta / skip */
551
    }
552
    frame_bits++; /* cplinu for block 0 */
553
    /* bit alloc info */
554 30b68f33 Zdenek Kabelac
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
555
    /* csnroffset[6] */
556
    /* (fsnoffset[4] + fgaincod[4]) * c */
557
    frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
558 de6d9b64 Fabrice Bellard
559 9ab2717a Michael Niedermayer
    /* auxdatae, crcrsv */
560
    frame_bits += 2;
561
562 de6d9b64 Fabrice Bellard
    /* CRC */
563
    frame_bits += 16;
564
565 bbd16dea Justin Ruggles
    /* calculate psd and masking curve before doing bit allocation */
566
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
567
568 de6d9b64 Fabrice Bellard
    /* now the big work begins : do the bit allocation. Modify the snr
569
       offset until we can pack everything in the requested frame size */
570
571
    csnroffst = s->csnroffst;
572 115329f1 Diego Biurrun
    while (csnroffst >= 0 &&
573 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap, frame_bits, csnroffst, 0) < 0)
574 bb270c08 Diego Biurrun
        csnroffst -= SNR_INC1;
575 de6d9b64 Fabrice Bellard
    if (csnroffst < 0) {
576 5b663851 Benjamin Larsson
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
577 bb270c08 Diego Biurrun
        return -1;
578 de6d9b64 Fabrice Bellard
    }
579 115329f1 Diego Biurrun
    while ((csnroffst + SNR_INC1) <= 63 &&
580 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
581 de6d9b64 Fabrice Bellard
                     csnroffst + SNR_INC1, 0) >= 0) {
582
        csnroffst += SNR_INC1;
583
        memcpy(bap, bap1, sizeof(bap1));
584
    }
585 115329f1 Diego Biurrun
    while ((csnroffst + 1) <= 63 &&
586 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits, csnroffst + 1, 0) >= 0) {
587 de6d9b64 Fabrice Bellard
        csnroffst++;
588
        memcpy(bap, bap1, sizeof(bap1));
589
    }
590
591
    fsnroffst = 0;
592 115329f1 Diego Biurrun
    while ((fsnroffst + SNR_INC1) <= 15 &&
593 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
594 de6d9b64 Fabrice Bellard
                     csnroffst, fsnroffst + SNR_INC1) >= 0) {
595
        fsnroffst += SNR_INC1;
596
        memcpy(bap, bap1, sizeof(bap1));
597
    }
598 115329f1 Diego Biurrun
    while ((fsnroffst + 1) <= 15 &&
599 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
600 de6d9b64 Fabrice Bellard
                     csnroffst, fsnroffst + 1) >= 0) {
601
        fsnroffst++;
602
        memcpy(bap, bap1, sizeof(bap1));
603
    }
604 115329f1 Diego Biurrun
605 de6d9b64 Fabrice Bellard
    s->csnroffst = csnroffst;
606 30b68f33 Zdenek Kabelac
    for(ch=0;ch<s->nb_all_channels;ch++)
607 de6d9b64 Fabrice Bellard
        s->fsnroffst[ch] = fsnroffst;
608
#if defined(DEBUG_BITALLOC)
609
    {
610
        int j;
611
612
        for(i=0;i<6;i++) {
613 30b68f33 Zdenek Kabelac
            for(ch=0;ch<s->nb_all_channels;ch++) {
614 de6d9b64 Fabrice Bellard
                printf("Block #%d Ch%d:\n", i, ch);
615
                printf("bap=");
616
                for(j=0;j<s->nb_coefs[ch];j++) {
617
                    printf("%d ",bap[i][ch][j]);
618
                }
619
                printf("\n");
620
            }
621
        }
622
    }
623
#endif
624
    return 0;
625
}
626
627
static int AC3_encode_init(AVCodecContext *avctx)
628
{
629
    int freq = avctx->sample_rate;
630
    int bitrate = avctx->bit_rate;
631
    int channels = avctx->channels;
632
    AC3EncodeContext *s = avctx->priv_data;
633 6107fa87 Fabrice Bellard
    int i, j, ch;
634 de6d9b64 Fabrice Bellard
    float alpha;
635 0c1a9eda Zdenek Kabelac
    static const uint8_t acmod_defs[6] = {
636 bb270c08 Diego Biurrun
        0x01, /* C */
637
        0x02, /* L R */
638
        0x03, /* L C R */
639
        0x06, /* L R SL SR */
640
        0x07, /* L C R SL SR */
641
        0x07, /* L C R SL SR (+LFE) */
642 30b68f33 Zdenek Kabelac
    };
643 de6d9b64 Fabrice Bellard
644
    avctx->frame_size = AC3_FRAME_SIZE;
645 115329f1 Diego Biurrun
646 050aa8b9 Justin Ruggles
    ac3_common_init();
647
648 de6d9b64 Fabrice Bellard
    /* number of channels */
649 30b68f33 Zdenek Kabelac
    if (channels < 1 || channels > 6)
650 bb270c08 Diego Biurrun
        return -1;
651 30b68f33 Zdenek Kabelac
    s->acmod = acmod_defs[channels - 1];
652
    s->lfe = (channels == 6) ? 1 : 0;
653
    s->nb_all_channels = channels;
654
    s->nb_channels = channels > 5 ? 5 : channels;
655
    s->lfe_channel = s->lfe ? 5 : -1;
656 de6d9b64 Fabrice Bellard
657
    /* frequency */
658
    for(i=0;i<3;i++) {
659 115329f1 Diego Biurrun
        for(j=0;j<3;j++)
660 4258a0a3 Justin Ruggles
            if ((ff_ac3_freqs[j] >> i) == freq)
661 de6d9b64 Fabrice Bellard
                goto found;
662
    }
663
    return -1;
664 115329f1 Diego Biurrun
 found:
665 de6d9b64 Fabrice Bellard
    s->sample_rate = freq;
666
    s->halfratecod = i;
667
    s->fscod = j;
668
    s->bsid = 8 + s->halfratecod;
669
    s->bsmod = 0; /* complete main audio service */
670
671
    /* bitrate & frame size */
672
    bitrate /= 1000;
673
    for(i=0;i<19;i++) {
674 4258a0a3 Justin Ruggles
        if ((ff_ac3_bitratetab[i] >> s->halfratecod) == bitrate)
675 de6d9b64 Fabrice Bellard
            break;
676
    }
677
    if (i == 19)
678
        return -1;
679
    s->bit_rate = bitrate;
680
    s->frmsizecod = i << 1;
681 050aa8b9 Justin Ruggles
    s->frame_size_min = ff_ac3_frame_sizes[s->frmsizecod][s->fscod];
682 f760b70f Justin Ruggles
    s->bits_written = 0;
683
    s->samples_written = 0;
684 de6d9b64 Fabrice Bellard
    s->frame_size = s->frame_size_min;
685 115329f1 Diego Biurrun
686 de6d9b64 Fabrice Bellard
    /* bit allocation init */
687
    for(ch=0;ch<s->nb_channels;ch++) {
688
        /* bandwidth for each channel */
689
        /* XXX: should compute the bandwidth according to the frame
690
           size, so that we avoid anoying high freq artefacts */
691
        s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
692
        s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
693
    }
694 30b68f33 Zdenek Kabelac
    if (s->lfe) {
695 bb270c08 Diego Biurrun
        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
696 30b68f33 Zdenek Kabelac
    }
697 de6d9b64 Fabrice Bellard
    /* initial snr offset */
698
    s->csnroffst = 40;
699
700
    /* mdct init */
701
    fft_init(MDCT_NBITS - 2);
702
    for(i=0;i<N/4;i++) {
703
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
704
        xcos1[i] = fix15(-cos(alpha));
705
        xsin1[i] = fix15(-sin(alpha));
706
    }
707
708 492cd3a9 Michael Niedermayer
    avctx->coded_frame= avcodec_alloc_frame();
709
    avctx->coded_frame->key_frame= 1;
710 de6d9b64 Fabrice Bellard
711
    return 0;
712
}
713
714
/* output the AC3 frame header */
715
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
716
{
717 ed7debda Alex Beregszaszi
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
718 de6d9b64 Fabrice Bellard
719
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
720
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
721
    put_bits(&s->pb, 2, s->fscod);
722
    put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
723
    put_bits(&s->pb, 5, s->bsid);
724
    put_bits(&s->pb, 3, s->bsmod);
725
    put_bits(&s->pb, 3, s->acmod);
726 30b68f33 Zdenek Kabelac
    if ((s->acmod & 0x01) && s->acmod != 0x01)
727 bb270c08 Diego Biurrun
        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
728 30b68f33 Zdenek Kabelac
    if (s->acmod & 0x04)
729 bb270c08 Diego Biurrun
        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
730 30b68f33 Zdenek Kabelac
    if (s->acmod == 0x02)
731 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 2, 0); /* surround not indicated */
732 30b68f33 Zdenek Kabelac
    put_bits(&s->pb, 1, s->lfe); /* LFE */
733 de6d9b64 Fabrice Bellard
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
734
    put_bits(&s->pb, 1, 0); /* no compression control word */
735
    put_bits(&s->pb, 1, 0); /* no lang code */
736
    put_bits(&s->pb, 1, 0); /* no audio production info */
737
    put_bits(&s->pb, 1, 0); /* no copyright */
738
    put_bits(&s->pb, 1, 1); /* original bitstream */
739
    put_bits(&s->pb, 1, 0); /* no time code 1 */
740
    put_bits(&s->pb, 1, 0); /* no time code 2 */
741
    put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
742
}
743
744
/* symetric quantization on 'levels' levels */
745
static inline int sym_quant(int c, int e, int levels)
746
{
747
    int v;
748
749
    if (c >= 0) {
750 8d67072f Fabrice Bellard
        v = (levels * (c << e)) >> 24;
751
        v = (v + 1) >> 1;
752 de6d9b64 Fabrice Bellard
        v = (levels >> 1) + v;
753
    } else {
754 8d67072f Fabrice Bellard
        v = (levels * ((-c) << e)) >> 24;
755
        v = (v + 1) >> 1;
756 de6d9b64 Fabrice Bellard
        v = (levels >> 1) - v;
757
    }
758
    assert (v >= 0 && v < levels);
759
    return v;
760
}
761
762
/* asymetric quantization on 2^qbits levels */
763
static inline int asym_quant(int c, int e, int qbits)
764
{
765
    int lshift, m, v;
766
767
    lshift = e + qbits - 24;
768
    if (lshift >= 0)
769
        v = c << lshift;
770
    else
771
        v = c >> (-lshift);
772
    /* rounding */
773
    v = (v + 1) >> 1;
774
    m = (1 << (qbits-1));
775
    if (v >= m)
776
        v = m - 1;
777
    assert(v >= -m);
778
    return v & ((1 << qbits)-1);
779
}
780
781
/* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
782
   frame */
783
static void output_audio_block(AC3EncodeContext *s,
784 0c1a9eda Zdenek Kabelac
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
785
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
786
                               uint8_t bap[AC3_MAX_CHANNELS][N/2],
787
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
788
                               int8_t global_exp[AC3_MAX_CHANNELS],
789 de6d9b64 Fabrice Bellard
                               int block_num)
790
{
791 743739d2 Michael Niedermayer
    int ch, nb_groups, group_size, i, baie, rbnd;
792 0c1a9eda Zdenek Kabelac
    uint8_t *p;
793
    uint16_t qmant[AC3_MAX_CHANNELS][N/2];
794 de6d9b64 Fabrice Bellard
    int exp0, exp1;
795
    int mant1_cnt, mant2_cnt, mant4_cnt;
796 0c1a9eda Zdenek Kabelac
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
797 de6d9b64 Fabrice Bellard
    int delta0, delta1, delta2;
798
799 115329f1 Diego Biurrun
    for(ch=0;ch<s->nb_channels;ch++)
800 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
801 115329f1 Diego Biurrun
    for(ch=0;ch<s->nb_channels;ch++)
802 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 1); /* no dither */
803
    put_bits(&s->pb, 1, 0); /* no dynamic range */
804
    if (block_num == 0) {
805
        /* for block 0, even if no coupling, we must say it. This is a
806
           waste of bit :-) */
807
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
808
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
809
    } else {
810
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
811
    }
812
813 743739d2 Michael Niedermayer
    if (s->acmod == 2)
814
      {
815 bb270c08 Diego Biurrun
        if(block_num==0)
816
          {
817
            /* first block must define rematrixing (rematstr)  */
818
            put_bits(&s->pb, 1, 1);
819
820
            /* dummy rematrixing rematflg(1:4)=0 */
821
            for (rbnd=0;rbnd<4;rbnd++)
822
              put_bits(&s->pb, 1, 0);
823
          }
824
        else
825
          {
826
            /* no matrixing (but should be used in the future) */
827
            put_bits(&s->pb, 1, 0);
828
          }
829 743739d2 Michael Niedermayer
      }
830 de6d9b64 Fabrice Bellard
831 115329f1 Diego Biurrun
#if defined(DEBUG)
832 de6d9b64 Fabrice Bellard
    {
833 743739d2 Michael Niedermayer
      static int count = 0;
834 3d0ef6dd Michael Niedermayer
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
835 de6d9b64 Fabrice Bellard
    }
836
#endif
837
    /* exponent strategy */
838
    for(ch=0;ch<s->nb_channels;ch++) {
839
        put_bits(&s->pb, 2, exp_strategy[ch]);
840
    }
841 115329f1 Diego Biurrun
842 30b68f33 Zdenek Kabelac
    if (s->lfe) {
843 bb270c08 Diego Biurrun
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
844 30b68f33 Zdenek Kabelac
    }
845
846 de6d9b64 Fabrice Bellard
    for(ch=0;ch<s->nb_channels;ch++) {
847
        if (exp_strategy[ch] != EXP_REUSE)
848
            put_bits(&s->pb, 6, s->chbwcod[ch]);
849
    }
850 115329f1 Diego Biurrun
851 de6d9b64 Fabrice Bellard
    /* exponents */
852 30b68f33 Zdenek Kabelac
    for (ch = 0; ch < s->nb_all_channels; ch++) {
853 de6d9b64 Fabrice Bellard
        switch(exp_strategy[ch]) {
854
        case EXP_REUSE:
855
            continue;
856
        case EXP_D15:
857
            group_size = 1;
858
            break;
859
        case EXP_D25:
860
            group_size = 2;
861
            break;
862
        default:
863
        case EXP_D45:
864
            group_size = 4;
865
            break;
866
        }
867 bb270c08 Diego Biurrun
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
868 de6d9b64 Fabrice Bellard
        p = encoded_exp[ch];
869
870
        /* first exponent */
871
        exp1 = *p++;
872
        put_bits(&s->pb, 4, exp1);
873
874
        /* next ones are delta encoded */
875
        for(i=0;i<nb_groups;i++) {
876
            /* merge three delta in one code */
877
            exp0 = exp1;
878
            exp1 = p[0];
879
            p += group_size;
880
            delta0 = exp1 - exp0 + 2;
881
882
            exp0 = exp1;
883
            exp1 = p[0];
884
            p += group_size;
885
            delta1 = exp1 - exp0 + 2;
886
887
            exp0 = exp1;
888
            exp1 = p[0];
889
            p += group_size;
890
            delta2 = exp1 - exp0 + 2;
891
892
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
893
        }
894
895 bb270c08 Diego Biurrun
        if (ch != s->lfe_channel)
896
            put_bits(&s->pb, 2, 0); /* no gain range info */
897 de6d9b64 Fabrice Bellard
    }
898
899
    /* bit allocation info */
900
    baie = (block_num == 0);
901
    put_bits(&s->pb, 1, baie);
902
    if (baie) {
903
        put_bits(&s->pb, 2, s->sdecaycod);
904
        put_bits(&s->pb, 2, s->fdecaycod);
905
        put_bits(&s->pb, 2, s->sgaincod);
906
        put_bits(&s->pb, 2, s->dbkneecod);
907
        put_bits(&s->pb, 3, s->floorcod);
908
    }
909
910
    /* snr offset */
911
    put_bits(&s->pb, 1, baie); /* always present with bai */
912
    if (baie) {
913
        put_bits(&s->pb, 6, s->csnroffst);
914 30b68f33 Zdenek Kabelac
        for(ch=0;ch<s->nb_all_channels;ch++) {
915 de6d9b64 Fabrice Bellard
            put_bits(&s->pb, 4, s->fsnroffst[ch]);
916
            put_bits(&s->pb, 3, s->fgaincod[ch]);
917
        }
918
    }
919 115329f1 Diego Biurrun
920 de6d9b64 Fabrice Bellard
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
921
    put_bits(&s->pb, 1, 0); /* no data to skip */
922
923
    /* mantissa encoding : we use two passes to handle the grouping. A
924
       one pass method may be faster, but it would necessitate to
925
       modify the output stream. */
926
927
    /* first pass: quantize */
928
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
929
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
930
931 30b68f33 Zdenek Kabelac
    for (ch = 0; ch < s->nb_all_channels; ch++) {
932 de6d9b64 Fabrice Bellard
        int b, c, e, v;
933
934
        for(i=0;i<s->nb_coefs[ch];i++) {
935
            c = mdct_coefs[ch][i];
936
            e = encoded_exp[ch][i] - global_exp[ch];
937
            b = bap[ch][i];
938
            switch(b) {
939
            case 0:
940
                v = 0;
941
                break;
942
            case 1:
943
                v = sym_quant(c, e, 3);
944
                switch(mant1_cnt) {
945
                case 0:
946
                    qmant1_ptr = &qmant[ch][i];
947
                    v = 9 * v;
948
                    mant1_cnt = 1;
949
                    break;
950
                case 1:
951
                    *qmant1_ptr += 3 * v;
952
                    mant1_cnt = 2;
953
                    v = 128;
954
                    break;
955
                default:
956
                    *qmant1_ptr += v;
957
                    mant1_cnt = 0;
958
                    v = 128;
959
                    break;
960
                }
961
                break;
962
            case 2:
963
                v = sym_quant(c, e, 5);
964
                switch(mant2_cnt) {
965
                case 0:
966
                    qmant2_ptr = &qmant[ch][i];
967
                    v = 25 * v;
968
                    mant2_cnt = 1;
969
                    break;
970
                case 1:
971
                    *qmant2_ptr += 5 * v;
972
                    mant2_cnt = 2;
973
                    v = 128;
974
                    break;
975
                default:
976
                    *qmant2_ptr += v;
977
                    mant2_cnt = 0;
978
                    v = 128;
979
                    break;
980
                }
981
                break;
982
            case 3:
983
                v = sym_quant(c, e, 7);
984
                break;
985
            case 4:
986
                v = sym_quant(c, e, 11);
987
                switch(mant4_cnt) {
988
                case 0:
989
                    qmant4_ptr = &qmant[ch][i];
990
                    v = 11 * v;
991
                    mant4_cnt = 1;
992
                    break;
993
                default:
994
                    *qmant4_ptr += v;
995
                    mant4_cnt = 0;
996
                    v = 128;
997
                    break;
998
                }
999
                break;
1000
            case 5:
1001
                v = sym_quant(c, e, 15);
1002
                break;
1003
            case 14:
1004
                v = asym_quant(c, e, 14);
1005
                break;
1006
            case 15:
1007
                v = asym_quant(c, e, 16);
1008
                break;
1009
            default:
1010
                v = asym_quant(c, e, b - 1);
1011
                break;
1012
            }
1013
            qmant[ch][i] = v;
1014
        }
1015
    }
1016
1017
    /* second pass : output the values */
1018 30b68f33 Zdenek Kabelac
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1019 de6d9b64 Fabrice Bellard
        int b, q;
1020 115329f1 Diego Biurrun
1021 de6d9b64 Fabrice Bellard
        for(i=0;i<s->nb_coefs[ch];i++) {
1022
            q = qmant[ch][i];
1023
            b = bap[ch][i];
1024
            switch(b) {
1025
            case 0:
1026
                break;
1027
            case 1:
1028 115329f1 Diego Biurrun
                if (q != 128)
1029 de6d9b64 Fabrice Bellard
                    put_bits(&s->pb, 5, q);
1030
                break;
1031
            case 2:
1032 115329f1 Diego Biurrun
                if (q != 128)
1033 de6d9b64 Fabrice Bellard
                    put_bits(&s->pb, 7, q);
1034
                break;
1035
            case 3:
1036
                put_bits(&s->pb, 3, q);
1037
                break;
1038
            case 4:
1039
                if (q != 128)
1040
                    put_bits(&s->pb, 7, q);
1041
                break;
1042
            case 14:
1043
                put_bits(&s->pb, 14, q);
1044
                break;
1045
            case 15:
1046
                put_bits(&s->pb, 16, q);
1047
                break;
1048
            default:
1049
                put_bits(&s->pb, b - 1, q);
1050
                break;
1051
            }
1052
        }
1053
    }
1054
}
1055
1056
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1057
1058
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1059
{
1060
    unsigned int c;
1061
1062
    c = 0;
1063
    while (a) {
1064
        if (a & 1)
1065
            c ^= b;
1066
        a = a >> 1;
1067
        b = b << 1;
1068
        if (b & (1 << 16))
1069
            b ^= poly;
1070
    }
1071
    return c;
1072
}
1073
1074
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1075
{
1076
    unsigned int r;
1077
    r = 1;
1078
    while (n) {
1079
        if (n & 1)
1080
            r = mul_poly(r, a, poly);
1081
        a = mul_poly(a, a, poly);
1082
        n >>= 1;
1083
    }
1084
    return r;
1085
}
1086
1087
1088
/* compute log2(max(abs(tab[]))) */
1089 0c1a9eda Zdenek Kabelac
static int log2_tab(int16_t *tab, int n)
1090 de6d9b64 Fabrice Bellard
{
1091
    int i, v;
1092
1093
    v = 0;
1094
    for(i=0;i<n;i++) {
1095
        v |= abs(tab[i]);
1096
    }
1097 34763c15 Fabrice Bellard
    return av_log2(v);
1098 de6d9b64 Fabrice Bellard
}
1099
1100 0c1a9eda Zdenek Kabelac
static void lshift_tab(int16_t *tab, int n, int lshift)
1101 de6d9b64 Fabrice Bellard
{
1102
    int i;
1103
1104
    if (lshift > 0) {
1105
        for(i=0;i<n;i++) {
1106
            tab[i] <<= lshift;
1107
        }
1108
    } else if (lshift < 0) {
1109
        lshift = -lshift;
1110
        for(i=0;i<n;i++) {
1111
            tab[i] >>= lshift;
1112
        }
1113
    }
1114
}
1115
1116
/* fill the end of the frame and compute the two crcs */
1117
static int output_frame_end(AC3EncodeContext *s)
1118
{
1119
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1120 0c1a9eda Zdenek Kabelac
    uint8_t *frame;
1121 de6d9b64 Fabrice Bellard
1122
    frame_size = s->frame_size; /* frame size in words */
1123
    /* align to 8 bits */
1124
    flush_put_bits(&s->pb);
1125
    /* add zero bytes to reach the frame size */
1126
    frame = s->pb.buf;
1127 17592475 Michael Niedermayer
    n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1128 de6d9b64 Fabrice Bellard
    assert(n >= 0);
1129 743739d2 Michael Niedermayer
    if(n>0)
1130
      memset(pbBufPtr(&s->pb), 0, n);
1131 115329f1 Diego Biurrun
1132 de6d9b64 Fabrice Bellard
    /* Now we must compute both crcs : this is not so easy for crc1
1133
       because it is at the beginning of the data... */
1134
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1135 e027d0a8 Michael Niedermayer
    crc1 = bswap_16(av_crc(av_crc8005, 0, frame + 4, 2 * frame_size_58 - 4));
1136 de6d9b64 Fabrice Bellard
    /* XXX: could precompute crc_inv */
1137
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1138
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1139
    frame[2] = crc1 >> 8;
1140
    frame[3] = crc1;
1141 115329f1 Diego Biurrun
1142 e027d0a8 Michael Niedermayer
    crc2 = bswap_16(av_crc(av_crc8005, 0, frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2));
1143 de6d9b64 Fabrice Bellard
    frame[2*frame_size - 2] = crc2 >> 8;
1144
    frame[2*frame_size - 1] = crc2;
1145
1146
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1147
    return frame_size * 2;
1148
}
1149
1150 6107fa87 Fabrice Bellard
static int AC3_encode_frame(AVCodecContext *avctx,
1151
                            unsigned char *frame, int buf_size, void *data)
1152 de6d9b64 Fabrice Bellard
{
1153
    AC3EncodeContext *s = avctx->priv_data;
1154 21d7e2ff Jeff Muizelaar
    int16_t *samples = data;
1155 de6d9b64 Fabrice Bellard
    int i, j, k, v, ch;
1156 0c1a9eda Zdenek Kabelac
    int16_t input_samples[N];
1157
    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1158
    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1159
    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1160
    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1161
    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1162
    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1163 de6d9b64 Fabrice Bellard
    int frame_bits;
1164
1165
    frame_bits = 0;
1166 30b68f33 Zdenek Kabelac
    for(ch=0;ch<s->nb_all_channels;ch++) {
1167 de6d9b64 Fabrice Bellard
        /* fixed mdct to the six sub blocks & exponent computation */
1168
        for(i=0;i<NB_BLOCKS;i++) {
1169 0c1a9eda Zdenek Kabelac
            int16_t *sptr;
1170 de6d9b64 Fabrice Bellard
            int sinc;
1171
1172
            /* compute input samples */
1173 0c1a9eda Zdenek Kabelac
            memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1174 30b68f33 Zdenek Kabelac
            sinc = s->nb_all_channels;
1175 de6d9b64 Fabrice Bellard
            sptr = samples + (sinc * (N/2) * i) + ch;
1176
            for(j=0;j<N/2;j++) {
1177
                v = *sptr;
1178
                input_samples[j + N/2] = v;
1179 115329f1 Diego Biurrun
                s->last_samples[ch][j] = v;
1180 de6d9b64 Fabrice Bellard
                sptr += sinc;
1181
            }
1182
1183
            /* apply the MDCT window */
1184
            for(j=0;j<N/2;j++) {
1185 115329f1 Diego Biurrun
                input_samples[j] = MUL16(input_samples[j],
1186 4258a0a3 Justin Ruggles
                                         ff_ac3_window[j]) >> 15;
1187 115329f1 Diego Biurrun
                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1188 4258a0a3 Justin Ruggles
                                             ff_ac3_window[j]) >> 15;
1189 de6d9b64 Fabrice Bellard
            }
1190 115329f1 Diego Biurrun
1191 de6d9b64 Fabrice Bellard
            /* Normalize the samples to use the maximum available
1192
               precision */
1193
            v = 14 - log2_tab(input_samples, N);
1194
            if (v < 0)
1195
                v = 0;
1196 4140a523 Bill O'Shaughnessy
            exp_samples[i][ch] = v - 9;
1197 de6d9b64 Fabrice Bellard
            lshift_tab(input_samples, N, v);
1198
1199
            /* do the MDCT */
1200
            mdct512(mdct_coef[i][ch], input_samples);
1201 115329f1 Diego Biurrun
1202 de6d9b64 Fabrice Bellard
            /* compute "exponents". We take into account the
1203
               normalization there */
1204
            for(j=0;j<N/2;j++) {
1205
                int e;
1206
                v = abs(mdct_coef[i][ch][j]);
1207
                if (v == 0)
1208
                    e = 24;
1209
                else {
1210 34763c15 Fabrice Bellard
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1211 de6d9b64 Fabrice Bellard
                    if (e >= 24) {
1212
                        e = 24;
1213
                        mdct_coef[i][ch][j] = 0;
1214
                    }
1215
                }
1216
                exp[i][ch][j] = e;
1217
            }
1218
        }
1219 115329f1 Diego Biurrun
1220 30b68f33 Zdenek Kabelac
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1221 de6d9b64 Fabrice Bellard
1222
        /* compute the exponents as the decoder will see them. The
1223
           EXP_REUSE case must be handled carefully : we select the
1224
           min of the exponents */
1225
        i = 0;
1226
        while (i < NB_BLOCKS) {
1227
            j = i + 1;
1228
            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1229
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1230
                j++;
1231
            }
1232
            frame_bits += encode_exp(encoded_exp[i][ch],
1233 115329f1 Diego Biurrun
                                     exp[i][ch], s->nb_coefs[ch],
1234 de6d9b64 Fabrice Bellard
                                     exp_strategy[i][ch]);
1235
            /* copy encoded exponents for reuse case */
1236
            for(k=i+1;k<j;k++) {
1237 115329f1 Diego Biurrun
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1238 0c1a9eda Zdenek Kabelac
                       s->nb_coefs[ch] * sizeof(uint8_t));
1239 de6d9b64 Fabrice Bellard
            }
1240
            i = j;
1241
        }
1242
    }
1243
1244 f760b70f Justin Ruggles
    /* adjust for fractional frame sizes */
1245
    while(s->bits_written >= s->bit_rate*1000 && s->samples_written >= s->sample_rate) {
1246
        s->bits_written -= s->bit_rate*1000;
1247
        s->samples_written -= s->sample_rate;
1248
    }
1249
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate*1000);
1250
    s->bits_written += s->frame_size * 16;
1251
    s->samples_written += AC3_FRAME_SIZE;
1252
1253 de6d9b64 Fabrice Bellard
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1254
    /* everything is known... let's output the frame */
1255
    output_frame_header(s, frame);
1256 115329f1 Diego Biurrun
1257 de6d9b64 Fabrice Bellard
    for(i=0;i<NB_BLOCKS;i++) {
1258 115329f1 Diego Biurrun
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1259 de6d9b64 Fabrice Bellard
                           bap[i], mdct_coef[i], exp_samples[i], i);
1260
    }
1261
    return output_frame_end(s);
1262
}
1263
1264 492cd3a9 Michael Niedermayer
static int AC3_encode_close(AVCodecContext *avctx)
1265
{
1266
    av_freep(&avctx->coded_frame);
1267 ef9f7306 Måns Rullgård
    return 0;
1268 492cd3a9 Michael Niedermayer
}
1269
1270 de6d9b64 Fabrice Bellard
#if 0
1271
/*************************************************************************/
1272
/* TEST */
1273

1274
#define FN (N/4)
1275

1276
void fft_test(void)
1277
{
1278
    IComplex in[FN], in1[FN];
1279
    int k, n, i;
1280
    float sum_re, sum_im, a;
1281

1282
    /* FFT test */
1283

1284
    for(i=0;i<FN;i++) {
1285
        in[i].re = random() % 65535 - 32767;
1286
        in[i].im = random() % 65535 - 32767;
1287
        in1[i] = in[i];
1288
    }
1289
    fft(in, 7);
1290

1291
    /* do it by hand */
1292
    for(k=0;k<FN;k++) {
1293
        sum_re = 0;
1294
        sum_im = 0;
1295
        for(n=0;n<FN;n++) {
1296
            a = -2 * M_PI * (n * k) / FN;
1297
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1298
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1299
        }
1300 115329f1 Diego Biurrun
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1301
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1302 de6d9b64 Fabrice Bellard
    }
1303
}
1304

1305
void mdct_test(void)
1306
{
1307 0c1a9eda Zdenek Kabelac
    int16_t input[N];
1308
    int32_t output[N/2];
1309 de6d9b64 Fabrice Bellard
    float input1[N];
1310
    float output1[N/2];
1311
    float s, a, err, e, emax;
1312
    int i, k, n;
1313

1314
    for(i=0;i<N;i++) {
1315
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1316
        input1[i] = input[i];
1317
    }
1318

1319
    mdct512(output, input);
1320 115329f1 Diego Biurrun

1321 de6d9b64 Fabrice Bellard
    /* do it by hand */
1322
    for(k=0;k<N/2;k++) {
1323
        s = 0;
1324
        for(n=0;n<N;n++) {
1325
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1326
            s += input1[n] * cos(a);
1327
        }
1328
        output1[k] = -2 * s / N;
1329
    }
1330 115329f1 Diego Biurrun

1331 de6d9b64 Fabrice Bellard
    err = 0;
1332
    emax = 0;
1333
    for(i=0;i<N/2;i++) {
1334
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1335
        e = output[i] - output1[i];
1336
        if (e > emax)
1337
            emax = e;
1338
        err += e * e;
1339
    }
1340
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1341
}
1342

1343
void test_ac3(void)
1344
{
1345
    AC3EncodeContext ctx;
1346
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1347
    short samples[AC3_FRAME_SIZE];
1348
    int ret, i;
1349 115329f1 Diego Biurrun

1350 de6d9b64 Fabrice Bellard
    AC3_encode_init(&ctx, 44100, 64000, 1);
1351

1352
    fft_test();
1353
    mdct_test();
1354

1355
    for(i=0;i<AC3_FRAME_SIZE;i++)
1356
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1357
    ret = AC3_encode_frame(&ctx, frame, samples);
1358
    printf("ret=%d\n", ret);
1359
}
1360
#endif
1361
1362
AVCodec ac3_encoder = {
1363
    "ac3",
1364
    CODEC_TYPE_AUDIO,
1365
    CODEC_ID_AC3,
1366
    sizeof(AC3EncodeContext),
1367
    AC3_encode_init,
1368
    AC3_encode_frame,
1369 492cd3a9 Michael Niedermayer
    AC3_encode_close,
1370 de6d9b64 Fabrice Bellard
    NULL,
1371
};