Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 834550ea

History | View | Annotate | Download (56.8 KB)

1 de6d9b64 Fabrice Bellard
/*
2 14b70628 Justin Ruggles
 * The simplest AC-3 encoder
3 406792e7 Diego Biurrun
 * Copyright (c) 2000 Fabrice Bellard
4 27af78cf Justin Ruggles
 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5
 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6 de6d9b64 Fabrice Bellard
 *
7 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
8
 *
9
 * FFmpeg is free software; you can redistribute it and/or
10 ff4ec49e Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
13 de6d9b64 Fabrice Bellard
 *
14 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
15 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ff4ec49e Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18 de6d9b64 Fabrice Bellard
 *
19 ff4ec49e Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
20 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
21 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 de6d9b64 Fabrice Bellard
 */
23 983e3246 Michael Niedermayer
24
/**
25 ba87f080 Diego Biurrun
 * @file
26 14b70628 Justin Ruggles
 * The simplest AC-3 encoder.
27 983e3246 Michael Niedermayer
 */
28 6a988808 Justin Ruggles
29 1a565432 Fabrice Bellard
//#define DEBUG
30 22c0b03c Justin Ruggles
31 63e8d976 Stefano Sabatini
#include "libavcore/audioconvert.h"
32 245976da Diego Biurrun
#include "libavutil/crc.h"
33 de6d9b64 Fabrice Bellard
#include "avcodec.h"
34 b2755007 Stefano Sabatini
#include "put_bits.h"
35 8846ee54 Justin Ruggles
#include "dsputil.h"
36 6107fa87 Fabrice Bellard
#include "ac3.h"
37 120b4557 Justin Ruggles
#include "audioconvert.h"
38 6107fa87 Fabrice Bellard
39 2f8ae522 Justin Ruggles
40 e77fd066 Justin Ruggles
#define MDCT_NBITS 9
41
#define MDCT_SAMPLES (1 << MDCT_NBITS)
42
43 f94bacc5 Justin Ruggles
/** Maximum number of exponent groups. +1 for separate DC exponent. */
44
#define AC3_MAX_EXP_GROUPS 85
45
46 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^bits and convert to an integer. */
47 918cd225 Justin Ruggles
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
48
49 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
50 e77fd066 Justin Ruggles
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
51
52 2f8ae522 Justin Ruggles
53 c36ce0f8 Justin Ruggles
/**
54
 * Compex number.
55
 * Used in fixed-point MDCT calculation.
56
 */
57 e77fd066 Justin Ruggles
typedef struct IComplex {
58
    int16_t re,im;
59
} IComplex;
60
61 c41ac4f8 Justin Ruggles
typedef struct AC3MDCTContext {
62
    AVCodecContext *avctx;                  ///< parent context for av_log()
63
    int16_t *rot_tmp;                       ///< temp buffer for pre-rotated samples
64
    IComplex *cplx_tmp;                     ///< temp buffer for complex pre-rotated samples
65
} AC3MDCTContext;
66
67 c36ce0f8 Justin Ruggles
/**
68 5901cebe Justin Ruggles
 * Data for a single audio block.
69
 */
70
typedef struct AC3Block {
71 b6f6204d Justin Ruggles
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
72
    int32_t  **mdct_coef;                       ///< MDCT coefficients
73
    uint8_t  **exp;                             ///< original exponents
74
    uint8_t  **grouped_exp;                     ///< grouped exponents
75
    int16_t  **psd;                             ///< psd per frequency bin
76
    int16_t  **band_psd;                        ///< psd per critical band
77
    int16_t  **mask;                            ///< masking curve
78
    uint16_t **qmant;                           ///< quantized mantissas
79
    uint8_t  num_exp_groups[AC3_MAX_CHANNELS];  ///< number of exponent groups
80
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];    ///< exponent strategies
81
    int8_t   exp_shift[AC3_MAX_CHANNELS];       ///< exponent shift values
82 5901cebe Justin Ruggles
} AC3Block;
83
84
/**
85 c36ce0f8 Justin Ruggles
 * AC-3 encoder private context.
86
 */
87 6107fa87 Fabrice Bellard
typedef struct AC3EncodeContext {
88 07965463 Justin Ruggles
    PutBitContext pb;                       ///< bitstream writer context
89 8846ee54 Justin Ruggles
    DSPContext dsp;
90 c41ac4f8 Justin Ruggles
    AC3MDCTContext mdct;                    ///< MDCT context
91 7e5a4bf8 Justin Ruggles
92 5901cebe Justin Ruggles
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
93
94 07965463 Justin Ruggles
    int bitstream_id;                       ///< bitstream id                           (bsid)
95
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
96 7e5a4bf8 Justin Ruggles
97 07965463 Justin Ruggles
    int bit_rate;                           ///< target bit rate, in bits-per-second
98
    int sample_rate;                        ///< sampling frequency, in Hz
99 7e5a4bf8 Justin Ruggles
100 07965463 Justin Ruggles
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
101 427e2293 Justin Ruggles
    int frame_size;                         ///< current frame size in bytes
102 07965463 Justin Ruggles
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
103
    int bits_written;                       ///< bit count    (used to avg. bitrate)
104
    int samples_written;                    ///< sample count (used to avg. bitrate)
105 7e5a4bf8 Justin Ruggles
106 07965463 Justin Ruggles
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
107
    int channels;                           ///< total number of channels               (nchans)
108
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
109
    int lfe_channel;                        ///< channel index of the LFE channel
110
    int channel_mode;                       ///< channel mode                           (acmod)
111
    const uint8_t *channel_map;             ///< channel map used to reorder channels
112 7e5a4bf8 Justin Ruggles
113 07965463 Justin Ruggles
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
114 6107fa87 Fabrice Bellard
    int nb_coefs[AC3_MAX_CHANNELS];
115 115329f1 Diego Biurrun
116 6107fa87 Fabrice Bellard
    /* bitrate allocation control */
117 07965463 Justin Ruggles
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
118
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
119
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
120
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
121
    int floor_code;                         ///< floor code                             (floorcod)
122
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
123
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
124
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
125
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
126 359c1d19 Justin Ruggles
    int frame_bits;                         ///< all frame bits except exponents and mantissas
127
    int exponent_bits;                      ///< number of bits used for exponents
128 7e5a4bf8 Justin Ruggles
129 6107fa87 Fabrice Bellard
    /* mantissa encoding */
130 07965463 Justin Ruggles
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
131 b6a1e523 Justin Ruggles
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
132 7e5a4bf8 Justin Ruggles
133 e8d21fba Justin Ruggles
    int16_t **planar_samples;
134 171bc51c Justin Ruggles
    uint8_t *bap_buffer;
135
    uint8_t *bap1_buffer;
136 b6f6204d Justin Ruggles
    int32_t *mdct_coef_buffer;
137
    uint8_t *exp_buffer;
138
    uint8_t *grouped_exp_buffer;
139
    int16_t *psd_buffer;
140
    int16_t *band_psd_buffer;
141
    int16_t *mask_buffer;
142
    uint16_t *qmant_buffer;
143 aa645b98 Justin Ruggles
144
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
145 6107fa87 Fabrice Bellard
} AC3EncodeContext;
146 de6d9b64 Fabrice Bellard
147 2f8ae522 Justin Ruggles
148 c36ce0f8 Justin Ruggles
/** MDCT and FFT tables */
149 4258a0a3 Justin Ruggles
static int16_t costab[64];
150
static int16_t sintab[64];
151
static int16_t xcos1[128];
152
static int16_t xsin1[128];
153 de6d9b64 Fabrice Bellard
154 2f8ae522 Justin Ruggles
155 c36ce0f8 Justin Ruggles
/**
156 160d85f5 Justin Ruggles
 * Adjust the frame size to make the average bit rate match the target bit rate.
157
 * This is only needed for 11025, 22050, and 44100 sample rates.
158
 */
159
static void adjust_frame_size(AC3EncodeContext *s)
160
{
161
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
162
        s->bits_written    -= s->bit_rate;
163
        s->samples_written -= s->sample_rate;
164
    }
165 2d82d9b1 Justin Ruggles
    s->frame_size = s->frame_size_min +
166
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
167 160d85f5 Justin Ruggles
    s->bits_written    += s->frame_size * 8;
168
    s->samples_written += AC3_FRAME_SIZE;
169
}
170
171
172
/**
173 4acc790f Justin Ruggles
 * Deinterleave input samples.
174
 * Channels are reordered from FFmpeg's default order to AC-3 order.
175
 */
176
static void deinterleave_input_samples(AC3EncodeContext *s,
177 266d24be Justin Ruggles
                                       const int16_t *samples)
178 4acc790f Justin Ruggles
{
179
    int ch, i;
180
181
    /* deinterleave and remap input samples */
182
    for (ch = 0; ch < s->channels; ch++) {
183
        const int16_t *sptr;
184
        int sinc;
185
186
        /* copy last 256 samples of previous frame to the start of the current frame */
187 1c3e117e Justin Ruggles
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
188 266d24be Justin Ruggles
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
189 4acc790f Justin Ruggles
190
        /* deinterleave */
191
        sinc = s->channels;
192
        sptr = samples + s->channel_map[ch];
193
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
194 266d24be Justin Ruggles
            s->planar_samples[ch][i] = *sptr;
195 4acc790f Justin Ruggles
            sptr += sinc;
196
        }
197
    }
198
}
199
200
201
/**
202 c41ac4f8 Justin Ruggles
 * Finalize MDCT and free allocated memory.
203
 */
204
static av_cold void mdct_end(AC3MDCTContext *mdct)
205
{
206
    av_freep(&mdct->rot_tmp);
207
    av_freep(&mdct->cplx_tmp);
208
}
209
210
211
212
/**
213 c36ce0f8 Justin Ruggles
 * Initialize FFT tables.
214
 * @param ln log2(FFT size)
215
 */
216 5ef251e5 Daniel Verkamp
static av_cold void fft_init(int ln)
217 de6d9b64 Fabrice Bellard
{
218 b84a211b Justin Ruggles
    int i, n, n2;
219 de6d9b64 Fabrice Bellard
    float alpha;
220
221 b84a211b Justin Ruggles
    n  = 1 << ln;
222
    n2 = n >> 1;
223 de6d9b64 Fabrice Bellard
224 b84a211b Justin Ruggles
    for (i = 0; i < n2; i++) {
225
        alpha     = 2.0 * M_PI * i / n;
226 918cd225 Justin Ruggles
        costab[i] = FIX15(cos(alpha));
227
        sintab[i] = FIX15(sin(alpha));
228 de6d9b64 Fabrice Bellard
    }
229
}
230
231 2f8ae522 Justin Ruggles
232 c36ce0f8 Justin Ruggles
/**
233
 * Initialize MDCT tables.
234
 * @param nbits log2(MDCT size)
235
 */
236 c41ac4f8 Justin Ruggles
static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
237 a8d2b06b Justin Ruggles
{
238 b84a211b Justin Ruggles
    int i, n, n4;
239
240
    n  = 1 << nbits;
241
    n4 = n >> 2;
242 a8d2b06b Justin Ruggles
243
    fft_init(nbits - 2);
244
245 c41ac4f8 Justin Ruggles
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),
246
                     mdct_alloc_fail);
247
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
248
                     mdct_alloc_fail);
249
250 6a988808 Justin Ruggles
    for (i = 0; i < n4; i++) {
251 b84a211b Justin Ruggles
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
252 918cd225 Justin Ruggles
        xcos1[i] = FIX15(-cos(alpha));
253
        xsin1[i] = FIX15(-sin(alpha));
254 a8d2b06b Justin Ruggles
    }
255 c41ac4f8 Justin Ruggles
256
    return 0;
257
mdct_alloc_fail:
258
    return AVERROR(ENOMEM);
259 a8d2b06b Justin Ruggles
}
260
261 2f8ae522 Justin Ruggles
262 c36ce0f8 Justin Ruggles
/** Butterfly op */
263 6a988808 Justin Ruggles
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
264
{                                                       \
265
  int ax, ay, bx, by;                                   \
266
  bx  = pre1;                                           \
267
  by  = pim1;                                           \
268
  ax  = qre1;                                           \
269
  ay  = qim1;                                           \
270
  pre = (bx + ax) >> 1;                                 \
271
  pim = (by + ay) >> 1;                                 \
272
  qre = (bx - ax) >> 1;                                 \
273
  qim = (by - ay) >> 1;                                 \
274 de6d9b64 Fabrice Bellard
}
275
276 2f8ae522 Justin Ruggles
277 c36ce0f8 Justin Ruggles
/** Complex multiply */
278 6a988808 Justin Ruggles
#define CMUL(pre, pim, are, aim, bre, bim)              \
279
{                                                       \
280
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
281
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
282 de6d9b64 Fabrice Bellard
}
283
284
285 c36ce0f8 Justin Ruggles
/**
286
 * Calculate a 2^n point complex FFT on 2^ln points.
287
 * @param z  complex input/output samples
288
 * @param ln log2(FFT size)
289
 */
290 de6d9b64 Fabrice Bellard
static void fft(IComplex *z, int ln)
291
{
292 6a988808 Justin Ruggles
    int j, l, np, np2;
293
    int nblocks, nloops;
294 de6d9b64 Fabrice Bellard
    register IComplex *p,*q;
295
    int tmp_re, tmp_im;
296
297
    np = 1 << ln;
298
299
    /* reverse */
300 6a988808 Justin Ruggles
    for (j = 0; j < np; j++) {
301 91cc5d37 Francesco Lavra
        int k = av_reverse[j] >> (8 - ln);
302 f952b30c Reimar Döffinger
        if (k < j)
303
            FFSWAP(IComplex, z[k], z[j]);
304 de6d9b64 Fabrice Bellard
    }
305
306
    /* pass 0 */
307
308 6a988808 Justin Ruggles
    p = &z[0];
309
    j = np >> 1;
310 de6d9b64 Fabrice Bellard
    do {
311 115329f1 Diego Biurrun
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
312 de6d9b64 Fabrice Bellard
           p[0].re, p[0].im, p[1].re, p[1].im);
313 6a988808 Justin Ruggles
        p += 2;
314
    } while (--j);
315 de6d9b64 Fabrice Bellard
316
    /* pass 1 */
317
318 6a988808 Justin Ruggles
    p = &z[0];
319
    j = np >> 2;
320 de6d9b64 Fabrice Bellard
    do {
321 6a988808 Justin Ruggles
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
322
           p[0].re, p[0].im, p[2].re,  p[2].im);
323
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
324 de6d9b64 Fabrice Bellard
           p[1].re, p[1].im, p[3].im, -p[3].re);
325
        p+=4;
326 6a988808 Justin Ruggles
    } while (--j);
327 de6d9b64 Fabrice Bellard
328
    /* pass 2 .. ln-1 */
329
330
    nblocks = np >> 3;
331 6a988808 Justin Ruggles
    nloops  =  1 << 2;
332
    np2     = np >> 1;
333 de6d9b64 Fabrice Bellard
    do {
334
        p = z;
335
        q = z + nloops;
336 6a988808 Justin Ruggles
        for (j = 0; j < nblocks; j++) {
337 de6d9b64 Fabrice Bellard
            BF(p->re, p->im, q->re, q->im,
338
               p->re, p->im, q->re, q->im);
339
            p++;
340
            q++;
341
            for(l = nblocks; l < np2; l += nblocks) {
342
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
343 6a988808 Justin Ruggles
                BF(p->re, p->im, q->re,  q->im,
344 de6d9b64 Fabrice Bellard
                   p->re, p->im, tmp_re, tmp_im);
345
                p++;
346
                q++;
347
            }
348
            p += nloops;
349
            q += nloops;
350
        }
351
        nblocks = nblocks >> 1;
352 6a988808 Justin Ruggles
        nloops  = nloops  << 1;
353
    } while (nblocks);
354 de6d9b64 Fabrice Bellard
}
355
356 2f8ae522 Justin Ruggles
357 c36ce0f8 Justin Ruggles
/**
358
 * Calculate a 512-point MDCT
359
 * @param out 256 output frequency coefficients
360
 * @param in  512 windowed input audio samples
361
 */
362 c41ac4f8 Justin Ruggles
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
363 de6d9b64 Fabrice Bellard
{
364 e29065f7 Justin Ruggles
    int i, re, im;
365 c41ac4f8 Justin Ruggles
    int16_t *rot = mdct->rot_tmp;
366
    IComplex *x  = mdct->cplx_tmp;
367 de6d9b64 Fabrice Bellard
368
    /* shift to simplify computations */
369 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++)
370 7066cc8f Justin Ruggles
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
371 9d853336 Justin Ruggles
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
372 115329f1 Diego Biurrun
373 de6d9b64 Fabrice Bellard
    /* pre rotation */
374 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
375
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
376 7066cc8f Justin Ruggles
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
377 de6d9b64 Fabrice Bellard
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
378
    }
379
380
    fft(x, MDCT_NBITS - 2);
381 115329f1 Diego Biurrun
382 de6d9b64 Fabrice Bellard
    /* post rotation */
383 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
384 de6d9b64 Fabrice Bellard
        re = x[i].re;
385
        im = x[i].im;
386 e29065f7 Justin Ruggles
        CMUL(out[MDCT_SAMPLES/2-1-2*i], out[2*i], re, im, xsin1[i], xcos1[i]);
387 de6d9b64 Fabrice Bellard
    }
388
}
389
390 2f8ae522 Justin Ruggles
391 c36ce0f8 Justin Ruggles
/**
392 0a0a8500 Justin Ruggles
 * Apply KBD window to input samples prior to MDCT.
393
 */
394
static void apply_window(int16_t *output, const int16_t *input,
395
                         const int16_t *window, int n)
396
{
397
    int i;
398
    int n2 = n >> 1;
399
400
    for (i = 0; i < n2; i++) {
401
        output[i]     = MUL16(input[i],     window[i]) >> 15;
402
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
403
    }
404
}
405
406
407
/**
408 c36ce0f8 Justin Ruggles
 * Calculate the log2() of the maximum absolute value in an array.
409
 * @param tab input array
410
 * @param n   number of values in the array
411
 * @return    log2(max(abs(tab[])))
412
 */
413 e77fd066 Justin Ruggles
static int log2_tab(int16_t *tab, int n)
414
{
415
    int i, v;
416
417
    v = 0;
418
    for (i = 0; i < n; i++)
419
        v |= abs(tab[i]);
420
421
    return av_log2(v);
422
}
423
424 2f8ae522 Justin Ruggles
425 c36ce0f8 Justin Ruggles
/**
426
 * Left-shift each value in an array by a specified amount.
427
 * @param tab    input array
428
 * @param n      number of values in the array
429
 * @param lshift left shift amount. a negative value means right shift.
430
 */
431 e77fd066 Justin Ruggles
static void lshift_tab(int16_t *tab, int n, int lshift)
432
{
433
    int i;
434
435
    if (lshift > 0) {
436 2d82d9b1 Justin Ruggles
        for (i = 0; i < n; i++)
437 e77fd066 Justin Ruggles
            tab[i] <<= lshift;
438
    } else if (lshift < 0) {
439
        lshift = -lshift;
440
        for (i = 0; i < n; i++)
441
            tab[i] >>= lshift;
442
    }
443
}
444
445 2f8ae522 Justin Ruggles
446 c36ce0f8 Justin Ruggles
/**
447 0a0a8500 Justin Ruggles
 * Normalize the input samples to use the maximum available precision.
448
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
449
 * match the 24-bit internal precision for MDCT coefficients.
450
 *
451
 * @return exponent shift
452
 */
453 266d24be Justin Ruggles
static int normalize_samples(AC3EncodeContext *s)
454 0a0a8500 Justin Ruggles
{
455 266d24be Justin Ruggles
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
456 0a0a8500 Justin Ruggles
    v = FFMAX(0, v);
457 266d24be Justin Ruggles
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
458 0a0a8500 Justin Ruggles
    return v - 9;
459
}
460
461
462
/**
463
 * Apply the MDCT to input samples to generate frequency coefficients.
464
 * This applies the KBD window and normalizes the input to reduce precision
465
 * loss due to fixed-point calculations.
466
 */
467 266d24be Justin Ruggles
static void apply_mdct(AC3EncodeContext *s)
468 0a0a8500 Justin Ruggles
{
469
    int blk, ch;
470
471
    for (ch = 0; ch < s->channels; ch++) {
472
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
473 5901cebe Justin Ruggles
            AC3Block *block = &s->blocks[blk];
474 266d24be Justin Ruggles
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
475 0a0a8500 Justin Ruggles
476 266d24be Justin Ruggles
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
477 0a0a8500 Justin Ruggles
478 5901cebe Justin Ruggles
            block->exp_shift[ch] = normalize_samples(s);
479 0a0a8500 Justin Ruggles
480 c41ac4f8 Justin Ruggles
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
481 0a0a8500 Justin Ruggles
        }
482
    }
483
}
484
485
486
/**
487 dfdf73eb Justin Ruggles
 * Extract exponents from the MDCT coefficients.
488
 * This takes into account the normalization that was done to the input samples
489
 * by adjusting the exponents by the exponent shift values.
490
 */
491 266d24be Justin Ruggles
static void extract_exponents(AC3EncodeContext *s)
492 dfdf73eb Justin Ruggles
{
493
    int blk, ch, i;
494
495
    for (ch = 0; ch < s->channels; ch++) {
496
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
497 5901cebe Justin Ruggles
            AC3Block *block = &s->blocks[blk];
498 dfdf73eb Justin Ruggles
            for (i = 0; i < AC3_MAX_COEFS; i++) {
499
                int e;
500 5901cebe Justin Ruggles
                int v = abs(block->mdct_coef[ch][i]);
501 dfdf73eb Justin Ruggles
                if (v == 0)
502
                    e = 24;
503
                else {
504 5901cebe Justin Ruggles
                    e = 23 - av_log2(v) + block->exp_shift[ch];
505 dfdf73eb Justin Ruggles
                    if (e >= 24) {
506
                        e = 24;
507 5901cebe Justin Ruggles
                        block->mdct_coef[ch][i] = 0;
508 dfdf73eb Justin Ruggles
                    }
509
                }
510 5901cebe Justin Ruggles
                block->exp[ch][i] = e;
511 dfdf73eb Justin Ruggles
            }
512
        }
513
    }
514
}
515
516
517
/**
518 c36ce0f8 Justin Ruggles
 * Exponent Difference Threshold.
519
 * New exponents are sent if their SAD exceed this number.
520
 */
521 6a988808 Justin Ruggles
#define EXP_DIFF_THRESHOLD 1000
522
523 2f8ae522 Justin Ruggles
524 c36ce0f8 Justin Ruggles
/**
525
 * Calculate exponent strategies for all blocks in a single channel.
526
 */
527 8846ee54 Justin Ruggles
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp)
528 de6d9b64 Fabrice Bellard
{
529 ce67b7cd Justin Ruggles
    int blk, blk1;
530 de6d9b64 Fabrice Bellard
    int exp_diff;
531 115329f1 Diego Biurrun
532 de6d9b64 Fabrice Bellard
    /* estimate if the exponent variation & decide if they should be
533
       reused in the next frame */
534 d7da8080 Justin Ruggles
    exp_strategy[0] = EXP_NEW;
535 ce67b7cd Justin Ruggles
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
536 8846ee54 Justin Ruggles
        exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
537 de6d9b64 Fabrice Bellard
        if (exp_diff > EXP_DIFF_THRESHOLD)
538 d7da8080 Justin Ruggles
            exp_strategy[blk] = EXP_NEW;
539 de6d9b64 Fabrice Bellard
        else
540 d7da8080 Justin Ruggles
            exp_strategy[blk] = EXP_REUSE;
541 de6d9b64 Fabrice Bellard
    }
542 30b68f33 Zdenek Kabelac
543 de6d9b64 Fabrice Bellard
    /* now select the encoding strategy type : if exponents are often
544
       recoded, we use a coarse encoding */
545 ce67b7cd Justin Ruggles
    blk = 0;
546
    while (blk < AC3_MAX_BLOCKS) {
547
        blk1 = blk + 1;
548 d7da8080 Justin Ruggles
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
549 ce67b7cd Justin Ruggles
            blk1++;
550
        switch (blk1 - blk) {
551 d7da8080 Justin Ruggles
        case 1:  exp_strategy[blk] = EXP_D45; break;
552 de6d9b64 Fabrice Bellard
        case 2:
553 d7da8080 Justin Ruggles
        case 3:  exp_strategy[blk] = EXP_D25; break;
554
        default: exp_strategy[blk] = EXP_D15; break;
555 de6d9b64 Fabrice Bellard
        }
556 ce67b7cd Justin Ruggles
        blk = blk1;
557 de6d9b64 Fabrice Bellard
    }
558
}
559
560 2f8ae522 Justin Ruggles
561 c36ce0f8 Justin Ruggles
/**
562 dfdf73eb Justin Ruggles
 * Calculate exponent strategies for all channels.
563 d7da8080 Justin Ruggles
 * Array arrangement is reversed to simplify the per-channel calculation.
564 dfdf73eb Justin Ruggles
 */
565 266d24be Justin Ruggles
static void compute_exp_strategy(AC3EncodeContext *s)
566 dfdf73eb Justin Ruggles
{
567 d7da8080 Justin Ruggles
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
568
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
569
    int ch, blk;
570 dfdf73eb Justin Ruggles
571 d7da8080 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++) {
572
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
573 5901cebe Justin Ruggles
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
574
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
575 d7da8080 Justin Ruggles
        }
576
577 8846ee54 Justin Ruggles
        compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
578 d7da8080 Justin Ruggles
579
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
580 5901cebe Justin Ruggles
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
581 d7da8080 Justin Ruggles
    }
582
    if (s->lfe_on) {
583
        ch = s->lfe_channel;
584 5901cebe Justin Ruggles
        s->blocks[0].exp_strategy[ch] = EXP_D15;
585 06f6f785 Justin Ruggles
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
586 5901cebe Justin Ruggles
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
587 dfdf73eb Justin Ruggles
    }
588
}
589
590
591
/**
592 c36ce0f8 Justin Ruggles
 * Set each encoded exponent in a block to the minimum of itself and the
593
 * exponent in the same frequency bin of a following block.
594
 * exp[i] = min(exp[i], exp1[i]
595
 */
596 2d82d9b1 Justin Ruggles
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
597 de6d9b64 Fabrice Bellard
{
598
    int i;
599 6a988808 Justin Ruggles
    for (i = 0; i < n; i++) {
600 de6d9b64 Fabrice Bellard
        if (exp1[i] < exp[i])
601
            exp[i] = exp1[i];
602
    }
603
}
604 115329f1 Diego Biurrun
605 2f8ae522 Justin Ruggles
606 c36ce0f8 Justin Ruggles
/**
607
 * Update the exponents so that they are the ones the decoder will decode.
608
 */
609 27af78cf Justin Ruggles
static void encode_exponents_blk_ch(uint8_t *exp,
610 d3325d55 Justin Ruggles
                                    int nb_exps, int exp_strategy,
611
                                    uint8_t *num_exp_groups)
612 de6d9b64 Fabrice Bellard
{
613 834550ea Justin Ruggles
    int group_size, nb_groups, i, k;
614 de6d9b64 Fabrice Bellard
615 02877def Justin Ruggles
    group_size = exp_strategy + (exp_strategy == EXP_D45);
616 d3325d55 Justin Ruggles
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
617
    nb_groups = *num_exp_groups * 3;
618 de6d9b64 Fabrice Bellard
619
    /* for each group, compute the minimum exponent */
620 834550ea Justin Ruggles
    switch(exp_strategy) {
621
    case EXP_D25:
622
        for (i = 1, k = 1; i <= nb_groups; i++) {
623
            uint8_t exp_min = exp[k];
624
            if (exp[k+1] < exp_min)
625
                exp_min = exp[k+1];
626
            exp[i] = exp_min;
627
            k += 2;
628 de6d9b64 Fabrice Bellard
        }
629 834550ea Justin Ruggles
        break;
630
    case EXP_D45:
631
        for (i = 1, k = 1; i <= nb_groups; i++) {
632
            uint8_t exp_min = exp[k];
633
            if (exp[k+1] < exp_min)
634
                exp_min = exp[k+1];
635
            if (exp[k+2] < exp_min)
636
                exp_min = exp[k+2];
637
            if (exp[k+3] < exp_min)
638
                exp_min = exp[k+3];
639
            exp[i] = exp_min;
640
            k += 4;
641
        }
642
        break;
643 27af78cf Justin Ruggles
    }
644 de6d9b64 Fabrice Bellard
645
    /* constraint for DC exponent */
646 27af78cf Justin Ruggles
    if (exp[0] > 15)
647
        exp[0] = 15;
648 de6d9b64 Fabrice Bellard
649 6a988808 Justin Ruggles
    /* decrease the delta between each groups to within 2 so that they can be
650
       differentially encoded */
651
    for (i = 1; i <= nb_groups; i++)
652 27af78cf Justin Ruggles
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
653 cdedf7e6 Justin Ruggles
    i--;
654
    while (--i >= 0)
655 27af78cf Justin Ruggles
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
656 e44cad52 Jeff Muizelaar
657 de6d9b64 Fabrice Bellard
    /* now we have the exponent values the decoder will see */
658 834550ea Justin Ruggles
    switch (exp_strategy) {
659
    case EXP_D25:
660
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
661
            uint8_t exp1 = exp[i];
662
            exp[k--] = exp1;
663
            exp[k--] = exp1;
664
        }
665
        break;
666
    case EXP_D45:
667
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
668
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
669
            k -= 4;
670
        }
671
        break;
672 de6d9b64 Fabrice Bellard
    }
673
}
674
675 2f8ae522 Justin Ruggles
676 c36ce0f8 Justin Ruggles
/**
677 dfdf73eb Justin Ruggles
 * Encode exponents from original extracted form to what the decoder will see.
678
 * This copies and groups exponents based on exponent strategy and reduces
679
 * deltas between adjacent exponent groups so that they can be differentially
680
 * encoded.
681
 */
682 266d24be Justin Ruggles
static void encode_exponents(AC3EncodeContext *s)
683 dfdf73eb Justin Ruggles
{
684
    int blk, blk1, blk2, ch;
685 5901cebe Justin Ruggles
    AC3Block *block, *block1, *block2;
686 dfdf73eb Justin Ruggles
687
    for (ch = 0; ch < s->channels; ch++) {
688
        blk = 0;
689 5901cebe Justin Ruggles
        block = &s->blocks[0];
690 dfdf73eb Justin Ruggles
        while (blk < AC3_MAX_BLOCKS) {
691
            blk1 = blk + 1;
692 5901cebe Justin Ruggles
            block1 = block + 1;
693 2d82d9b1 Justin Ruggles
            /* for the EXP_REUSE case we select the min of the exponents */
694 5901cebe Justin Ruggles
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
695
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
696 dfdf73eb Justin Ruggles
                blk1++;
697 5901cebe Justin Ruggles
                block1++;
698 dfdf73eb Justin Ruggles
            }
699 27af78cf Justin Ruggles
            encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
700 5901cebe Justin Ruggles
                                    block->exp_strategy[ch],
701
                                    &block->num_exp_groups[ch]);
702 dfdf73eb Justin Ruggles
            /* copy encoded exponents for reuse case */
703 5901cebe Justin Ruggles
            block2 = block + 1;
704
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
705 27af78cf Justin Ruggles
                memcpy(block2->exp[ch], block->exp[ch],
706 dfdf73eb Justin Ruggles
                       s->nb_coefs[ch] * sizeof(uint8_t));
707
            }
708
            blk = blk1;
709 5901cebe Justin Ruggles
            block = block1;
710 dfdf73eb Justin Ruggles
        }
711
    }
712 f94bacc5 Justin Ruggles
}
713
714
715
/**
716
 * Group exponents.
717
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
718
 * varies depending on exponent strategy and bandwidth.
719
 */
720 266d24be Justin Ruggles
static void group_exponents(AC3EncodeContext *s)
721 f94bacc5 Justin Ruggles
{
722
    int blk, ch, i;
723
    int group_size, bit_count;
724
    uint8_t *p;
725
    int delta0, delta1, delta2;
726
    int exp0, exp1;
727
728
    bit_count = 0;
729
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
730 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
731 f94bacc5 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
732 5901cebe Justin Ruggles
            if (block->exp_strategy[ch] == EXP_REUSE) {
733
                block->num_exp_groups[ch] = 0;
734 f94bacc5 Justin Ruggles
                continue;
735
            }
736 5901cebe Justin Ruggles
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
737
            bit_count += 4 + (block->num_exp_groups[ch] * 7);
738 27af78cf Justin Ruggles
            p = block->exp[ch];
739 f94bacc5 Justin Ruggles
740
            /* DC exponent */
741
            exp1 = *p++;
742 5901cebe Justin Ruggles
            block->grouped_exp[ch][0] = exp1;
743 f94bacc5 Justin Ruggles
744
            /* remaining exponents are delta encoded */
745 5901cebe Justin Ruggles
            for (i = 1; i <= block->num_exp_groups[ch]; i++) {
746 f94bacc5 Justin Ruggles
                /* merge three delta in one code */
747
                exp0   = exp1;
748
                exp1   = p[0];
749
                p     += group_size;
750
                delta0 = exp1 - exp0 + 2;
751
752
                exp0   = exp1;
753
                exp1   = p[0];
754
                p     += group_size;
755
                delta1 = exp1 - exp0 + 2;
756
757
                exp0   = exp1;
758
                exp1   = p[0];
759
                p     += group_size;
760
                delta2 = exp1 - exp0 + 2;
761
762 5901cebe Justin Ruggles
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
763 f94bacc5 Justin Ruggles
            }
764
        }
765
    }
766 dfdf73eb Justin Ruggles
767 359c1d19 Justin Ruggles
    s->exponent_bits = bit_count;
768 dfdf73eb Justin Ruggles
}
769
770
771
/**
772
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
773
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
774
 * and encode final exponents.
775
 */
776 266d24be Justin Ruggles
static void process_exponents(AC3EncodeContext *s)
777 dfdf73eb Justin Ruggles
{
778 266d24be Justin Ruggles
    extract_exponents(s);
779 dfdf73eb Justin Ruggles
780 266d24be Justin Ruggles
    compute_exp_strategy(s);
781 dfdf73eb Justin Ruggles
782 266d24be Justin Ruggles
    encode_exponents(s);
783 f94bacc5 Justin Ruggles
784 266d24be Justin Ruggles
    group_exponents(s);
785 dfdf73eb Justin Ruggles
}
786
787
788
/**
789 793bbf95 Justin Ruggles
 * Initialize bit allocation.
790
 * Set default parameter codes and calculate parameter values.
791
 */
792
static void bit_alloc_init(AC3EncodeContext *s)
793
{
794
    int ch;
795
796
    /* init default parameters */
797
    s->slow_decay_code = 2;
798
    s->fast_decay_code = 1;
799
    s->slow_gain_code  = 1;
800
    s->db_per_bit_code = 2;
801
    s->floor_code      = 4;
802
    for (ch = 0; ch < s->channels; ch++)
803
        s->fast_gain_code[ch] = 4;
804
805
    /* initial snr offset */
806
    s->coarse_snr_offset = 40;
807
808
    /* compute real values */
809
    /* currently none of these values change during encoding, so we can just
810
       set them once at initialization */
811
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
812
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
813
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
814
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
815
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
816
}
817
818
819
/**
820 8999944e Justin Ruggles
 * Count the bits used to encode the frame, minus exponents and mantissas.
821
 */
822 266d24be Justin Ruggles
static void count_frame_bits(AC3EncodeContext *s)
823 8999944e Justin Ruggles
{
824
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
825
    int blk, ch;
826
    int frame_bits;
827
828
    /* header size */
829
    frame_bits = 65;
830
    frame_bits += frame_bits_inc[s->channel_mode];
831
832
    /* audio blocks */
833
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
834
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
835
        if (s->channel_mode == AC3_CHMODE_STEREO) {
836
            frame_bits++; /* rematstr */
837
            if (!blk)
838
                frame_bits += 4;
839
        }
840
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
841
        if (s->lfe_on)
842
            frame_bits++; /* lfeexpstr */
843
        for (ch = 0; ch < s->fbw_channels; ch++) {
844 5901cebe Justin Ruggles
            if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
845 8999944e Justin Ruggles
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
846
        }
847
        frame_bits++; /* baie */
848
        frame_bits++; /* snr */
849
        frame_bits += 2; /* delta / skip */
850
    }
851
    frame_bits++; /* cplinu for block 0 */
852
    /* bit alloc info */
853
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
854
    /* csnroffset[6] */
855
    /* (fsnoffset[4] + fgaincod[4]) * c */
856
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
857
858
    /* auxdatae, crcrsv */
859
    frame_bits += 2;
860
861
    /* CRC */
862
    frame_bits += 16;
863
864 359c1d19 Justin Ruggles
    s->frame_bits = frame_bits;
865 8999944e Justin Ruggles
}
866
867
868
/**
869 c36ce0f8 Justin Ruggles
 * Calculate the number of bits needed to encode a set of mantissas.
870
 */
871 2d82d9b1 Justin Ruggles
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
872 de6d9b64 Fabrice Bellard
{
873 2d82d9b1 Justin Ruggles
    int bits, b, i;
874 de6d9b64 Fabrice Bellard
875
    bits = 0;
876 6a988808 Justin Ruggles
    for (i = 0; i < nb_coefs; i++) {
877 2d82d9b1 Justin Ruggles
        b = bap[i];
878
        switch (b) {
879 de6d9b64 Fabrice Bellard
        case 0:
880 2d82d9b1 Justin Ruggles
            /* bap=0 mantissas are not encoded */
881 de6d9b64 Fabrice Bellard
            break;
882
        case 1:
883 2d82d9b1 Justin Ruggles
            /* 3 mantissas in 5 bits */
884 115329f1 Diego Biurrun
            if (s->mant1_cnt == 0)
885 de6d9b64 Fabrice Bellard
                bits += 5;
886
            if (++s->mant1_cnt == 3)
887
                s->mant1_cnt = 0;
888
            break;
889
        case 2:
890 2d82d9b1 Justin Ruggles
            /* 3 mantissas in 7 bits */
891 115329f1 Diego Biurrun
            if (s->mant2_cnt == 0)
892 de6d9b64 Fabrice Bellard
                bits += 7;
893
            if (++s->mant2_cnt == 3)
894
                s->mant2_cnt = 0;
895
            break;
896
        case 3:
897
            bits += 3;
898
            break;
899
        case 4:
900 2d82d9b1 Justin Ruggles
            /* 2 mantissas in 7 bits */
901 de6d9b64 Fabrice Bellard
            if (s->mant4_cnt == 0)
902
                bits += 7;
903 115329f1 Diego Biurrun
            if (++s->mant4_cnt == 2)
904 de6d9b64 Fabrice Bellard
                s->mant4_cnt = 0;
905
            break;
906
        case 14:
907
            bits += 14;
908
            break;
909
        case 15:
910
            bits += 16;
911
            break;
912
        default:
913 2d82d9b1 Justin Ruggles
            bits += b - 1;
914 de6d9b64 Fabrice Bellard
            break;
915
        }
916
    }
917
    return bits;
918
}
919
920
921 c36ce0f8 Justin Ruggles
/**
922
 * Calculate masking curve based on the final exponents.
923
 * Also calculate the power spectral densities to use in future calculations.
924
 */
925 266d24be Justin Ruggles
static void bit_alloc_masking(AC3EncodeContext *s)
926 bbd16dea Justin Ruggles
{
927
    int blk, ch;
928
929 6a988808 Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
930 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
931 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
932 5901cebe Justin Ruggles
            if (block->exp_strategy[ch] == EXP_REUSE) {
933
                AC3Block *block1 = &s->blocks[blk-1];
934
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
935
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
936 bbd16dea Justin Ruggles
            } else {
937 27af78cf Justin Ruggles
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
938 bbd16dea Justin Ruggles
                                          s->nb_coefs[ch],
939 5901cebe Justin Ruggles
                                          block->psd[ch], block->band_psd[ch]);
940
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
941 bbd16dea Justin Ruggles
                                           0, s->nb_coefs[ch],
942 5ce21342 Justin Ruggles
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
943 bbd16dea Justin Ruggles
                                           ch == s->lfe_channel,
944 cc2a8443 Justin Ruggles
                                           DBA_NONE, 0, NULL, NULL, NULL,
945 5901cebe Justin Ruggles
                                           block->mask[ch]);
946 bbd16dea Justin Ruggles
            }
947
        }
948
    }
949
}
950
951 2f8ae522 Justin Ruggles
952 c36ce0f8 Justin Ruggles
/**
953 171bc51c Justin Ruggles
 * Ensure that bap for each block and channel point to the current bap_buffer.
954
 * They may have been switched during the bit allocation search.
955
 */
956
static void reset_block_bap(AC3EncodeContext *s)
957
{
958
    int blk, ch;
959
    if (s->blocks[0].bap[0] == s->bap_buffer)
960
        return;
961
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
962
        for (ch = 0; ch < s->channels; ch++) {
963
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
964
        }
965
    }
966
}
967
968
969
/**
970 c36ce0f8 Justin Ruggles
 * Run the bit allocation with a given SNR offset.
971
 * This calculates the bit allocation pointers that will be used to determine
972
 * the quantization of each mantissa.
973 70fcd7ea Justin Ruggles
 * @return the number of bits needed for mantissas if the given SNR offset is
974
 *         is used.
975 c36ce0f8 Justin Ruggles
 */
976 de6d9b64 Fabrice Bellard
static int bit_alloc(AC3EncodeContext *s,
977 a0d763fc Justin Ruggles
                     int snr_offset)
978 de6d9b64 Fabrice Bellard
{
979 ce67b7cd Justin Ruggles
    int blk, ch;
980 a0d763fc Justin Ruggles
    int mantissa_bits;
981 319708da Justin Ruggles
982 a0d763fc Justin Ruggles
    snr_offset = (snr_offset - 240) << 2;
983 de6d9b64 Fabrice Bellard
984 171bc51c Justin Ruggles
    reset_block_bap(s);
985 70fcd7ea Justin Ruggles
    mantissa_bits = 0;
986 ce67b7cd Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
987 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
988 de6d9b64 Fabrice Bellard
        s->mant1_cnt = 0;
989
        s->mant2_cnt = 0;
990
        s->mant4_cnt = 0;
991 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
992 5901cebe Justin Ruggles
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
993 5ce21342 Justin Ruggles
                                      s->nb_coefs[ch], snr_offset,
994 687671f0 Justin Ruggles
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
995 171bc51c Justin Ruggles
                                      block->bap[ch]);
996
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
997 de6d9b64 Fabrice Bellard
        }
998
    }
999 70fcd7ea Justin Ruggles
    return mantissa_bits;
1000 de6d9b64 Fabrice Bellard
}
1001
1002 2f8ae522 Justin Ruggles
1003 c36ce0f8 Justin Ruggles
/**
1004 cb6247cb Justin Ruggles
 * Constant bitrate bit allocation search.
1005
 * Find the largest SNR offset that will allow data to fit in the frame.
1006 c36ce0f8 Justin Ruggles
 */
1007 cb6247cb Justin Ruggles
static int cbr_bit_allocation(AC3EncodeContext *s)
1008 de6d9b64 Fabrice Bellard
{
1009 8999944e Justin Ruggles
    int ch;
1010 70fcd7ea Justin Ruggles
    int bits_left;
1011 a0d763fc Justin Ruggles
    int snr_offset;
1012 de6d9b64 Fabrice Bellard
1013 70fcd7ea Justin Ruggles
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1014 7da4dc17 Justin Ruggles
1015 a0d763fc Justin Ruggles
    snr_offset = s->coarse_snr_offset << 4;
1016 7da4dc17 Justin Ruggles
1017 a0d763fc Justin Ruggles
    while (snr_offset >= 0 &&
1018 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset) > bits_left) {
1019 a0d763fc Justin Ruggles
        snr_offset -= 64;
1020 7da4dc17 Justin Ruggles
    }
1021 2d82d9b1 Justin Ruggles
    if (snr_offset < 0)
1022 dc0bc0f8 Justin Ruggles
        return AVERROR(EINVAL);
1023 7da4dc17 Justin Ruggles
1024 171bc51c Justin Ruggles
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1025 a0d763fc Justin Ruggles
    while (snr_offset + 64 <= 1023 &&
1026 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 64) <= bits_left) {
1027 a0d763fc Justin Ruggles
        snr_offset += 64;
1028 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1029 de6d9b64 Fabrice Bellard
    }
1030 a0d763fc Justin Ruggles
    while (snr_offset + 16 <= 1023 &&
1031 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 16) <= bits_left) {
1032 a0d763fc Justin Ruggles
        snr_offset += 16;
1033 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1034 de6d9b64 Fabrice Bellard
    }
1035 a0d763fc Justin Ruggles
    while (snr_offset + 4 <= 1023 &&
1036 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1037 a0d763fc Justin Ruggles
        snr_offset += 4;
1038 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1039 de6d9b64 Fabrice Bellard
    }
1040 a0d763fc Justin Ruggles
    while (snr_offset + 1 <= 1023 &&
1041 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1042 a0d763fc Justin Ruggles
        snr_offset++;
1043 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1044 de6d9b64 Fabrice Bellard
    }
1045 171bc51c Justin Ruggles
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1046
    reset_block_bap(s);
1047 115329f1 Diego Biurrun
1048 a0d763fc Justin Ruggles
    s->coarse_snr_offset = snr_offset >> 4;
1049 6a988808 Justin Ruggles
    for (ch = 0; ch < s->channels; ch++)
1050 a0d763fc Justin Ruggles
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1051 22c0b03c Justin Ruggles
1052 de6d9b64 Fabrice Bellard
    return 0;
1053
}
1054
1055 2f8ae522 Justin Ruggles
1056 c36ce0f8 Justin Ruggles
/**
1057 cb6247cb Justin Ruggles
 * Perform bit allocation search.
1058
 * Finds the SNR offset value that maximizes quality and fits in the specified
1059
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1060
 * used to quantize the mantissas.
1061
 */
1062
static int compute_bit_allocation(AC3EncodeContext *s)
1063
{
1064
    count_frame_bits(s);
1065
1066
    bit_alloc_masking(s);
1067
1068
    return cbr_bit_allocation(s);
1069
}
1070
1071
1072
/**
1073 c36ce0f8 Justin Ruggles
 * Symmetric quantization on 'levels' levels.
1074
 */
1075 de6d9b64 Fabrice Bellard
static inline int sym_quant(int c, int e, int levels)
1076
{
1077
    int v;
1078
1079
    if (c >= 0) {
1080 8d67072f Fabrice Bellard
        v = (levels * (c << e)) >> 24;
1081
        v = (v + 1) >> 1;
1082 de6d9b64 Fabrice Bellard
        v = (levels >> 1) + v;
1083
    } else {
1084 8d67072f Fabrice Bellard
        v = (levels * ((-c) << e)) >> 24;
1085
        v = (v + 1) >> 1;
1086 de6d9b64 Fabrice Bellard
        v = (levels >> 1) - v;
1087
    }
1088 2d82d9b1 Justin Ruggles
    assert(v >= 0 && v < levels);
1089 de6d9b64 Fabrice Bellard
    return v;
1090
}
1091
1092 2f8ae522 Justin Ruggles
1093 c36ce0f8 Justin Ruggles
/**
1094
 * Asymmetric quantization on 2^qbits levels.
1095
 */
1096 de6d9b64 Fabrice Bellard
static inline int asym_quant(int c, int e, int qbits)
1097
{
1098
    int lshift, m, v;
1099
1100
    lshift = e + qbits - 24;
1101
    if (lshift >= 0)
1102
        v = c << lshift;
1103
    else
1104
        v = c >> (-lshift);
1105
    /* rounding */
1106
    v = (v + 1) >> 1;
1107
    m = (1 << (qbits-1));
1108
    if (v >= m)
1109
        v = m - 1;
1110
    assert(v >= -m);
1111
    return v & ((1 << qbits)-1);
1112
}
1113
1114 2f8ae522 Justin Ruggles
1115 c36ce0f8 Justin Ruggles
/**
1116 b6a1e523 Justin Ruggles
 * Quantize a set of mantissas for a single channel in a single block.
1117
 */
1118
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1119
                                      int32_t *mdct_coef, int8_t exp_shift,
1120 27af78cf Justin Ruggles
                                      uint8_t *exp, uint8_t *bap,
1121 b6a1e523 Justin Ruggles
                                      uint16_t *qmant, int n)
1122
{
1123
    int i;
1124
1125
    for (i = 0; i < n; i++) {
1126
        int v;
1127
        int c = mdct_coef[i];
1128 27af78cf Justin Ruggles
        int e = exp[i] - exp_shift;
1129 b6a1e523 Justin Ruggles
        int b = bap[i];
1130
        switch (b) {
1131
        case 0:
1132
            v = 0;
1133
            break;
1134
        case 1:
1135
            v = sym_quant(c, e, 3);
1136
            switch (s->mant1_cnt) {
1137
            case 0:
1138
                s->qmant1_ptr = &qmant[i];
1139
                v = 9 * v;
1140
                s->mant1_cnt = 1;
1141
                break;
1142
            case 1:
1143
                *s->qmant1_ptr += 3 * v;
1144
                s->mant1_cnt = 2;
1145
                v = 128;
1146
                break;
1147
            default:
1148
                *s->qmant1_ptr += v;
1149
                s->mant1_cnt = 0;
1150
                v = 128;
1151
                break;
1152
            }
1153
            break;
1154
        case 2:
1155
            v = sym_quant(c, e, 5);
1156
            switch (s->mant2_cnt) {
1157
            case 0:
1158
                s->qmant2_ptr = &qmant[i];
1159
                v = 25 * v;
1160
                s->mant2_cnt = 1;
1161
                break;
1162
            case 1:
1163
                *s->qmant2_ptr += 5 * v;
1164
                s->mant2_cnt = 2;
1165
                v = 128;
1166
                break;
1167
            default:
1168
                *s->qmant2_ptr += v;
1169
                s->mant2_cnt = 0;
1170
                v = 128;
1171
                break;
1172
            }
1173
            break;
1174
        case 3:
1175
            v = sym_quant(c, e, 7);
1176
            break;
1177
        case 4:
1178
            v = sym_quant(c, e, 11);
1179
            switch (s->mant4_cnt) {
1180
            case 0:
1181
                s->qmant4_ptr = &qmant[i];
1182
                v = 11 * v;
1183
                s->mant4_cnt = 1;
1184
                break;
1185
            default:
1186
                *s->qmant4_ptr += v;
1187
                s->mant4_cnt = 0;
1188
                v = 128;
1189
                break;
1190
            }
1191
            break;
1192
        case 5:
1193
            v = sym_quant(c, e, 15);
1194
            break;
1195
        case 14:
1196
            v = asym_quant(c, e, 14);
1197
            break;
1198
        case 15:
1199
            v = asym_quant(c, e, 16);
1200
            break;
1201
        default:
1202
            v = asym_quant(c, e, b - 1);
1203
            break;
1204
        }
1205
        qmant[i] = v;
1206
    }
1207
}
1208
1209
1210
/**
1211
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1212
 */
1213 266d24be Justin Ruggles
static void quantize_mantissas(AC3EncodeContext *s)
1214 b6a1e523 Justin Ruggles
{
1215
    int blk, ch;
1216
1217
1218
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1219 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
1220 b6a1e523 Justin Ruggles
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1221
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1222
1223
        for (ch = 0; ch < s->channels; ch++) {
1224 5901cebe Justin Ruggles
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1225 27af78cf Justin Ruggles
                                      block->exp[ch], block->bap[ch],
1226 5901cebe Justin Ruggles
                                      block->qmant[ch], s->nb_coefs[ch]);
1227 b6a1e523 Justin Ruggles
        }
1228
    }
1229
}
1230
1231
1232
/**
1233 5b44ede0 Justin Ruggles
 * Write the AC-3 frame header to the output bitstream.
1234
 */
1235
static void output_frame_header(AC3EncodeContext *s)
1236
{
1237
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1238
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1239
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1240
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1241
    put_bits(&s->pb, 5,  s->bitstream_id);
1242
    put_bits(&s->pb, 3,  s->bitstream_mode);
1243
    put_bits(&s->pb, 3,  s->channel_mode);
1244
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1245
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1246
    if (s->channel_mode & 0x04)
1247
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1248
    if (s->channel_mode == AC3_CHMODE_STEREO)
1249
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1250
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1251
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1252
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1253
    put_bits(&s->pb, 1, 0);         /* no lang code */
1254
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1255
    put_bits(&s->pb, 1, 0);         /* no copyright */
1256
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1257
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1258
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1259
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1260
}
1261
1262
1263
/**
1264 c36ce0f8 Justin Ruggles
 * Write one audio block to the output bitstream.
1265
 */
1266 de6d9b64 Fabrice Bellard
static void output_audio_block(AC3EncodeContext *s,
1267
                               int block_num)
1268
{
1269 f94bacc5 Justin Ruggles
    int ch, i, baie, rbnd;
1270 5901cebe Justin Ruggles
    AC3Block *block = &s->blocks[block_num];
1271 de6d9b64 Fabrice Bellard
1272 2d82d9b1 Justin Ruggles
    /* block switching */
1273 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1274 2d82d9b1 Justin Ruggles
        put_bits(&s->pb, 1, 0);
1275
1276
    /* dither flags */
1277 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1278 2d82d9b1 Justin Ruggles
        put_bits(&s->pb, 1, 1);
1279
1280
    /* dynamic range codes */
1281
    put_bits(&s->pb, 1, 0);
1282
1283
    /* channel coupling */
1284 6a988808 Justin Ruggles
    if (!block_num) {
1285 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1286
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1287
    } else {
1288
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1289
    }
1290
1291 2d82d9b1 Justin Ruggles
    /* stereo rematrixing */
1292 6a988808 Justin Ruggles
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1293
        if (!block_num) {
1294
            /* first block must define rematrixing (rematstr) */
1295 bb270c08 Diego Biurrun
            put_bits(&s->pb, 1, 1);
1296
1297
            /* dummy rematrixing rematflg(1:4)=0 */
1298 6a988808 Justin Ruggles
            for (rbnd = 0; rbnd < 4; rbnd++)
1299
                put_bits(&s->pb, 1, 0);
1300
        } else {
1301 bb270c08 Diego Biurrun
            /* no matrixing (but should be used in the future) */
1302
            put_bits(&s->pb, 1, 0);
1303 6a988808 Justin Ruggles
        }
1304
    }
1305 de6d9b64 Fabrice Bellard
1306
    /* exponent strategy */
1307 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1308 5901cebe Justin Ruggles
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1309 6a988808 Justin Ruggles
    if (s->lfe_on)
1310 5901cebe Justin Ruggles
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1311 30b68f33 Zdenek Kabelac
1312 6a988808 Justin Ruggles
    /* bandwidth */
1313
    for (ch = 0; ch < s->fbw_channels; ch++) {
1314 5901cebe Justin Ruggles
        if (block->exp_strategy[ch] != EXP_REUSE)
1315 2d2692eb Justin Ruggles
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1316 de6d9b64 Fabrice Bellard
    }
1317 115329f1 Diego Biurrun
1318 de6d9b64 Fabrice Bellard
    /* exponents */
1319 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
1320 5901cebe Justin Ruggles
        if (block->exp_strategy[ch] == EXP_REUSE)
1321 de6d9b64 Fabrice Bellard
            continue;
1322
1323 2d82d9b1 Justin Ruggles
        /* DC exponent */
1324 5901cebe Justin Ruggles
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1325 f94bacc5 Justin Ruggles
1326 2d82d9b1 Justin Ruggles
        /* exponent groups */
1327 5901cebe Justin Ruggles
        for (i = 1; i <= block->num_exp_groups[ch]; i++)
1328
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1329 de6d9b64 Fabrice Bellard
1330 2d82d9b1 Justin Ruggles
        /* gain range info */
1331 bb270c08 Diego Biurrun
        if (ch != s->lfe_channel)
1332 2d82d9b1 Justin Ruggles
            put_bits(&s->pb, 2, 0);
1333 de6d9b64 Fabrice Bellard
    }
1334
1335
    /* bit allocation info */
1336
    baie = (block_num == 0);
1337
    put_bits(&s->pb, 1, baie);
1338
    if (baie) {
1339 5ce21342 Justin Ruggles
        put_bits(&s->pb, 2, s->slow_decay_code);
1340
        put_bits(&s->pb, 2, s->fast_decay_code);
1341
        put_bits(&s->pb, 2, s->slow_gain_code);
1342
        put_bits(&s->pb, 2, s->db_per_bit_code);
1343
        put_bits(&s->pb, 3, s->floor_code);
1344 de6d9b64 Fabrice Bellard
    }
1345
1346
    /* snr offset */
1347 6a988808 Justin Ruggles
    put_bits(&s->pb, 1, baie);
1348 de6d9b64 Fabrice Bellard
    if (baie) {
1349 5ce21342 Justin Ruggles
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1350 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
1351 5ce21342 Justin Ruggles
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1352
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1353 de6d9b64 Fabrice Bellard
        }
1354
    }
1355 115329f1 Diego Biurrun
1356 de6d9b64 Fabrice Bellard
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1357
    put_bits(&s->pb, 1, 0); /* no data to skip */
1358
1359 2d82d9b1 Justin Ruggles
    /* mantissas */
1360 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
1361 de6d9b64 Fabrice Bellard
        int b, q;
1362 6a988808 Justin Ruggles
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1363 5901cebe Justin Ruggles
            q = block->qmant[ch][i];
1364 171bc51c Justin Ruggles
            b = block->bap[ch][i];
1365 6a988808 Justin Ruggles
            switch (b) {
1366
            case 0:                                         break;
1367
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1368
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1369
            case 3:               put_bits(&s->pb,   3, q); break;
1370
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1371
            case 14:              put_bits(&s->pb,  14, q); break;
1372
            case 15:              put_bits(&s->pb,  16, q); break;
1373
            default:              put_bits(&s->pb, b-1, q); break;
1374 de6d9b64 Fabrice Bellard
            }
1375
        }
1376
    }
1377
}
1378
1379 2f8ae522 Justin Ruggles
1380 c36ce0f8 Justin Ruggles
/** CRC-16 Polynomial */
1381 de6d9b64 Fabrice Bellard
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1382
1383 2f8ae522 Justin Ruggles
1384 de6d9b64 Fabrice Bellard
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1385
{
1386
    unsigned int c;
1387
1388
    c = 0;
1389
    while (a) {
1390
        if (a & 1)
1391
            c ^= b;
1392
        a = a >> 1;
1393
        b = b << 1;
1394
        if (b & (1 << 16))
1395
            b ^= poly;
1396
    }
1397
    return c;
1398
}
1399
1400 2f8ae522 Justin Ruggles
1401 de6d9b64 Fabrice Bellard
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1402
{
1403
    unsigned int r;
1404
    r = 1;
1405
    while (n) {
1406
        if (n & 1)
1407
            r = mul_poly(r, a, poly);
1408
        a = mul_poly(a, a, poly);
1409
        n >>= 1;
1410
    }
1411
    return r;
1412
}
1413
1414 2f8ae522 Justin Ruggles
1415 c36ce0f8 Justin Ruggles
/**
1416
 * Fill the end of the frame with 0's and compute the two CRCs.
1417
 */
1418 1971ab6e Justin Ruggles
static void output_frame_end(AC3EncodeContext *s)
1419 de6d9b64 Fabrice Bellard
{
1420 eed00252 Justin Ruggles
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1421 0c1a9eda Zdenek Kabelac
    uint8_t *frame;
1422 de6d9b64 Fabrice Bellard
1423 2d82d9b1 Justin Ruggles
    frame_size    = s->frame_size;
1424
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1425
1426
    /* pad the remainder of the frame with zeros */
1427 de6d9b64 Fabrice Bellard
    flush_put_bits(&s->pb);
1428
    frame = s->pb.buf;
1429 427e2293 Justin Ruggles
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1430 eed00252 Justin Ruggles
    assert(pad_bytes >= 0);
1431
    if (pad_bytes > 0)
1432
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1433 115329f1 Diego Biurrun
1434 2d82d9b1 Justin Ruggles
    /* compute crc1 */
1435
    /* this is not so easy because it is at the beginning of the data... */
1436 8fc0162a Måns Rullgård
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1437 427e2293 Justin Ruggles
                             frame + 4, frame_size_58 - 4));
1438 de6d9b64 Fabrice Bellard
    /* XXX: could precompute crc_inv */
1439 427e2293 Justin Ruggles
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1440 6a988808 Justin Ruggles
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1441
    AV_WB16(frame + 2, crc1);
1442 115329f1 Diego Biurrun
1443 2d82d9b1 Justin Ruggles
    /* compute crc2 */
1444 8fc0162a Måns Rullgård
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1445 427e2293 Justin Ruggles
                             frame + frame_size_58,
1446
                             frame_size - frame_size_58 - 2));
1447
    AV_WB16(frame + frame_size - 2, crc2);
1448 de6d9b64 Fabrice Bellard
}
1449
1450 2f8ae522 Justin Ruggles
1451 c36ce0f8 Justin Ruggles
/**
1452 67d979fe Justin Ruggles
 * Write the frame to the output bitstream.
1453
 */
1454
static void output_frame(AC3EncodeContext *s,
1455 266d24be Justin Ruggles
                         unsigned char *frame)
1456 67d979fe Justin Ruggles
{
1457
    int blk;
1458
1459
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1460
1461
    output_frame_header(s);
1462
1463 2d82d9b1 Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1464 266d24be Justin Ruggles
        output_audio_block(s, blk);
1465 67d979fe Justin Ruggles
1466
    output_frame_end(s);
1467
}
1468
1469
1470
/**
1471 c36ce0f8 Justin Ruggles
 * Encode a single AC-3 frame.
1472
 */
1473 a0a9204e Justin Ruggles
static int ac3_encode_frame(AVCodecContext *avctx,
1474 6107fa87 Fabrice Bellard
                            unsigned char *frame, int buf_size, void *data)
1475 de6d9b64 Fabrice Bellard
{
1476
    AC3EncodeContext *s = avctx->priv_data;
1477 edac49da Reimar Döffinger
    const int16_t *samples = data;
1478 dc0bc0f8 Justin Ruggles
    int ret;
1479 de6d9b64 Fabrice Bellard
1480 160d85f5 Justin Ruggles
    if (s->bit_alloc.sr_code == 1)
1481
        adjust_frame_size(s);
1482
1483 266d24be Justin Ruggles
    deinterleave_input_samples(s, samples);
1484 12ed6226 Justin Ruggles
1485 266d24be Justin Ruggles
    apply_mdct(s);
1486 115329f1 Diego Biurrun
1487 266d24be Justin Ruggles
    process_exponents(s);
1488 de6d9b64 Fabrice Bellard
1489 266d24be Justin Ruggles
    ret = compute_bit_allocation(s);
1490 dc0bc0f8 Justin Ruggles
    if (ret) {
1491
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1492
        return ret;
1493
    }
1494 084f5c5a Justin Ruggles
1495 266d24be Justin Ruggles
    quantize_mantissas(s);
1496 b6a1e523 Justin Ruggles
1497 266d24be Justin Ruggles
    output_frame(s, frame);
1498 1971ab6e Justin Ruggles
1499 427e2293 Justin Ruggles
    return s->frame_size;
1500 de6d9b64 Fabrice Bellard
}
1501
1502 2f8ae522 Justin Ruggles
1503 c36ce0f8 Justin Ruggles
/**
1504
 * Finalize encoding and free any memory allocated by the encoder.
1505
 */
1506 a0a9204e Justin Ruggles
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1507 492cd3a9 Michael Niedermayer
{
1508 e8d21fba Justin Ruggles
    int blk, ch;
1509 171bc51c Justin Ruggles
    AC3EncodeContext *s = avctx->priv_data;
1510
1511 e8d21fba Justin Ruggles
    for (ch = 0; ch < s->channels; ch++)
1512
        av_freep(&s->planar_samples[ch]);
1513
    av_freep(&s->planar_samples);
1514 171bc51c Justin Ruggles
    av_freep(&s->bap_buffer);
1515
    av_freep(&s->bap1_buffer);
1516 b6f6204d Justin Ruggles
    av_freep(&s->mdct_coef_buffer);
1517
    av_freep(&s->exp_buffer);
1518
    av_freep(&s->grouped_exp_buffer);
1519
    av_freep(&s->psd_buffer);
1520
    av_freep(&s->band_psd_buffer);
1521
    av_freep(&s->mask_buffer);
1522
    av_freep(&s->qmant_buffer);
1523 171bc51c Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1524
        AC3Block *block = &s->blocks[blk];
1525
        av_freep(&block->bap);
1526 b6f6204d Justin Ruggles
        av_freep(&block->mdct_coef);
1527
        av_freep(&block->exp);
1528
        av_freep(&block->grouped_exp);
1529
        av_freep(&block->psd);
1530
        av_freep(&block->band_psd);
1531
        av_freep(&block->mask);
1532
        av_freep(&block->qmant);
1533 171bc51c Justin Ruggles
    }
1534
1535 c41ac4f8 Justin Ruggles
    mdct_end(&s->mdct);
1536
1537 492cd3a9 Michael Niedermayer
    av_freep(&avctx->coded_frame);
1538 ef9f7306 Måns Rullgård
    return 0;
1539 492cd3a9 Michael Niedermayer
}
1540
1541 2f8ae522 Justin Ruggles
1542 c36ce0f8 Justin Ruggles
/**
1543
 * Set channel information during initialization.
1544
 */
1545 e77fd066 Justin Ruggles
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1546
                                    int64_t *channel_layout)
1547
{
1548
    int ch_layout;
1549
1550
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1551 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1552 e77fd066 Justin Ruggles
    if ((uint64_t)*channel_layout > 0x7FF)
1553 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1554 e77fd066 Justin Ruggles
    ch_layout = *channel_layout;
1555
    if (!ch_layout)
1556
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1557
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1558 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1559 e77fd066 Justin Ruggles
1560
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1561
    s->channels     = channels;
1562
    s->fbw_channels = channels - s->lfe_on;
1563
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1564
    if (s->lfe_on)
1565
        ch_layout -= AV_CH_LOW_FREQUENCY;
1566
1567
    switch (ch_layout) {
1568
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1569
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1570
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1571
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1572
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1573
    case AV_CH_LAYOUT_QUAD:
1574
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1575
    case AV_CH_LAYOUT_5POINT0:
1576
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1577
    default:
1578 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1579 e77fd066 Justin Ruggles
    }
1580
1581
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1582
    *channel_layout = ch_layout;
1583
    if (s->lfe_on)
1584
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1585
1586
    return 0;
1587
}
1588
1589 2f8ae522 Justin Ruggles
1590 8f60f70d Justin Ruggles
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1591 e77fd066 Justin Ruggles
{
1592 ddf63d37 Justin Ruggles
    int i, ret;
1593 e77fd066 Justin Ruggles
1594 e0685bc9 Justin Ruggles
    /* validate channel layout */
1595 e77fd066 Justin Ruggles
    if (!avctx->channel_layout) {
1596
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1597
                                      "encoder will guess the layout, but it "
1598
                                      "might be incorrect.\n");
1599
    }
1600 ddf63d37 Justin Ruggles
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1601
    if (ret) {
1602 e77fd066 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1603 ddf63d37 Justin Ruggles
        return ret;
1604 e77fd066 Justin Ruggles
    }
1605
1606 e0685bc9 Justin Ruggles
    /* validate sample rate */
1607 99ca4f73 Justin Ruggles
    for (i = 0; i < 9; i++) {
1608
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1609
            break;
1610 e77fd066 Justin Ruggles
    }
1611 99ca4f73 Justin Ruggles
    if (i == 9) {
1612 ddf63d37 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1613
        return AVERROR(EINVAL);
1614 99ca4f73 Justin Ruggles
    }
1615 1607db0a Justin Ruggles
    s->sample_rate        = avctx->sample_rate;
1616 99ca4f73 Justin Ruggles
    s->bit_alloc.sr_shift = i % 3;
1617
    s->bit_alloc.sr_code  = i / 3;
1618 e77fd066 Justin Ruggles
1619 e0685bc9 Justin Ruggles
    /* validate bit rate */
1620 e77fd066 Justin Ruggles
    for (i = 0; i < 19; i++) {
1621 1607db0a Justin Ruggles
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1622 e77fd066 Justin Ruggles
            break;
1623
    }
1624 ddf63d37 Justin Ruggles
    if (i == 19) {
1625
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1626
        return AVERROR(EINVAL);
1627
    }
1628 1607db0a Justin Ruggles
    s->bit_rate        = avctx->bit_rate;
1629 e77fd066 Justin Ruggles
    s->frame_size_code = i << 1;
1630 8f60f70d Justin Ruggles
1631
    return 0;
1632
}
1633
1634
1635
/**
1636 282255bb Justin Ruggles
 * Set bandwidth for all channels.
1637
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1638
 * default value will be used.
1639
 */
1640
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1641
{
1642
    int ch, bw_code;
1643
1644
    if (cutoff) {
1645
        /* calculate bandwidth based on user-specified cutoff frequency */
1646
        int fbw_coeffs;
1647
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1648
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1649
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1650
    } else {
1651
        /* use default bandwidth setting */
1652
        /* XXX: should compute the bandwidth according to the frame
1653
           size, so that we avoid annoying high frequency artifacts */
1654
        bw_code = 50;
1655
    }
1656
1657
    /* set number of coefficients for each channel */
1658
    for (ch = 0; ch < s->fbw_channels; ch++) {
1659
        s->bandwidth_code[ch] = bw_code;
1660
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1661
    }
1662
    if (s->lfe_on)
1663
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1664
}
1665
1666
1667 171bc51c Justin Ruggles
static av_cold int allocate_buffers(AVCodecContext *avctx)
1668
{
1669 e8d21fba Justin Ruggles
    int blk, ch;
1670 171bc51c Justin Ruggles
    AC3EncodeContext *s = avctx->priv_data;
1671
1672 e8d21fba Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1673
                     alloc_fail);
1674
    for (ch = 0; ch < s->channels; ch++) {
1675
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1676
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1677
                          alloc_fail);
1678
    }
1679 171bc51c Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1680
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1681
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1682
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1683 b6f6204d Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1684
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1685
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1686
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1687
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1688
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1689
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1690
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1691
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1692
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1693
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1694
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1695
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1696
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1697 171bc51c Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1698
        AC3Block *block = &s->blocks[blk];
1699
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1700
                         alloc_fail);
1701 b6f6204d Justin Ruggles
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1702
                          alloc_fail);
1703
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1704
                          alloc_fail);
1705
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1706
                          alloc_fail);
1707
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1708
                          alloc_fail);
1709
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1710
                          alloc_fail);
1711
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1712
                          alloc_fail);
1713
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1714
                          alloc_fail);
1715
1716
        for (ch = 0; ch < s->channels; ch++) {
1717
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1718
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1719
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1720
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1721
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1722
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1723
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1724
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1725
        }
1726 171bc51c Justin Ruggles
    }
1727
1728
    return 0;
1729
alloc_fail:
1730
    return AVERROR(ENOMEM);
1731
}
1732
1733
1734 282255bb Justin Ruggles
/**
1735 8f60f70d Justin Ruggles
 * Initialize the encoder.
1736
 */
1737
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1738
{
1739
    AC3EncodeContext *s = avctx->priv_data;
1740 282255bb Justin Ruggles
    int ret;
1741 8f60f70d Justin Ruggles
1742
    avctx->frame_size = AC3_FRAME_SIZE;
1743
1744
    ac3_common_init();
1745
1746
    ret = validate_options(avctx, s);
1747
    if (ret)
1748
        return ret;
1749
1750 e35c984a Justin Ruggles
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1751
    s->bitstream_mode = 0; /* complete main audio service */
1752
1753 427e2293 Justin Ruggles
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1754 e77fd066 Justin Ruggles
    s->bits_written    = 0;
1755
    s->samples_written = 0;
1756
    s->frame_size      = s->frame_size_min;
1757
1758 282255bb Justin Ruggles
    set_bandwidth(s, avctx->cutoff);
1759 e77fd066 Justin Ruggles
1760 793bbf95 Justin Ruggles
    bit_alloc_init(s);
1761 e77fd066 Justin Ruggles
1762 c41ac4f8 Justin Ruggles
    s->mdct.avctx = avctx;
1763
    ret = mdct_init(&s->mdct, 9);
1764 7786c384 Justin Ruggles
    if (ret)
1765 89bedc4d Justin Ruggles
        goto init_fail;
1766 e77fd066 Justin Ruggles
1767 171bc51c Justin Ruggles
    ret = allocate_buffers(avctx);
1768 7786c384 Justin Ruggles
    if (ret)
1769 89bedc4d Justin Ruggles
        goto init_fail;
1770 171bc51c Justin Ruggles
1771 e77fd066 Justin Ruggles
    avctx->coded_frame= avcodec_alloc_frame();
1772
1773 8846ee54 Justin Ruggles
    dsputil_init(&s->dsp, avctx);
1774
1775 e77fd066 Justin Ruggles
    return 0;
1776 89bedc4d Justin Ruggles
init_fail:
1777
    ac3_encode_close(avctx);
1778
    return ret;
1779 e77fd066 Justin Ruggles
}
1780
1781 2f8ae522 Justin Ruggles
1782 228315bb Justin Ruggles
#ifdef TEST
1783 de6d9b64 Fabrice Bellard
/*************************************************************************/
1784
/* TEST */
1785
1786 228315bb Justin Ruggles
#include "libavutil/lfg.h"
1787 de6d9b64 Fabrice Bellard
1788 228315bb Justin Ruggles
#define FN (MDCT_SAMPLES/4)
1789
1790 2f8ae522 Justin Ruggles
1791 228315bb Justin Ruggles
static void fft_test(AVLFG *lfg)
1792 de6d9b64 Fabrice Bellard
{
1793
    IComplex in[FN], in1[FN];
1794
    int k, n, i;
1795
    float sum_re, sum_im, a;
1796
1797 6a988808 Justin Ruggles
    for (i = 0; i < FN; i++) {
1798 228315bb Justin Ruggles
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1799
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1800 6a988808 Justin Ruggles
        in1[i]   = in[i];
1801 de6d9b64 Fabrice Bellard
    }
1802
    fft(in, 7);
1803
1804
    /* do it by hand */
1805 6a988808 Justin Ruggles
    for (k = 0; k < FN; k++) {
1806 de6d9b64 Fabrice Bellard
        sum_re = 0;
1807
        sum_im = 0;
1808 6a988808 Justin Ruggles
        for (n = 0; n < FN; n++) {
1809 de6d9b64 Fabrice Bellard
            a = -2 * M_PI * (n * k) / FN;
1810
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1811
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1812
        }
1813 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1814 115329f1 Diego Biurrun
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1815 de6d9b64 Fabrice Bellard
    }
1816
}
1817
1818 2f8ae522 Justin Ruggles
1819 228315bb Justin Ruggles
static void mdct_test(AVLFG *lfg)
1820 de6d9b64 Fabrice Bellard
{
1821 228315bb Justin Ruggles
    int16_t input[MDCT_SAMPLES];
1822
    int32_t output[AC3_MAX_COEFS];
1823
    float input1[MDCT_SAMPLES];
1824
    float output1[AC3_MAX_COEFS];
1825 de6d9b64 Fabrice Bellard
    float s, a, err, e, emax;
1826
    int i, k, n;
1827
1828 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES; i++) {
1829
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1830 de6d9b64 Fabrice Bellard
        input1[i] = input[i];
1831
    }
1832
1833
    mdct512(output, input);
1834 115329f1 Diego Biurrun
1835 de6d9b64 Fabrice Bellard
    /* do it by hand */
1836 6a988808 Justin Ruggles
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1837 de6d9b64 Fabrice Bellard
        s = 0;
1838 6a988808 Justin Ruggles
        for (n = 0; n < MDCT_SAMPLES; n++) {
1839 228315bb Justin Ruggles
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1840 de6d9b64 Fabrice Bellard
            s += input1[n] * cos(a);
1841
        }
1842 228315bb Justin Ruggles
        output1[k] = -2 * s / MDCT_SAMPLES;
1843 de6d9b64 Fabrice Bellard
    }
1844 115329f1 Diego Biurrun
1845 6a988808 Justin Ruggles
    err  = 0;
1846 de6d9b64 Fabrice Bellard
    emax = 0;
1847 6a988808 Justin Ruggles
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1848 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1849 de6d9b64 Fabrice Bellard
        e = output[i] - output1[i];
1850
        if (e > emax)
1851
            emax = e;
1852
        err += e * e;
1853
    }
1854 228315bb Justin Ruggles
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1855 de6d9b64 Fabrice Bellard
}
1856
1857 2f8ae522 Justin Ruggles
1858 228315bb Justin Ruggles
int main(void)
1859 de6d9b64 Fabrice Bellard
{
1860 228315bb Justin Ruggles
    AVLFG lfg;
1861 115329f1 Diego Biurrun
1862 228315bb Justin Ruggles
    av_log_set_level(AV_LOG_DEBUG);
1863
    mdct_init(9);
1864 de6d9b64 Fabrice Bellard
1865 228315bb Justin Ruggles
    fft_test(&lfg);
1866
    mdct_test(&lfg);
1867 de6d9b64 Fabrice Bellard
1868 228315bb Justin Ruggles
    return 0;
1869 de6d9b64 Fabrice Bellard
}
1870 228315bb Justin Ruggles
#endif /* TEST */
1871 de6d9b64 Fabrice Bellard
1872 2f8ae522 Justin Ruggles
1873 de6d9b64 Fabrice Bellard
AVCodec ac3_encoder = {
1874
    "ac3",
1875 72415b2a Stefano Sabatini
    AVMEDIA_TYPE_AUDIO,
1876 de6d9b64 Fabrice Bellard
    CODEC_ID_AC3,
1877
    sizeof(AC3EncodeContext),
1878 a0a9204e Justin Ruggles
    ac3_encode_init,
1879
    ac3_encode_frame,
1880
    ac3_encode_close,
1881 de6d9b64 Fabrice Bellard
    NULL,
1882 5d6e4c16 Stefano Sabatini
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1883 2988c93d Justin Ruggles
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1884 b5f09d31 Reimar Döffinger
    .channel_layouts = (const int64_t[]){
1885 63e8d976 Stefano Sabatini
        AV_CH_LAYOUT_MONO,
1886
        AV_CH_LAYOUT_STEREO,
1887
        AV_CH_LAYOUT_2_1,
1888
        AV_CH_LAYOUT_SURROUND,
1889
        AV_CH_LAYOUT_2_2,
1890
        AV_CH_LAYOUT_QUAD,
1891
        AV_CH_LAYOUT_4POINT0,
1892
        AV_CH_LAYOUT_5POINT0,
1893
        AV_CH_LAYOUT_5POINT0_BACK,
1894
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1895
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1896
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1897
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1898
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1899
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1900
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1901
        AV_CH_LAYOUT_5POINT1,
1902
        AV_CH_LAYOUT_5POINT1_BACK,
1903 120b4557 Justin Ruggles
        0 },
1904 de6d9b64 Fabrice Bellard
};