Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 98f6ee44

History | View | Annotate | Download (46.7 KB)

1 de6d9b64 Fabrice Bellard
/*
2 14b70628 Justin Ruggles
 * The simplest AC-3 encoder
3 406792e7 Diego Biurrun
 * 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 ba87f080 Diego Biurrun
 * @file
24 14b70628 Justin Ruggles
 * The simplest AC-3 encoder.
25 983e3246 Michael Niedermayer
 */
26 6a988808 Justin Ruggles
27 1a565432 Fabrice Bellard
//#define DEBUG
28 22c0b03c Justin Ruggles
29 63e8d976 Stefano Sabatini
#include "libavcore/audioconvert.h"
30 245976da Diego Biurrun
#include "libavutil/crc.h"
31 de6d9b64 Fabrice Bellard
#include "avcodec.h"
32 b2755007 Stefano Sabatini
#include "put_bits.h"
33 6107fa87 Fabrice Bellard
#include "ac3.h"
34 120b4557 Justin Ruggles
#include "audioconvert.h"
35 6107fa87 Fabrice Bellard
36 2f8ae522 Justin Ruggles
37 e77fd066 Justin Ruggles
#define MDCT_NBITS 9
38
#define MDCT_SAMPLES (1 << MDCT_NBITS)
39
40 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^bits and convert to an integer. */
41 918cd225 Justin Ruggles
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
42
43 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
44 e77fd066 Justin Ruggles
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
45
46 2f8ae522 Justin Ruggles
47 c36ce0f8 Justin Ruggles
/**
48
 * Compex number.
49
 * Used in fixed-point MDCT calculation.
50
 */
51 e77fd066 Justin Ruggles
typedef struct IComplex {
52
    int16_t re,im;
53
} IComplex;
54
55 c36ce0f8 Justin Ruggles
/**
56
 * AC-3 encoder private context.
57
 */
58 6107fa87 Fabrice Bellard
typedef struct AC3EncodeContext {
59 07965463 Justin Ruggles
    PutBitContext pb;                       ///< bitstream writer context
60 7e5a4bf8 Justin Ruggles
61 07965463 Justin Ruggles
    int bitstream_id;                       ///< bitstream id                           (bsid)
62
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
63 7e5a4bf8 Justin Ruggles
64 07965463 Justin Ruggles
    int bit_rate;                           ///< target bit rate, in bits-per-second
65
    int sample_rate;                        ///< sampling frequency, in Hz
66 7e5a4bf8 Justin Ruggles
67 07965463 Justin Ruggles
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
68 427e2293 Justin Ruggles
    int frame_size;                         ///< current frame size in bytes
69 07965463 Justin Ruggles
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
70
    int bits_written;                       ///< bit count    (used to avg. bitrate)
71
    int samples_written;                    ///< sample count (used to avg. bitrate)
72 7e5a4bf8 Justin Ruggles
73 07965463 Justin Ruggles
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
74
    int channels;                           ///< total number of channels               (nchans)
75
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
76
    int lfe_channel;                        ///< channel index of the LFE channel
77
    int channel_mode;                       ///< channel mode                           (acmod)
78
    const uint8_t *channel_map;             ///< channel map used to reorder channels
79 7e5a4bf8 Justin Ruggles
80 07965463 Justin Ruggles
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
81 6107fa87 Fabrice Bellard
    int nb_coefs[AC3_MAX_CHANNELS];
82 115329f1 Diego Biurrun
83 6107fa87 Fabrice Bellard
    /* bitrate allocation control */
84 07965463 Justin Ruggles
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
85
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
86
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
87
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
88
    int floor_code;                         ///< floor code                             (floorcod)
89
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
90
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
91
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
92
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
93 7e5a4bf8 Justin Ruggles
94 6107fa87 Fabrice Bellard
    /* mantissa encoding */
95 07965463 Justin Ruggles
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
96 7e5a4bf8 Justin Ruggles
97 07965463 Justin Ruggles
    int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
98 6107fa87 Fabrice Bellard
} AC3EncodeContext;
99 de6d9b64 Fabrice Bellard
100 2f8ae522 Justin Ruggles
101 c36ce0f8 Justin Ruggles
/** MDCT and FFT tables */
102 4258a0a3 Justin Ruggles
static int16_t costab[64];
103
static int16_t sintab[64];
104
static int16_t xcos1[128];
105
static int16_t xsin1[128];
106 de6d9b64 Fabrice Bellard
107 2f8ae522 Justin Ruggles
108 c36ce0f8 Justin Ruggles
/**
109
 * Initialize FFT tables.
110
 * @param ln log2(FFT size)
111
 */
112 5ef251e5 Daniel Verkamp
static av_cold void fft_init(int ln)
113 de6d9b64 Fabrice Bellard
{
114 b84a211b Justin Ruggles
    int i, n, n2;
115 de6d9b64 Fabrice Bellard
    float alpha;
116
117 b84a211b Justin Ruggles
    n  = 1 << ln;
118
    n2 = n >> 1;
119 de6d9b64 Fabrice Bellard
120 b84a211b Justin Ruggles
    for (i = 0; i < n2; i++) {
121
        alpha     = 2.0 * M_PI * i / n;
122 918cd225 Justin Ruggles
        costab[i] = FIX15(cos(alpha));
123
        sintab[i] = FIX15(sin(alpha));
124 de6d9b64 Fabrice Bellard
    }
125
}
126
127 2f8ae522 Justin Ruggles
128 c36ce0f8 Justin Ruggles
/**
129
 * Initialize MDCT tables.
130
 * @param nbits log2(MDCT size)
131
 */
132 a8d2b06b Justin Ruggles
static av_cold void mdct_init(int nbits)
133
{
134 b84a211b Justin Ruggles
    int i, n, n4;
135
136
    n  = 1 << nbits;
137
    n4 = n >> 2;
138 a8d2b06b Justin Ruggles
139
    fft_init(nbits - 2);
140
141 6a988808 Justin Ruggles
    for (i = 0; i < n4; i++) {
142 b84a211b Justin Ruggles
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
143 918cd225 Justin Ruggles
        xcos1[i] = FIX15(-cos(alpha));
144
        xsin1[i] = FIX15(-sin(alpha));
145 a8d2b06b Justin Ruggles
    }
146
}
147
148 2f8ae522 Justin Ruggles
149 c36ce0f8 Justin Ruggles
/** Butterfly op */
150 6a988808 Justin Ruggles
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
151
{                                                       \
152
  int ax, ay, bx, by;                                   \
153
  bx  = pre1;                                           \
154
  by  = pim1;                                           \
155
  ax  = qre1;                                           \
156
  ay  = qim1;                                           \
157
  pre = (bx + ax) >> 1;                                 \
158
  pim = (by + ay) >> 1;                                 \
159
  qre = (bx - ax) >> 1;                                 \
160
  qim = (by - ay) >> 1;                                 \
161 de6d9b64 Fabrice Bellard
}
162
163 2f8ae522 Justin Ruggles
164 c36ce0f8 Justin Ruggles
/** Complex multiply */
165 6a988808 Justin Ruggles
#define CMUL(pre, pim, are, aim, bre, bim)              \
166
{                                                       \
167
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
168
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
169 de6d9b64 Fabrice Bellard
}
170
171
172 c36ce0f8 Justin Ruggles
/**
173
 * Calculate a 2^n point complex FFT on 2^ln points.
174
 * @param z  complex input/output samples
175
 * @param ln log2(FFT size)
176
 */
177 de6d9b64 Fabrice Bellard
static void fft(IComplex *z, int ln)
178
{
179 6a988808 Justin Ruggles
    int j, l, np, np2;
180
    int nblocks, nloops;
181 de6d9b64 Fabrice Bellard
    register IComplex *p,*q;
182
    int tmp_re, tmp_im;
183
184
    np = 1 << ln;
185
186
    /* reverse */
187 6a988808 Justin Ruggles
    for (j = 0; j < np; j++) {
188 91cc5d37 Francesco Lavra
        int k = av_reverse[j] >> (8 - ln);
189 f952b30c Reimar Döffinger
        if (k < j)
190
            FFSWAP(IComplex, z[k], z[j]);
191 de6d9b64 Fabrice Bellard
    }
192
193
    /* pass 0 */
194
195 6a988808 Justin Ruggles
    p = &z[0];
196
    j = np >> 1;
197 de6d9b64 Fabrice Bellard
    do {
198 115329f1 Diego Biurrun
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
199 de6d9b64 Fabrice Bellard
           p[0].re, p[0].im, p[1].re, p[1].im);
200 6a988808 Justin Ruggles
        p += 2;
201
    } while (--j);
202 de6d9b64 Fabrice Bellard
203
    /* pass 1 */
204
205 6a988808 Justin Ruggles
    p = &z[0];
206
    j = np >> 2;
207 de6d9b64 Fabrice Bellard
    do {
208 6a988808 Justin Ruggles
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
209
           p[0].re, p[0].im, p[2].re,  p[2].im);
210
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
211 de6d9b64 Fabrice Bellard
           p[1].re, p[1].im, p[3].im, -p[3].re);
212
        p+=4;
213 6a988808 Justin Ruggles
    } while (--j);
214 de6d9b64 Fabrice Bellard
215
    /* pass 2 .. ln-1 */
216
217
    nblocks = np >> 3;
218 6a988808 Justin Ruggles
    nloops  =  1 << 2;
219
    np2     = np >> 1;
220 de6d9b64 Fabrice Bellard
    do {
221
        p = z;
222
        q = z + nloops;
223 6a988808 Justin Ruggles
        for (j = 0; j < nblocks; j++) {
224 de6d9b64 Fabrice Bellard
            BF(p->re, p->im, q->re, q->im,
225
               p->re, p->im, q->re, q->im);
226
            p++;
227
            q++;
228
            for(l = nblocks; l < np2; l += nblocks) {
229
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
230 6a988808 Justin Ruggles
                BF(p->re, p->im, q->re,  q->im,
231 de6d9b64 Fabrice Bellard
                   p->re, p->im, tmp_re, tmp_im);
232
                p++;
233
                q++;
234
            }
235
            p += nloops;
236
            q += nloops;
237
        }
238
        nblocks = nblocks >> 1;
239 6a988808 Justin Ruggles
        nloops  = nloops  << 1;
240
    } while (nblocks);
241 de6d9b64 Fabrice Bellard
}
242
243 2f8ae522 Justin Ruggles
244 c36ce0f8 Justin Ruggles
/**
245
 * Calculate a 512-point MDCT
246
 * @param out 256 output frequency coefficients
247
 * @param in  512 windowed input audio samples
248
 */
249 0c1a9eda Zdenek Kabelac
static void mdct512(int32_t *out, int16_t *in)
250 de6d9b64 Fabrice Bellard
{
251
    int i, re, im, re1, im1;
252 7066cc8f Justin Ruggles
    int16_t rot[MDCT_SAMPLES];
253
    IComplex x[MDCT_SAMPLES/4];
254 de6d9b64 Fabrice Bellard
255
    /* shift to simplify computations */
256 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++)
257 7066cc8f Justin Ruggles
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
258 6a988808 Justin Ruggles
    for (;i < MDCT_SAMPLES; i++)
259
        rot[i] =  in[i -   MDCT_SAMPLES/4];
260 115329f1 Diego Biurrun
261 de6d9b64 Fabrice Bellard
    /* pre rotation */
262 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
263
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
264 7066cc8f Justin Ruggles
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
265 de6d9b64 Fabrice Bellard
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
266
    }
267
268
    fft(x, MDCT_NBITS - 2);
269 115329f1 Diego Biurrun
270 de6d9b64 Fabrice Bellard
    /* post rotation */
271 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
272 de6d9b64 Fabrice Bellard
        re = x[i].re;
273
        im = x[i].im;
274
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
275 6a988808 Justin Ruggles
        out[                 2*i] = im1;
276 7066cc8f Justin Ruggles
        out[MDCT_SAMPLES/2-1-2*i] = re1;
277 de6d9b64 Fabrice Bellard
    }
278
}
279
280 2f8ae522 Justin Ruggles
281 c36ce0f8 Justin Ruggles
/**
282
 * Calculate the log2() of the maximum absolute value in an array.
283
 * @param tab input array
284
 * @param n   number of values in the array
285
 * @return    log2(max(abs(tab[])))
286
 */
287 e77fd066 Justin Ruggles
static int log2_tab(int16_t *tab, int n)
288
{
289
    int i, v;
290
291
    v = 0;
292
    for (i = 0; i < n; i++)
293
        v |= abs(tab[i]);
294
295
    return av_log2(v);
296
}
297
298 2f8ae522 Justin Ruggles
299 c36ce0f8 Justin Ruggles
/**
300
 * Left-shift each value in an array by a specified amount.
301
 * @param tab    input array
302
 * @param n      number of values in the array
303
 * @param lshift left shift amount. a negative value means right shift.
304
 */
305 e77fd066 Justin Ruggles
static void lshift_tab(int16_t *tab, int n, int lshift)
306
{
307
    int i;
308
309
    if (lshift > 0) {
310
        for(i = 0; i < n; i++)
311
            tab[i] <<= lshift;
312
    } else if (lshift < 0) {
313
        lshift = -lshift;
314
        for (i = 0; i < n; i++)
315
            tab[i] >>= lshift;
316
    }
317
}
318
319 2f8ae522 Justin Ruggles
320 c36ce0f8 Justin Ruggles
/**
321
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
322
 */
323 0c1a9eda Zdenek Kabelac
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
324 de6d9b64 Fabrice Bellard
{
325
    int sum, i;
326
    sum = 0;
327 6a988808 Justin Ruggles
    for (i = 0; i < n; i++)
328 de6d9b64 Fabrice Bellard
        sum += abs(exp1[i] - exp2[i]);
329
    return sum;
330
}
331
332 2f8ae522 Justin Ruggles
333 c36ce0f8 Justin Ruggles
/**
334
 * Exponent Difference Threshold.
335
 * New exponents are sent if their SAD exceed this number.
336
 */
337 6a988808 Justin Ruggles
#define EXP_DIFF_THRESHOLD 1000
338
339 2f8ae522 Justin Ruggles
340 c36ce0f8 Justin Ruggles
/**
341
 * Calculate exponent strategies for all blocks in a single channel.
342
 */
343 23c5b361 Justin Ruggles
static void compute_exp_strategy_ch(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
344
                                    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
345
                                    int ch, int is_lfe)
346 de6d9b64 Fabrice Bellard
{
347 ce67b7cd Justin Ruggles
    int blk, blk1;
348 de6d9b64 Fabrice Bellard
    int exp_diff;
349 115329f1 Diego Biurrun
350 de6d9b64 Fabrice Bellard
    /* estimate if the exponent variation & decide if they should be
351
       reused in the next frame */
352
    exp_strategy[0][ch] = EXP_NEW;
353 ce67b7cd Justin Ruggles
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
354
        exp_diff = calc_exp_diff(exp[blk][ch], exp[blk-1][ch], AC3_MAX_COEFS);
355 de6d9b64 Fabrice Bellard
        if (exp_diff > EXP_DIFF_THRESHOLD)
356 ce67b7cd Justin Ruggles
            exp_strategy[blk][ch] = EXP_NEW;
357 de6d9b64 Fabrice Bellard
        else
358 ce67b7cd Justin Ruggles
            exp_strategy[blk][ch] = EXP_REUSE;
359 de6d9b64 Fabrice Bellard
    }
360 30b68f33 Zdenek Kabelac
    if (is_lfe)
361 bb270c08 Diego Biurrun
        return;
362 30b68f33 Zdenek Kabelac
363 de6d9b64 Fabrice Bellard
    /* now select the encoding strategy type : if exponents are often
364
       recoded, we use a coarse encoding */
365 ce67b7cd Justin Ruggles
    blk = 0;
366
    while (blk < AC3_MAX_BLOCKS) {
367
        blk1 = blk + 1;
368
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE)
369
            blk1++;
370
        switch (blk1 - blk) {
371
        case 1:  exp_strategy[blk][ch] = EXP_D45; break;
372 de6d9b64 Fabrice Bellard
        case 2:
373 ce67b7cd Justin Ruggles
        case 3:  exp_strategy[blk][ch] = EXP_D25; break;
374
        default: exp_strategy[blk][ch] = EXP_D15; break;
375 de6d9b64 Fabrice Bellard
        }
376 ce67b7cd Justin Ruggles
        blk = blk1;
377 de6d9b64 Fabrice Bellard
    }
378
}
379
380 2f8ae522 Justin Ruggles
381 c36ce0f8 Justin Ruggles
/**
382
 * Set each encoded exponent in a block to the minimum of itself and the
383
 * exponent in the same frequency bin of a following block.
384
 * exp[i] = min(exp[i], exp1[i]
385
 */
386 7066cc8f Justin Ruggles
static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
387 de6d9b64 Fabrice Bellard
{
388
    int i;
389 6a988808 Justin Ruggles
    for (i = 0; i < n; i++) {
390 de6d9b64 Fabrice Bellard
        if (exp1[i] < exp[i])
391
            exp[i] = exp1[i];
392
    }
393
}
394 115329f1 Diego Biurrun
395 2f8ae522 Justin Ruggles
396 c36ce0f8 Justin Ruggles
/**
397
 * Update the exponents so that they are the ones the decoder will decode.
398
 * @return the number of bits used to encode the exponents.
399
 */
400 23c5b361 Justin Ruggles
static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
401
                                   uint8_t exp[AC3_MAX_COEFS],
402
                                   int nb_exps, int exp_strategy)
403 de6d9b64 Fabrice Bellard
{
404 e44cad52 Jeff Muizelaar
    int group_size, nb_groups, i, j, k, exp_min;
405 7066cc8f Justin Ruggles
    uint8_t exp1[AC3_MAX_COEFS];
406 de6d9b64 Fabrice Bellard
407 02877def Justin Ruggles
    group_size = exp_strategy + (exp_strategy == EXP_D45);
408 de6d9b64 Fabrice Bellard
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
409
410
    /* for each group, compute the minimum exponent */
411
    exp1[0] = exp[0]; /* DC exponent is handled separately */
412
    k = 1;
413 6a988808 Justin Ruggles
    for (i = 1; i <= nb_groups; i++) {
414 de6d9b64 Fabrice Bellard
        exp_min = exp[k];
415
        assert(exp_min >= 0 && exp_min <= 24);
416 6a988808 Justin Ruggles
        for (j = 1; j < group_size; j++) {
417 de6d9b64 Fabrice Bellard
            if (exp[k+j] < exp_min)
418
                exp_min = exp[k+j];
419
        }
420
        exp1[i] = exp_min;
421
        k += group_size;
422
    }
423
424
    /* constraint for DC exponent */
425
    if (exp1[0] > 15)
426
        exp1[0] = 15;
427
428 6a988808 Justin Ruggles
    /* decrease the delta between each groups to within 2 so that they can be
429
       differentially encoded */
430
    for (i = 1; i <= nb_groups; i++)
431 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
432 6a988808 Justin Ruggles
    for (i = nb_groups-1; i >= 0; i--)
433 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
434 e44cad52 Jeff Muizelaar
435 de6d9b64 Fabrice Bellard
    /* now we have the exponent values the decoder will see */
436
    encoded_exp[0] = exp1[0];
437
    k = 1;
438 6a988808 Justin Ruggles
    for (i = 1; i <= nb_groups; i++) {
439
        for (j = 0; j < group_size; j++)
440 de6d9b64 Fabrice Bellard
            encoded_exp[k+j] = exp1[i];
441
        k += group_size;
442
    }
443 115329f1 Diego Biurrun
444 de6d9b64 Fabrice Bellard
    return 4 + (nb_groups / 3) * 7;
445
}
446
447 2f8ae522 Justin Ruggles
448 c36ce0f8 Justin Ruggles
/**
449
 * Calculate the number of bits needed to encode a set of mantissas.
450
 */
451 0c1a9eda Zdenek Kabelac
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
452 de6d9b64 Fabrice Bellard
{
453
    int bits, mant, i;
454
455
    bits = 0;
456 6a988808 Justin Ruggles
    for (i = 0; i < nb_coefs; i++) {
457 de6d9b64 Fabrice Bellard
        mant = m[i];
458 6a988808 Justin Ruggles
        switch (mant) {
459 de6d9b64 Fabrice Bellard
        case 0:
460
            /* nothing */
461
            break;
462
        case 1:
463
            /* 3 mantissa in 5 bits */
464 115329f1 Diego Biurrun
            if (s->mant1_cnt == 0)
465 de6d9b64 Fabrice Bellard
                bits += 5;
466
            if (++s->mant1_cnt == 3)
467
                s->mant1_cnt = 0;
468
            break;
469
        case 2:
470
            /* 3 mantissa in 7 bits */
471 115329f1 Diego Biurrun
            if (s->mant2_cnt == 0)
472 de6d9b64 Fabrice Bellard
                bits += 7;
473
            if (++s->mant2_cnt == 3)
474
                s->mant2_cnt = 0;
475
            break;
476
        case 3:
477
            bits += 3;
478
            break;
479
        case 4:
480
            /* 2 mantissa in 7 bits */
481
            if (s->mant4_cnt == 0)
482
                bits += 7;
483 115329f1 Diego Biurrun
            if (++s->mant4_cnt == 2)
484 de6d9b64 Fabrice Bellard
                s->mant4_cnt = 0;
485
            break;
486
        case 14:
487
            bits += 14;
488
            break;
489
        case 15:
490
            bits += 16;
491
            break;
492
        default:
493
            bits += mant - 1;
494
            break;
495
        }
496
    }
497
    return bits;
498
}
499
500
501 c36ce0f8 Justin Ruggles
/**
502
 * Calculate masking curve based on the final exponents.
503
 * Also calculate the power spectral densities to use in future calculations.
504
 */
505 bbd16dea Justin Ruggles
static void bit_alloc_masking(AC3EncodeContext *s,
506 7066cc8f Justin Ruggles
                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
507
                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
508
                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
509 47ae6e79 Justin Ruggles
                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
510 bbd16dea Justin Ruggles
{
511
    int blk, ch;
512 47ae6e79 Justin Ruggles
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
513 bbd16dea Justin Ruggles
514 6a988808 Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
515
        for (ch = 0; ch < s->channels; ch++) {
516 bbd16dea Justin Ruggles
            if(exp_strategy[blk][ch] == EXP_REUSE) {
517 0454b558 Justin Ruggles
                memcpy(psd[blk][ch],  psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(psd[0][0][0]));
518 47ae6e79 Justin Ruggles
                memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
519 bbd16dea Justin Ruggles
            } else {
520
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
521
                                          s->nb_coefs[ch],
522 5ce21342 Justin Ruggles
                                          psd[blk][ch], band_psd[blk][ch]);
523
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
524 bbd16dea Justin Ruggles
                                           0, s->nb_coefs[ch],
525 5ce21342 Justin Ruggles
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
526 bbd16dea Justin Ruggles
                                           ch == s->lfe_channel,
527 cc2a8443 Justin Ruggles
                                           DBA_NONE, 0, NULL, NULL, NULL,
528 bbd16dea Justin Ruggles
                                           mask[blk][ch]);
529
            }
530
        }
531
    }
532
}
533
534 2f8ae522 Justin Ruggles
535 c36ce0f8 Justin Ruggles
/**
536
 * Run the bit allocation with a given SNR offset.
537
 * This calculates the bit allocation pointers that will be used to determine
538
 * the quantization of each mantissa.
539
 * @return the number of remaining bits (positive or negative) if the given
540
 *         SNR offset is used to quantize the mantissas.
541
 */
542 de6d9b64 Fabrice Bellard
static int bit_alloc(AC3EncodeContext *s,
543 47ae6e79 Justin Ruggles
                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
544 7066cc8f Justin Ruggles
                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
545
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
546 5ce21342 Justin Ruggles
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
547 de6d9b64 Fabrice Bellard
{
548 ce67b7cd Justin Ruggles
    int blk, ch;
549 5ce21342 Justin Ruggles
    int snr_offset;
550 319708da Justin Ruggles
551 5ce21342 Justin Ruggles
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
552 de6d9b64 Fabrice Bellard
553 ce67b7cd Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
554 de6d9b64 Fabrice Bellard
        s->mant1_cnt = 0;
555
        s->mant2_cnt = 0;
556
        s->mant4_cnt = 0;
557 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
558 ce67b7cd Justin Ruggles
            ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
559 5ce21342 Justin Ruggles
                                      s->nb_coefs[ch], snr_offset,
560 687671f0 Justin Ruggles
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
561 ce67b7cd Justin Ruggles
                                      bap[blk][ch]);
562
            frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
563 de6d9b64 Fabrice Bellard
        }
564
    }
565 427e2293 Justin Ruggles
    return 8 * s->frame_size - frame_bits;
566 de6d9b64 Fabrice Bellard
}
567
568 2f8ae522 Justin Ruggles
569 de6d9b64 Fabrice Bellard
#define SNR_INC1 4
570
571 c36ce0f8 Justin Ruggles
/**
572
 * Perform bit allocation search.
573
 * Finds the SNR offset value that maximizes quality and fits in the specified
574
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
575
 * used to quantize the mantissas.
576
 */
577 de6d9b64 Fabrice Bellard
static int compute_bit_allocation(AC3EncodeContext *s,
578 7066cc8f Justin Ruggles
                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
579
                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
580
                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
581 de6d9b64 Fabrice Bellard
                                  int frame_bits)
582
{
583 ce67b7cd Justin Ruggles
    int blk, ch;
584 5ce21342 Justin Ruggles
    int coarse_snr_offset, fine_snr_offset;
585 7066cc8f Justin Ruggles
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
586
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
587 47ae6e79 Justin Ruggles
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
588 cf2baeb3 Stefan Gehrer
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
589 de6d9b64 Fabrice Bellard
590
    /* init default parameters */
591 5ce21342 Justin Ruggles
    s->slow_decay_code = 2;
592
    s->fast_decay_code = 1;
593 6a988808 Justin Ruggles
    s->slow_gain_code  = 1;
594 5ce21342 Justin Ruggles
    s->db_per_bit_code = 2;
595 6a988808 Justin Ruggles
    s->floor_code      = 4;
596
    for (ch = 0; ch < s->channels; ch++)
597 5ce21342 Justin Ruggles
        s->fast_gain_code[ch] = 4;
598 115329f1 Diego Biurrun
599 de6d9b64 Fabrice Bellard
    /* compute real values */
600 a657899c Justin Ruggles
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
601
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
602 6a988808 Justin Ruggles
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
603 5ce21342 Justin Ruggles
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
604 6a988808 Justin Ruggles
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
605 115329f1 Diego Biurrun
606 de6d9b64 Fabrice Bellard
    /* header size */
607
    frame_bits += 65;
608 e59cc205 Justin Ruggles
    // if (s->channel_mode == 2)
609 30b68f33 Zdenek Kabelac
    //    frame_bits += 2;
610 e59cc205 Justin Ruggles
    frame_bits += frame_bits_inc[s->channel_mode];
611 de6d9b64 Fabrice Bellard
612
    /* audio blocks */
613 ce67b7cd Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
614 2d2692eb Justin Ruggles
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
615 e59cc205 Justin Ruggles
        if (s->channel_mode == AC3_CHMODE_STEREO) {
616 30b68f33 Zdenek Kabelac
            frame_bits++; /* rematstr */
617 ce67b7cd Justin Ruggles
            if (!blk)
618 6a988808 Justin Ruggles
                frame_bits += 4;
619 132041f0 Justin Ruggles
        }
620 2d2692eb Justin Ruggles
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
621
        if (s->lfe_on)
622 bb270c08 Diego Biurrun
            frame_bits++; /* lfeexpstr */
623 6a988808 Justin Ruggles
        for (ch = 0; ch < s->fbw_channels; ch++) {
624 ce67b7cd Justin Ruggles
            if (exp_strategy[blk][ch] != EXP_REUSE)
625 30b68f33 Zdenek Kabelac
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
626 de6d9b64 Fabrice Bellard
        }
627
        frame_bits++; /* baie */
628
        frame_bits++; /* snr */
629
        frame_bits += 2; /* delta / skip */
630
    }
631
    frame_bits++; /* cplinu for block 0 */
632
    /* bit alloc info */
633 30b68f33 Zdenek Kabelac
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
634
    /* csnroffset[6] */
635
    /* (fsnoffset[4] + fgaincod[4]) * c */
636 2d2692eb Justin Ruggles
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
637 de6d9b64 Fabrice Bellard
638 9ab2717a Michael Niedermayer
    /* auxdatae, crcrsv */
639
    frame_bits += 2;
640
641 de6d9b64 Fabrice Bellard
    /* CRC */
642
    frame_bits += 16;
643
644 bbd16dea Justin Ruggles
    /* calculate psd and masking curve before doing bit allocation */
645
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
646
647 de6d9b64 Fabrice Bellard
    /* now the big work begins : do the bit allocation. Modify the snr
648
       offset until we can pack everything in the requested frame size */
649
650 5ce21342 Justin Ruggles
    coarse_snr_offset = s->coarse_snr_offset;
651
    while (coarse_snr_offset >= 0 &&
652
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
653
        coarse_snr_offset -= SNR_INC1;
654
    if (coarse_snr_offset < 0) {
655 c135b520 Justin Ruggles
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
656 bb270c08 Diego Biurrun
        return -1;
657 de6d9b64 Fabrice Bellard
    }
658 6a988808 Justin Ruggles
    while (coarse_snr_offset + SNR_INC1 <= 63 &&
659 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
660 5ce21342 Justin Ruggles
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
661
        coarse_snr_offset += SNR_INC1;
662 de6d9b64 Fabrice Bellard
        memcpy(bap, bap1, sizeof(bap1));
663
    }
664 6a988808 Justin Ruggles
    while (coarse_snr_offset + 1 <= 63 &&
665 5ce21342 Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
666
        coarse_snr_offset++;
667 de6d9b64 Fabrice Bellard
        memcpy(bap, bap1, sizeof(bap1));
668
    }
669
670 5ce21342 Justin Ruggles
    fine_snr_offset = 0;
671 6a988808 Justin Ruggles
    while (fine_snr_offset + SNR_INC1 <= 15 &&
672 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
673 5ce21342 Justin Ruggles
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
674
        fine_snr_offset += SNR_INC1;
675 de6d9b64 Fabrice Bellard
        memcpy(bap, bap1, sizeof(bap1));
676
    }
677 6a988808 Justin Ruggles
    while (fine_snr_offset + 1 <= 15 &&
678 bbd16dea Justin Ruggles
           bit_alloc(s, mask, psd, bap1, frame_bits,
679 5ce21342 Justin Ruggles
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
680
        fine_snr_offset++;
681 de6d9b64 Fabrice Bellard
        memcpy(bap, bap1, sizeof(bap1));
682
    }
683 115329f1 Diego Biurrun
684 5ce21342 Justin Ruggles
    s->coarse_snr_offset = coarse_snr_offset;
685 6a988808 Justin Ruggles
    for (ch = 0; ch < s->channels; ch++)
686 5ce21342 Justin Ruggles
        s->fine_snr_offset[ch] = fine_snr_offset;
687 22c0b03c Justin Ruggles
688 de6d9b64 Fabrice Bellard
    return 0;
689
}
690
691 2f8ae522 Justin Ruggles
692 c36ce0f8 Justin Ruggles
/**
693
 * Write the AC-3 frame header to the output bitstream.
694
 */
695 de6d9b64 Fabrice Bellard
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
696
{
697 ed7debda Alex Beregszaszi
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
698 de6d9b64 Fabrice Bellard
699 6a988808 Justin Ruggles
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
700
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
701
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
702 427e2293 Justin Ruggles
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
703 6a988808 Justin Ruggles
    put_bits(&s->pb, 5,  s->bitstream_id);
704
    put_bits(&s->pb, 3,  s->bitstream_mode);
705
    put_bits(&s->pb, 3,  s->channel_mode);
706 e59cc205 Justin Ruggles
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
707 6a988808 Justin Ruggles
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
708 e59cc205 Justin Ruggles
    if (s->channel_mode & 0x04)
709 6a988808 Justin Ruggles
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
710 e59cc205 Justin Ruggles
    if (s->channel_mode == AC3_CHMODE_STEREO)
711 6a988808 Justin Ruggles
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
712 2d2692eb Justin Ruggles
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
713 6a988808 Justin Ruggles
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
714
    put_bits(&s->pb, 1, 0);         /* no compression control word */
715
    put_bits(&s->pb, 1, 0);         /* no lang code */
716
    put_bits(&s->pb, 1, 0);         /* no audio production info */
717
    put_bits(&s->pb, 1, 0);         /* no copyright */
718
    put_bits(&s->pb, 1, 1);         /* original bitstream */
719
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
720
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
721
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
722 de6d9b64 Fabrice Bellard
}
723
724 2f8ae522 Justin Ruggles
725 c36ce0f8 Justin Ruggles
/**
726
 * Symmetric quantization on 'levels' levels.
727
 */
728 de6d9b64 Fabrice Bellard
static inline int sym_quant(int c, int e, int levels)
729
{
730
    int v;
731
732
    if (c >= 0) {
733 8d67072f Fabrice Bellard
        v = (levels * (c << e)) >> 24;
734
        v = (v + 1) >> 1;
735 de6d9b64 Fabrice Bellard
        v = (levels >> 1) + v;
736
    } else {
737 8d67072f Fabrice Bellard
        v = (levels * ((-c) << e)) >> 24;
738
        v = (v + 1) >> 1;
739 de6d9b64 Fabrice Bellard
        v = (levels >> 1) - v;
740
    }
741
    assert (v >= 0 && v < levels);
742
    return v;
743
}
744
745 2f8ae522 Justin Ruggles
746 c36ce0f8 Justin Ruggles
/**
747
 * Asymmetric quantization on 2^qbits levels.
748
 */
749 de6d9b64 Fabrice Bellard
static inline int asym_quant(int c, int e, int qbits)
750
{
751
    int lshift, m, v;
752
753
    lshift = e + qbits - 24;
754
    if (lshift >= 0)
755
        v = c << lshift;
756
    else
757
        v = c >> (-lshift);
758
    /* rounding */
759
    v = (v + 1) >> 1;
760
    m = (1 << (qbits-1));
761
    if (v >= m)
762
        v = m - 1;
763
    assert(v >= -m);
764
    return v & ((1 << qbits)-1);
765
}
766
767 2f8ae522 Justin Ruggles
768 c36ce0f8 Justin Ruggles
/**
769
 * Write one audio block to the output bitstream.
770
 */
771 de6d9b64 Fabrice Bellard
static void output_audio_block(AC3EncodeContext *s,
772 0c1a9eda Zdenek Kabelac
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
773 7066cc8f Justin Ruggles
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
774
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
775 77773275 Justin Ruggles
                               int32_t mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
776 aab45ca3 Justin Ruggles
                               int8_t exp_shift[AC3_MAX_CHANNELS],
777 de6d9b64 Fabrice Bellard
                               int block_num)
778
{
779 743739d2 Michael Niedermayer
    int ch, nb_groups, group_size, i, baie, rbnd;
780 0c1a9eda Zdenek Kabelac
    uint8_t *p;
781 7066cc8f Justin Ruggles
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
782 de6d9b64 Fabrice Bellard
    int exp0, exp1;
783
    int mant1_cnt, mant2_cnt, mant4_cnt;
784 0c1a9eda Zdenek Kabelac
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
785 de6d9b64 Fabrice Bellard
    int delta0, delta1, delta2;
786
787 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
788
        put_bits(&s->pb, 1, 0); /* no block switching */
789
    for (ch = 0; ch < s->fbw_channels; ch++)
790 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 1); /* no dither */
791 6a988808 Justin Ruggles
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
792
    if (!block_num) {
793 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
794
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
795
    } else {
796
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
797
    }
798
799 6a988808 Justin Ruggles
    if (s->channel_mode == AC3_CHMODE_STEREO) {
800
        if (!block_num) {
801
            /* first block must define rematrixing (rematstr) */
802 bb270c08 Diego Biurrun
            put_bits(&s->pb, 1, 1);
803
804
            /* dummy rematrixing rematflg(1:4)=0 */
805 6a988808 Justin Ruggles
            for (rbnd = 0; rbnd < 4; rbnd++)
806
                put_bits(&s->pb, 1, 0);
807
        } else {
808 bb270c08 Diego Biurrun
            /* no matrixing (but should be used in the future) */
809
            put_bits(&s->pb, 1, 0);
810 6a988808 Justin Ruggles
        }
811
    }
812 de6d9b64 Fabrice Bellard
813
    /* exponent strategy */
814 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
815 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 2, exp_strategy[ch]);
816 115329f1 Diego Biurrun
817 6a988808 Justin Ruggles
    if (s->lfe_on)
818 bb270c08 Diego Biurrun
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
819 30b68f33 Zdenek Kabelac
820 6a988808 Justin Ruggles
    /* bandwidth */
821
    for (ch = 0; ch < s->fbw_channels; ch++) {
822 de6d9b64 Fabrice Bellard
        if (exp_strategy[ch] != EXP_REUSE)
823 2d2692eb Justin Ruggles
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
824 de6d9b64 Fabrice Bellard
    }
825 115329f1 Diego Biurrun
826 de6d9b64 Fabrice Bellard
    /* exponents */
827 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
828 02877def Justin Ruggles
        if (exp_strategy[ch] == EXP_REUSE)
829 de6d9b64 Fabrice Bellard
            continue;
830 02877def Justin Ruggles
        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
831 bb270c08 Diego Biurrun
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
832 de6d9b64 Fabrice Bellard
        p = encoded_exp[ch];
833
834
        /* first exponent */
835
        exp1 = *p++;
836
        put_bits(&s->pb, 4, exp1);
837
838
        /* next ones are delta encoded */
839 6a988808 Justin Ruggles
        for (i = 0; i < nb_groups; i++) {
840 de6d9b64 Fabrice Bellard
            /* merge three delta in one code */
841 6a988808 Justin Ruggles
            exp0   = exp1;
842
            exp1   = p[0];
843
            p     += group_size;
844 de6d9b64 Fabrice Bellard
            delta0 = exp1 - exp0 + 2;
845
846 6a988808 Justin Ruggles
            exp0   = exp1;
847
            exp1   = p[0];
848
            p     += group_size;
849 de6d9b64 Fabrice Bellard
            delta1 = exp1 - exp0 + 2;
850
851 6a988808 Justin Ruggles
            exp0   = exp1;
852
            exp1   = p[0];
853
            p     += group_size;
854 de6d9b64 Fabrice Bellard
            delta2 = exp1 - exp0 + 2;
855
856
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
857
        }
858
859 bb270c08 Diego Biurrun
        if (ch != s->lfe_channel)
860
            put_bits(&s->pb, 2, 0); /* no gain range info */
861 de6d9b64 Fabrice Bellard
    }
862
863
    /* bit allocation info */
864
    baie = (block_num == 0);
865
    put_bits(&s->pb, 1, baie);
866
    if (baie) {
867 5ce21342 Justin Ruggles
        put_bits(&s->pb, 2, s->slow_decay_code);
868
        put_bits(&s->pb, 2, s->fast_decay_code);
869
        put_bits(&s->pb, 2, s->slow_gain_code);
870
        put_bits(&s->pb, 2, s->db_per_bit_code);
871
        put_bits(&s->pb, 3, s->floor_code);
872 de6d9b64 Fabrice Bellard
    }
873
874
    /* snr offset */
875 6a988808 Justin Ruggles
    put_bits(&s->pb, 1, baie);
876 de6d9b64 Fabrice Bellard
    if (baie) {
877 5ce21342 Justin Ruggles
        put_bits(&s->pb, 6, s->coarse_snr_offset);
878 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
879 5ce21342 Justin Ruggles
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
880
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
881 de6d9b64 Fabrice Bellard
        }
882
    }
883 115329f1 Diego Biurrun
884 de6d9b64 Fabrice Bellard
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
885
    put_bits(&s->pb, 1, 0); /* no data to skip */
886
887
    /* mantissa encoding : we use two passes to handle the grouping. A
888
       one pass method may be faster, but it would necessitate to
889
       modify the output stream. */
890
891
    /* first pass: quantize */
892
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
893
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
894
895 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
896 de6d9b64 Fabrice Bellard
        int b, c, e, v;
897
898 6a988808 Justin Ruggles
        for (i = 0; i < s->nb_coefs[ch]; i++) {
899 77773275 Justin Ruggles
            c = mdct_coef[ch][i];
900 aab45ca3 Justin Ruggles
            e = encoded_exp[ch][i] - exp_shift[ch];
901 de6d9b64 Fabrice Bellard
            b = bap[ch][i];
902 6a988808 Justin Ruggles
            switch (b) {
903 de6d9b64 Fabrice Bellard
            case 0:
904
                v = 0;
905
                break;
906
            case 1:
907
                v = sym_quant(c, e, 3);
908 6a988808 Justin Ruggles
                switch (mant1_cnt) {
909 de6d9b64 Fabrice Bellard
                case 0:
910
                    qmant1_ptr = &qmant[ch][i];
911
                    v = 9 * v;
912
                    mant1_cnt = 1;
913
                    break;
914
                case 1:
915
                    *qmant1_ptr += 3 * v;
916
                    mant1_cnt = 2;
917
                    v = 128;
918
                    break;
919
                default:
920
                    *qmant1_ptr += v;
921
                    mant1_cnt = 0;
922
                    v = 128;
923
                    break;
924
                }
925
                break;
926
            case 2:
927
                v = sym_quant(c, e, 5);
928 6a988808 Justin Ruggles
                switch (mant2_cnt) {
929 de6d9b64 Fabrice Bellard
                case 0:
930
                    qmant2_ptr = &qmant[ch][i];
931
                    v = 25 * v;
932
                    mant2_cnt = 1;
933
                    break;
934
                case 1:
935
                    *qmant2_ptr += 5 * v;
936
                    mant2_cnt = 2;
937
                    v = 128;
938
                    break;
939
                default:
940
                    *qmant2_ptr += v;
941
                    mant2_cnt = 0;
942
                    v = 128;
943
                    break;
944
                }
945
                break;
946
            case 3:
947
                v = sym_quant(c, e, 7);
948
                break;
949
            case 4:
950
                v = sym_quant(c, e, 11);
951 6a988808 Justin Ruggles
                switch (mant4_cnt) {
952 de6d9b64 Fabrice Bellard
                case 0:
953
                    qmant4_ptr = &qmant[ch][i];
954
                    v = 11 * v;
955
                    mant4_cnt = 1;
956
                    break;
957
                default:
958
                    *qmant4_ptr += v;
959
                    mant4_cnt = 0;
960
                    v = 128;
961
                    break;
962
                }
963
                break;
964
            case 5:
965
                v = sym_quant(c, e, 15);
966
                break;
967
            case 14:
968
                v = asym_quant(c, e, 14);
969
                break;
970
            case 15:
971
                v = asym_quant(c, e, 16);
972
                break;
973
            default:
974
                v = asym_quant(c, e, b - 1);
975
                break;
976
            }
977
            qmant[ch][i] = v;
978
        }
979
    }
980
981
    /* second pass : output the values */
982 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
983 de6d9b64 Fabrice Bellard
        int b, q;
984 115329f1 Diego Biurrun
985 6a988808 Justin Ruggles
        for (i = 0; i < s->nb_coefs[ch]; i++) {
986 de6d9b64 Fabrice Bellard
            q = qmant[ch][i];
987
            b = bap[ch][i];
988 6a988808 Justin Ruggles
            switch (b) {
989
            case 0:                                         break;
990
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
991
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
992
            case 3:               put_bits(&s->pb,   3, q); break;
993
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
994
            case 14:              put_bits(&s->pb,  14, q); break;
995
            case 15:              put_bits(&s->pb,  16, q); break;
996
            default:              put_bits(&s->pb, b-1, q); break;
997 de6d9b64 Fabrice Bellard
            }
998
        }
999
    }
1000
}
1001
1002 2f8ae522 Justin Ruggles
1003 c36ce0f8 Justin Ruggles
/** CRC-16 Polynomial */
1004 de6d9b64 Fabrice Bellard
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1005
1006 2f8ae522 Justin Ruggles
1007 de6d9b64 Fabrice Bellard
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1008
{
1009
    unsigned int c;
1010
1011
    c = 0;
1012
    while (a) {
1013
        if (a & 1)
1014
            c ^= b;
1015
        a = a >> 1;
1016
        b = b << 1;
1017
        if (b & (1 << 16))
1018
            b ^= poly;
1019
    }
1020
    return c;
1021
}
1022
1023 2f8ae522 Justin Ruggles
1024 de6d9b64 Fabrice Bellard
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1025
{
1026
    unsigned int r;
1027
    r = 1;
1028
    while (n) {
1029
        if (n & 1)
1030
            r = mul_poly(r, a, poly);
1031
        a = mul_poly(a, a, poly);
1032
        n >>= 1;
1033
    }
1034
    return r;
1035
}
1036
1037 2f8ae522 Justin Ruggles
1038 c36ce0f8 Justin Ruggles
/**
1039
 * Fill the end of the frame with 0's and compute the two CRCs.
1040
 */
1041 1971ab6e Justin Ruggles
static void output_frame_end(AC3EncodeContext *s)
1042 de6d9b64 Fabrice Bellard
{
1043 eed00252 Justin Ruggles
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1044 0c1a9eda Zdenek Kabelac
    uint8_t *frame;
1045 de6d9b64 Fabrice Bellard
1046
    frame_size = s->frame_size; /* frame size in words */
1047
    /* align to 8 bits */
1048
    flush_put_bits(&s->pb);
1049
    /* add zero bytes to reach the frame size */
1050
    frame = s->pb.buf;
1051 427e2293 Justin Ruggles
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1052 eed00252 Justin Ruggles
    assert(pad_bytes >= 0);
1053
    if (pad_bytes > 0)
1054
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1055 115329f1 Diego Biurrun
1056 de6d9b64 Fabrice Bellard
    /* Now we must compute both crcs : this is not so easy for crc1
1057
       because it is at the beginning of the data... */
1058 427e2293 Justin Ruggles
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1059 6a988808 Justin Ruggles
1060 8fc0162a Måns Rullgård
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1061 427e2293 Justin Ruggles
                             frame + 4, frame_size_58 - 4));
1062 6a988808 Justin Ruggles
1063 de6d9b64 Fabrice Bellard
    /* XXX: could precompute crc_inv */
1064 427e2293 Justin Ruggles
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1065 6a988808 Justin Ruggles
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1066
    AV_WB16(frame + 2, crc1);
1067 115329f1 Diego Biurrun
1068 8fc0162a Måns Rullgård
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1069 427e2293 Justin Ruggles
                             frame + frame_size_58,
1070
                             frame_size - frame_size_58 - 2));
1071
    AV_WB16(frame + frame_size - 2, crc2);
1072 de6d9b64 Fabrice Bellard
}
1073
1074 2f8ae522 Justin Ruggles
1075 c36ce0f8 Justin Ruggles
/**
1076
 * Encode a single AC-3 frame.
1077
 */
1078 a0a9204e Justin Ruggles
static int ac3_encode_frame(AVCodecContext *avctx,
1079 6107fa87 Fabrice Bellard
                            unsigned char *frame, int buf_size, void *data)
1080 de6d9b64 Fabrice Bellard
{
1081
    AC3EncodeContext *s = avctx->priv_data;
1082 edac49da Reimar Döffinger
    const int16_t *samples = data;
1083 ce67b7cd Justin Ruggles
    int v;
1084
    int blk, blk1, blk2, ch, i;
1085 12ed6226 Justin Ruggles
    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
1086 98f6ee44 Justin Ruggles
    int16_t windowed_samples[AC3_WINDOW_SIZE];
1087 7066cc8f Justin Ruggles
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1088
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1089
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1090
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1091
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1092 aab45ca3 Justin Ruggles
    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1093 de6d9b64 Fabrice Bellard
    int frame_bits;
1094
1095 12ed6226 Justin Ruggles
    /* deinterleave and remap input samples */
1096
    for (ch = 0; ch < s->channels; ch++) {
1097
        const int16_t *sptr;
1098
        int sinc;
1099
1100
        /* copy last 256 samples of previous frame to the start of the current frame */
1101
        memcpy(&planar_samples[ch][0], s->last_samples[ch],
1102
                AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
1103
1104
        /* deinterleave */
1105
        sinc = s->channels;
1106
        sptr = samples + s->channel_map[ch];
1107
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
1108
            planar_samples[ch][i] = *sptr;
1109
            sptr += sinc;
1110
        }
1111
1112
        /* save last 256 samples for next frame */
1113
        memcpy(s->last_samples[ch], &planar_samples[ch][6* AC3_BLOCK_SIZE],
1114
                AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
1115
    }
1116
1117 de6d9b64 Fabrice Bellard
    frame_bits = 0;
1118 6a988808 Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
1119 de6d9b64 Fabrice Bellard
        /* fixed mdct to the six sub blocks & exponent computation */
1120 ce67b7cd Justin Ruggles
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1121 98f6ee44 Justin Ruggles
            int16_t *input_samples = &planar_samples[ch][blk * AC3_BLOCK_SIZE];
1122 de6d9b64 Fabrice Bellard
1123
            /* apply the MDCT window */
1124 ce67b7cd Justin Ruggles
            for (i = 0; i < AC3_BLOCK_SIZE; i++) {
1125 98f6ee44 Justin Ruggles
                windowed_samples[i]                   = MUL16(input_samples[i],
1126 ce67b7cd Justin Ruggles
                                                           ff_ac3_window[i]) >> 15;
1127 98f6ee44 Justin Ruggles
                windowed_samples[AC3_WINDOW_SIZE-i-1] = MUL16(input_samples[AC3_WINDOW_SIZE-i-1],
1128 ce67b7cd Justin Ruggles
                                                           ff_ac3_window[i]) >> 15;
1129 de6d9b64 Fabrice Bellard
            }
1130 115329f1 Diego Biurrun
1131 6a988808 Justin Ruggles
            /* Normalize the samples to use the maximum available precision */
1132 98f6ee44 Justin Ruggles
            v = 14 - log2_tab(windowed_samples, AC3_WINDOW_SIZE);
1133 de6d9b64 Fabrice Bellard
            if (v < 0)
1134
                v = 0;
1135 ce67b7cd Justin Ruggles
            exp_shift[blk][ch] = v - 9;
1136 98f6ee44 Justin Ruggles
            lshift_tab(windowed_samples, AC3_WINDOW_SIZE, v);
1137 de6d9b64 Fabrice Bellard
1138
            /* do the MDCT */
1139 98f6ee44 Justin Ruggles
            mdct512(mdct_coef[blk][ch], windowed_samples);
1140 115329f1 Diego Biurrun
1141 6a988808 Justin Ruggles
            /* compute "exponents". We take into account the normalization there */
1142 ce67b7cd Justin Ruggles
            for (i = 0; i < AC3_MAX_COEFS; i++) {
1143 de6d9b64 Fabrice Bellard
                int e;
1144 ce67b7cd Justin Ruggles
                v = abs(mdct_coef[blk][ch][i]);
1145 de6d9b64 Fabrice Bellard
                if (v == 0)
1146
                    e = 24;
1147
                else {
1148 ce67b7cd Justin Ruggles
                    e = 23 - av_log2(v) + exp_shift[blk][ch];
1149 de6d9b64 Fabrice Bellard
                    if (e >= 24) {
1150
                        e = 24;
1151 ce67b7cd Justin Ruggles
                        mdct_coef[blk][ch][i] = 0;
1152 de6d9b64 Fabrice Bellard
                    }
1153
                }
1154 ce67b7cd Justin Ruggles
                exp[blk][ch][i] = e;
1155 de6d9b64 Fabrice Bellard
            }
1156
        }
1157 115329f1 Diego Biurrun
1158 23c5b361 Justin Ruggles
        compute_exp_strategy_ch(exp_strategy, exp, ch, ch == s->lfe_channel);
1159 de6d9b64 Fabrice Bellard
1160
        /* compute the exponents as the decoder will see them. The
1161
           EXP_REUSE case must be handled carefully : we select the
1162
           min of the exponents */
1163 ce67b7cd Justin Ruggles
        blk = 0;
1164
        while (blk < AC3_MAX_BLOCKS) {
1165
            blk1 = blk + 1;
1166
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE) {
1167
                exponent_min(exp[blk][ch], exp[blk1][ch], s->nb_coefs[ch]);
1168
                blk1++;
1169 de6d9b64 Fabrice Bellard
            }
1170 ce67b7cd Justin Ruggles
            frame_bits += encode_exponents_blk_ch(encoded_exp[blk][ch],
1171
                                                  exp[blk][ch], s->nb_coefs[ch],
1172
                                                  exp_strategy[blk][ch]);
1173 de6d9b64 Fabrice Bellard
            /* copy encoded exponents for reuse case */
1174 ce67b7cd Justin Ruggles
            for (blk2 = blk+1; blk2 < blk1; blk2++) {
1175
                memcpy(encoded_exp[blk2][ch], encoded_exp[blk][ch],
1176 0c1a9eda Zdenek Kabelac
                       s->nb_coefs[ch] * sizeof(uint8_t));
1177 de6d9b64 Fabrice Bellard
            }
1178 ce67b7cd Justin Ruggles
            blk = blk1;
1179 de6d9b64 Fabrice Bellard
        }
1180
    }
1181
1182 f760b70f Justin Ruggles
    /* adjust for fractional frame sizes */
1183 6a988808 Justin Ruggles
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1184
        s->bits_written    -= s->bit_rate;
1185 f760b70f Justin Ruggles
        s->samples_written -= s->sample_rate;
1186
    }
1187 427e2293 Justin Ruggles
    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1188
    s->bits_written    += s->frame_size * 8;
1189 f760b70f Justin Ruggles
    s->samples_written += AC3_FRAME_SIZE;
1190
1191 de6d9b64 Fabrice Bellard
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1192
    /* everything is known... let's output the frame */
1193
    output_frame_header(s, frame);
1194 115329f1 Diego Biurrun
1195 ce67b7cd Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1196
        output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
1197
                           bap[blk], mdct_coef[blk], exp_shift[blk], blk);
1198 de6d9b64 Fabrice Bellard
    }
1199 1971ab6e Justin Ruggles
    output_frame_end(s);
1200
1201 427e2293 Justin Ruggles
    return s->frame_size;
1202 de6d9b64 Fabrice Bellard
}
1203
1204 2f8ae522 Justin Ruggles
1205 c36ce0f8 Justin Ruggles
/**
1206
 * Finalize encoding and free any memory allocated by the encoder.
1207
 */
1208 a0a9204e Justin Ruggles
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1209 492cd3a9 Michael Niedermayer
{
1210
    av_freep(&avctx->coded_frame);
1211 ef9f7306 Måns Rullgård
    return 0;
1212 492cd3a9 Michael Niedermayer
}
1213
1214 2f8ae522 Justin Ruggles
1215 c36ce0f8 Justin Ruggles
/**
1216
 * Set channel information during initialization.
1217
 */
1218 e77fd066 Justin Ruggles
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1219
                                    int64_t *channel_layout)
1220
{
1221
    int ch_layout;
1222
1223
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1224 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1225 e77fd066 Justin Ruggles
    if ((uint64_t)*channel_layout > 0x7FF)
1226 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1227 e77fd066 Justin Ruggles
    ch_layout = *channel_layout;
1228
    if (!ch_layout)
1229
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1230
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1231 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1232 e77fd066 Justin Ruggles
1233
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1234
    s->channels     = channels;
1235
    s->fbw_channels = channels - s->lfe_on;
1236
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1237
    if (s->lfe_on)
1238
        ch_layout -= AV_CH_LOW_FREQUENCY;
1239
1240
    switch (ch_layout) {
1241
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1242
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1243
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1244
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1245
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1246
    case AV_CH_LAYOUT_QUAD:
1247
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1248
    case AV_CH_LAYOUT_5POINT0:
1249
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1250
    default:
1251 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1252 e77fd066 Justin Ruggles
    }
1253
1254
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1255
    *channel_layout = ch_layout;
1256
    if (s->lfe_on)
1257
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1258
1259
    return 0;
1260
}
1261
1262 2f8ae522 Justin Ruggles
1263 8f60f70d Justin Ruggles
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1264 e77fd066 Justin Ruggles
{
1265 ddf63d37 Justin Ruggles
    int i, ret;
1266 e77fd066 Justin Ruggles
1267 e0685bc9 Justin Ruggles
    /* validate channel layout */
1268 e77fd066 Justin Ruggles
    if (!avctx->channel_layout) {
1269
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1270
                                      "encoder will guess the layout, but it "
1271
                                      "might be incorrect.\n");
1272
    }
1273 ddf63d37 Justin Ruggles
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1274
    if (ret) {
1275 e77fd066 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1276 ddf63d37 Justin Ruggles
        return ret;
1277 e77fd066 Justin Ruggles
    }
1278
1279 e0685bc9 Justin Ruggles
    /* validate sample rate */
1280 99ca4f73 Justin Ruggles
    for (i = 0; i < 9; i++) {
1281
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1282
            break;
1283 e77fd066 Justin Ruggles
    }
1284 99ca4f73 Justin Ruggles
    if (i == 9) {
1285 ddf63d37 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1286
        return AVERROR(EINVAL);
1287 99ca4f73 Justin Ruggles
    }
1288 1607db0a Justin Ruggles
    s->sample_rate        = avctx->sample_rate;
1289 99ca4f73 Justin Ruggles
    s->bit_alloc.sr_shift = i % 3;
1290
    s->bit_alloc.sr_code  = i / 3;
1291 e77fd066 Justin Ruggles
1292 e0685bc9 Justin Ruggles
    /* validate bit rate */
1293 e77fd066 Justin Ruggles
    for (i = 0; i < 19; i++) {
1294 1607db0a Justin Ruggles
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1295 e77fd066 Justin Ruggles
            break;
1296
    }
1297 ddf63d37 Justin Ruggles
    if (i == 19) {
1298
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1299
        return AVERROR(EINVAL);
1300
    }
1301 1607db0a Justin Ruggles
    s->bit_rate        = avctx->bit_rate;
1302 e77fd066 Justin Ruggles
    s->frame_size_code = i << 1;
1303 8f60f70d Justin Ruggles
1304
    return 0;
1305
}
1306
1307
1308
/**
1309 282255bb Justin Ruggles
 * Set bandwidth for all channels.
1310
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1311
 * default value will be used.
1312
 */
1313
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1314
{
1315
    int ch, bw_code;
1316
1317
    if (cutoff) {
1318
        /* calculate bandwidth based on user-specified cutoff frequency */
1319
        int fbw_coeffs;
1320
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1321
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1322
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1323
    } else {
1324
        /* use default bandwidth setting */
1325
        /* XXX: should compute the bandwidth according to the frame
1326
           size, so that we avoid annoying high frequency artifacts */
1327
        bw_code = 50;
1328
    }
1329
1330
    /* set number of coefficients for each channel */
1331
    for (ch = 0; ch < s->fbw_channels; ch++) {
1332
        s->bandwidth_code[ch] = bw_code;
1333
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1334
    }
1335
    if (s->lfe_on)
1336
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1337
}
1338
1339
1340
/**
1341 8f60f70d Justin Ruggles
 * Initialize the encoder.
1342
 */
1343
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1344
{
1345
    AC3EncodeContext *s = avctx->priv_data;
1346 282255bb Justin Ruggles
    int ret;
1347 8f60f70d Justin Ruggles
1348
    avctx->frame_size = AC3_FRAME_SIZE;
1349
1350
    ac3_common_init();
1351
1352
    ret = validate_options(avctx, s);
1353
    if (ret)
1354
        return ret;
1355
1356 e35c984a Justin Ruggles
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1357
    s->bitstream_mode = 0; /* complete main audio service */
1358
1359 427e2293 Justin Ruggles
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1360 e77fd066 Justin Ruggles
    s->bits_written    = 0;
1361
    s->samples_written = 0;
1362
    s->frame_size      = s->frame_size_min;
1363
1364 282255bb Justin Ruggles
    set_bandwidth(s, avctx->cutoff);
1365 e77fd066 Justin Ruggles
1366
    /* initial snr offset */
1367
    s->coarse_snr_offset = 40;
1368
1369
    mdct_init(9);
1370
1371
    avctx->coded_frame= avcodec_alloc_frame();
1372
    avctx->coded_frame->key_frame= 1;
1373
1374
    return 0;
1375
}
1376
1377 2f8ae522 Justin Ruggles
1378 228315bb Justin Ruggles
#ifdef TEST
1379 de6d9b64 Fabrice Bellard
/*************************************************************************/
1380
/* TEST */
1381
1382 228315bb Justin Ruggles
#include "libavutil/lfg.h"
1383 de6d9b64 Fabrice Bellard
1384 228315bb Justin Ruggles
#define FN (MDCT_SAMPLES/4)
1385
1386 2f8ae522 Justin Ruggles
1387 228315bb Justin Ruggles
static void fft_test(AVLFG *lfg)
1388 de6d9b64 Fabrice Bellard
{
1389
    IComplex in[FN], in1[FN];
1390
    int k, n, i;
1391
    float sum_re, sum_im, a;
1392
1393 6a988808 Justin Ruggles
    for (i = 0; i < FN; i++) {
1394 228315bb Justin Ruggles
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1395
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1396 6a988808 Justin Ruggles
        in1[i]   = in[i];
1397 de6d9b64 Fabrice Bellard
    }
1398
    fft(in, 7);
1399
1400
    /* do it by hand */
1401 6a988808 Justin Ruggles
    for (k = 0; k < FN; k++) {
1402 de6d9b64 Fabrice Bellard
        sum_re = 0;
1403
        sum_im = 0;
1404 6a988808 Justin Ruggles
        for (n = 0; n < FN; n++) {
1405 de6d9b64 Fabrice Bellard
            a = -2 * M_PI * (n * k) / FN;
1406
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1407
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1408
        }
1409 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1410 115329f1 Diego Biurrun
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1411 de6d9b64 Fabrice Bellard
    }
1412
}
1413
1414 2f8ae522 Justin Ruggles
1415 228315bb Justin Ruggles
static void mdct_test(AVLFG *lfg)
1416 de6d9b64 Fabrice Bellard
{
1417 228315bb Justin Ruggles
    int16_t input[MDCT_SAMPLES];
1418
    int32_t output[AC3_MAX_COEFS];
1419
    float input1[MDCT_SAMPLES];
1420
    float output1[AC3_MAX_COEFS];
1421 de6d9b64 Fabrice Bellard
    float s, a, err, e, emax;
1422
    int i, k, n;
1423
1424 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES; i++) {
1425
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1426 de6d9b64 Fabrice Bellard
        input1[i] = input[i];
1427
    }
1428
1429
    mdct512(output, input);
1430 115329f1 Diego Biurrun
1431 de6d9b64 Fabrice Bellard
    /* do it by hand */
1432 6a988808 Justin Ruggles
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1433 de6d9b64 Fabrice Bellard
        s = 0;
1434 6a988808 Justin Ruggles
        for (n = 0; n < MDCT_SAMPLES; n++) {
1435 228315bb Justin Ruggles
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1436 de6d9b64 Fabrice Bellard
            s += input1[n] * cos(a);
1437
        }
1438 228315bb Justin Ruggles
        output1[k] = -2 * s / MDCT_SAMPLES;
1439 de6d9b64 Fabrice Bellard
    }
1440 115329f1 Diego Biurrun
1441 6a988808 Justin Ruggles
    err  = 0;
1442 de6d9b64 Fabrice Bellard
    emax = 0;
1443 6a988808 Justin Ruggles
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1444 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1445 de6d9b64 Fabrice Bellard
        e = output[i] - output1[i];
1446
        if (e > emax)
1447
            emax = e;
1448
        err += e * e;
1449
    }
1450 228315bb Justin Ruggles
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1451 de6d9b64 Fabrice Bellard
}
1452
1453 2f8ae522 Justin Ruggles
1454 228315bb Justin Ruggles
int main(void)
1455 de6d9b64 Fabrice Bellard
{
1456 228315bb Justin Ruggles
    AVLFG lfg;
1457 115329f1 Diego Biurrun
1458 228315bb Justin Ruggles
    av_log_set_level(AV_LOG_DEBUG);
1459
    mdct_init(9);
1460 de6d9b64 Fabrice Bellard
1461 228315bb Justin Ruggles
    fft_test(&lfg);
1462
    mdct_test(&lfg);
1463 de6d9b64 Fabrice Bellard
1464 228315bb Justin Ruggles
    return 0;
1465 de6d9b64 Fabrice Bellard
}
1466 228315bb Justin Ruggles
#endif /* TEST */
1467 de6d9b64 Fabrice Bellard
1468 2f8ae522 Justin Ruggles
1469 de6d9b64 Fabrice Bellard
AVCodec ac3_encoder = {
1470
    "ac3",
1471 72415b2a Stefano Sabatini
    AVMEDIA_TYPE_AUDIO,
1472 de6d9b64 Fabrice Bellard
    CODEC_ID_AC3,
1473
    sizeof(AC3EncodeContext),
1474 a0a9204e Justin Ruggles
    ac3_encode_init,
1475
    ac3_encode_frame,
1476
    ac3_encode_close,
1477 de6d9b64 Fabrice Bellard
    NULL,
1478 5d6e4c16 Stefano Sabatini
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1479 2988c93d Justin Ruggles
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1480 b5f09d31 Reimar Döffinger
    .channel_layouts = (const int64_t[]){
1481 63e8d976 Stefano Sabatini
        AV_CH_LAYOUT_MONO,
1482
        AV_CH_LAYOUT_STEREO,
1483
        AV_CH_LAYOUT_2_1,
1484
        AV_CH_LAYOUT_SURROUND,
1485
        AV_CH_LAYOUT_2_2,
1486
        AV_CH_LAYOUT_QUAD,
1487
        AV_CH_LAYOUT_4POINT0,
1488
        AV_CH_LAYOUT_5POINT0,
1489
        AV_CH_LAYOUT_5POINT0_BACK,
1490
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1491
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1492
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1493
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1494
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1495
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1496
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1497
        AV_CH_LAYOUT_5POINT1,
1498
        AV_CH_LAYOUT_5POINT1_BACK,
1499 120b4557 Justin Ruggles
        0 },
1500 de6d9b64 Fabrice Bellard
};