]> git.sesse.net Git - ffmpeg/blob - libavcodec/dcaenc.c
avformat/mp3dec: improve junk skipping heuristic
[ffmpeg] / libavcodec / dcaenc.c
1 /*
2  * DCA encoder
3  * Copyright (C) 2008-2012 Alexander E. Patrakov
4  *               2010 Benjamin Larsson
5  *               2011 Xiang Wang
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/channel_layout.h"
26 #include "libavutil/common.h"
27 #include "avcodec.h"
28 #include "dca.h"
29 #include "dcadata.h"
30 #include "dcaenc.h"
31 #include "internal.h"
32 #include "mathops.h"
33 #include "put_bits.h"
34
35 #define MAX_CHANNELS 6
36 #define DCA_MAX_FRAME_SIZE 16384
37 #define DCA_HEADER_SIZE 13
38 #define DCA_LFE_SAMPLES 8
39
40 #define DCAENC_SUBBANDS 32
41 #define SUBFRAMES 1
42 #define SUBSUBFRAMES 2
43 #define SUBBAND_SAMPLES (SUBFRAMES * SUBSUBFRAMES * 8)
44 #define AUBANDS 25
45
46 typedef struct DCAEncContext {
47     PutBitContext pb;
48     int frame_size;
49     int frame_bits;
50     int fullband_channels;
51     int channels;
52     int lfe_channel;
53     int samplerate_index;
54     int bitrate_index;
55     int channel_config;
56     const int32_t *band_interpolation;
57     const int32_t *band_spectrum;
58     int lfe_scale_factor;
59     softfloat lfe_quant;
60     int32_t lfe_peak_cb;
61     const int8_t *channel_order_tab;  ///< channel reordering table, lfe and non lfe
62
63     int32_t history[512][MAX_CHANNELS]; /* This is a circular buffer */
64     int32_t subband[SUBBAND_SAMPLES][DCAENC_SUBBANDS][MAX_CHANNELS];
65     int32_t quantized[SUBBAND_SAMPLES][DCAENC_SUBBANDS][MAX_CHANNELS];
66     int32_t peak_cb[DCAENC_SUBBANDS][MAX_CHANNELS];
67     int32_t downsampled_lfe[DCA_LFE_SAMPLES];
68     int32_t masking_curve_cb[SUBSUBFRAMES][256];
69     int abits[DCAENC_SUBBANDS][MAX_CHANNELS];
70     int scale_factor[DCAENC_SUBBANDS][MAX_CHANNELS];
71     softfloat quant[DCAENC_SUBBANDS][MAX_CHANNELS];
72     int32_t eff_masking_curve_cb[256];
73     int32_t band_masking_cb[32];
74     int32_t worst_quantization_noise;
75     int32_t worst_noise_ever;
76     int consumed_bits;
77 } DCAEncContext;
78
79 static int32_t cos_table[2048];
80 static int32_t band_interpolation[2][512];
81 static int32_t band_spectrum[2][8];
82 static int32_t auf[9][AUBANDS][256];
83 static int32_t cb_to_add[256];
84 static int32_t cb_to_level[2048];
85 static int32_t lfe_fir_64i[512];
86
87 /* Transfer function of outer and middle ear, Hz -> dB */
88 static double hom(double f)
89 {
90     double f1 = f / 1000;
91
92     return -3.64 * pow(f1, -0.8)
93            + 6.8 * exp(-0.6 * (f1 - 3.4) * (f1 - 3.4))
94            - 6.0 * exp(-0.15 * (f1 - 8.7) * (f1 - 8.7))
95            - 0.0006 * (f1 * f1) * (f1 * f1);
96 }
97
98 static double gammafilter(int i, double f)
99 {
100     double h = (f - fc[i]) / erb[i];
101
102     h = 1 + h * h;
103     h = 1 / (h * h);
104     return 20 * log10(h);
105 }
106
107 static int encode_init(AVCodecContext *avctx)
108 {
109     DCAEncContext *c = avctx->priv_data;
110     uint64_t layout = avctx->channel_layout;
111     int i, min_frame_bits;
112
113     c->fullband_channels = c->channels = avctx->channels;
114     c->lfe_channel = (avctx->channels == 3 || avctx->channels == 6);
115     c->band_interpolation = band_interpolation[1];
116     c->band_spectrum = band_spectrum[1];
117     c->worst_quantization_noise = -2047;
118     c->worst_noise_ever = -2047;
119
120     if (!layout) {
121         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
122                                       "encoder will guess the layout, but it "
123                                       "might be incorrect.\n");
124         layout = av_get_default_channel_layout(avctx->channels);
125     }
126     switch (layout) {
127     case AV_CH_LAYOUT_MONO:         c->channel_config = 0; break;
128     case AV_CH_LAYOUT_STEREO:       c->channel_config = 2; break;
129     case AV_CH_LAYOUT_2_2:          c->channel_config = 8; break;
130     case AV_CH_LAYOUT_5POINT0:      c->channel_config = 9; break;
131     case AV_CH_LAYOUT_5POINT1:      c->channel_config = 9; break;
132     default:
133         av_log(avctx, AV_LOG_ERROR, "Unsupported channel layout!\n");
134         return AVERROR_PATCHWELCOME;
135     }
136
137     if (c->lfe_channel) {
138         c->fullband_channels--;
139         c->channel_order_tab = ff_dca_channel_reorder_lfe[c->channel_config];
140     } else {
141         c->channel_order_tab = ff_dca_channel_reorder_nolfe[c->channel_config];
142     }
143
144     for (i = 0; i < 9; i++) {
145         if (sample_rates[i] == avctx->sample_rate)
146             break;
147     }
148     if (i == 9)
149         return AVERROR(EINVAL);
150     c->samplerate_index = i;
151
152     if (avctx->bit_rate < 32000 || avctx->bit_rate > 3840000) {
153         av_log(avctx, AV_LOG_ERROR, "Bit rate %"PRId64" not supported.", (int64_t)avctx->bit_rate);
154         return AVERROR(EINVAL);
155     }
156     for (i = 0; ff_dca_bit_rates[i] < avctx->bit_rate; i++)
157         ;
158     c->bitrate_index = i;
159     avctx->bit_rate = ff_dca_bit_rates[i];
160     c->frame_bits = FFALIGN((avctx->bit_rate * 512 + avctx->sample_rate - 1) / avctx->sample_rate, 32);
161     min_frame_bits = 132 + (493 + 28 * 32) * c->fullband_channels + c->lfe_channel * 72;
162     if (c->frame_bits < min_frame_bits || c->frame_bits > (DCA_MAX_FRAME_SIZE << 3))
163         return AVERROR(EINVAL);
164
165     c->frame_size = (c->frame_bits + 7) / 8;
166
167     avctx->frame_size = 32 * SUBBAND_SAMPLES;
168
169     if (!cos_table[0]) {
170         int j, k;
171
172         for (i = 0; i < 2048; i++) {
173             cos_table[i]   = (int32_t)(0x7fffffff * cos(M_PI * i / 1024));
174             cb_to_level[i] = (int32_t)(0x7fffffff * pow(10, -0.005 * i));
175         }
176
177         for (k = 0; k < 32; k++) {
178             for (j = 0; j < 8; j++) {
179                 lfe_fir_64i[64 * j + k] = (int32_t)(0xffffff800000ULL * ff_dca_lfe_fir_64[8 * k + j]);
180                 lfe_fir_64i[64 * (7-j) + (63 - k)] = (int32_t)(0xffffff800000ULL * ff_dca_lfe_fir_64[8 * k + j]);
181             }
182         }
183
184         for (i = 0; i < 512; i++) {
185             band_interpolation[0][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_perfect[i]);
186             band_interpolation[1][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_nonperfect[i]);
187         }
188
189         for (i = 0; i < 9; i++) {
190             for (j = 0; j < AUBANDS; j++) {
191                 for (k = 0; k < 256; k++) {
192                     double freq = sample_rates[i] * (k + 0.5) / 512;
193
194                     auf[i][j][k] = (int32_t)(10 * (hom(freq) + gammafilter(j, freq)));
195                 }
196             }
197         }
198
199         for (i = 0; i < 256; i++) {
200             double add = 1 + pow(10, -0.01 * i);
201             cb_to_add[i] = (int32_t)(100 * log10(add));
202         }
203         for (j = 0; j < 8; j++) {
204             double accum = 0;
205             for (i = 0; i < 512; i++) {
206                 double reconst = ff_dca_fir_32bands_perfect[i] * ((i & 64) ? (-1) : 1);
207                 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
208             }
209             band_spectrum[0][j] = (int32_t)(200 * log10(accum));
210         }
211         for (j = 0; j < 8; j++) {
212             double accum = 0;
213             for (i = 0; i < 512; i++) {
214                 double reconst = ff_dca_fir_32bands_nonperfect[i] * ((i & 64) ? (-1) : 1);
215                 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
216             }
217             band_spectrum[1][j] = (int32_t)(200 * log10(accum));
218         }
219     }
220     return 0;
221 }
222
223 static inline int32_t cos_t(int x)
224 {
225     return cos_table[x & 2047];
226 }
227
228 static inline int32_t sin_t(int x)
229 {
230     return cos_t(x - 512);
231 }
232
233 static inline int32_t half32(int32_t a)
234 {
235     return (a + 1) >> 1;
236 }
237
238 static inline int32_t mul32(int32_t a, int32_t b)
239 {
240     int64_t r = (int64_t)a * b + 0x80000000ULL;
241     return r >> 32;
242 }
243
244 static void subband_transform(DCAEncContext *c, const int32_t *input)
245 {
246     int ch, subs, i, k, j;
247
248     for (ch = 0; ch < c->fullband_channels; ch++) {
249         /* History is copied because it is also needed for PSY */
250         int32_t hist[512];
251         int hist_start = 0;
252         const int chi = c->channel_order_tab[ch];
253
254         for (i = 0; i < 512; i++)
255             hist[i] = c->history[i][ch];
256
257         for (subs = 0; subs < SUBBAND_SAMPLES; subs++) {
258             int32_t accum[64];
259             int32_t resp;
260             int band;
261
262             /* Calculate the convolutions at once */
263             for (i = 0; i < 64; i++)
264                 accum[i] = 0;
265
266             for (k = 0, i = hist_start, j = 0;
267                     i < 512; k = (k + 1) & 63, i++, j++)
268                 accum[k] += mul32(hist[i], c->band_interpolation[j]);
269             for (i = 0; i < hist_start; k = (k + 1) & 63, i++, j++)
270                 accum[k] += mul32(hist[i], c->band_interpolation[j]);
271
272             for (k = 16; k < 32; k++)
273                 accum[k] = accum[k] - accum[31 - k];
274             for (k = 32; k < 48; k++)
275                 accum[k] = accum[k] + accum[95 - k];
276
277             for (band = 0; band < 32; band++) {
278                 resp = 0;
279                 for (i = 16; i < 48; i++) {
280                     int s = (2 * band + 1) * (2 * (i + 16) + 1);
281                     resp += mul32(accum[i], cos_t(s << 3)) >> 3;
282                 }
283
284                 c->subband[subs][band][ch] = ((band + 1) & 2) ? -resp : resp;
285             }
286
287             /* Copy in 32 new samples from input */
288             for (i = 0; i < 32; i++)
289                 hist[i + hist_start] = input[(subs * 32 + i) * c->channels + chi];
290             hist_start = (hist_start + 32) & 511;
291         }
292     }
293 }
294
295 static void lfe_downsample(DCAEncContext *c, const int32_t *input)
296 {
297     /* FIXME: make 128x LFE downsampling possible */
298     const int lfech = ff_dca_lfe_index[c->channel_config];
299     int i, j, lfes;
300     int32_t hist[512];
301     int32_t accum;
302     int hist_start = 0;
303
304     for (i = 0; i < 512; i++)
305         hist[i] = c->history[i][c->channels - 1];
306
307     for (lfes = 0; lfes < DCA_LFE_SAMPLES; lfes++) {
308         /* Calculate the convolution */
309         accum = 0;
310
311         for (i = hist_start, j = 0; i < 512; i++, j++)
312             accum += mul32(hist[i], lfe_fir_64i[j]);
313         for (i = 0; i < hist_start; i++, j++)
314             accum += mul32(hist[i], lfe_fir_64i[j]);
315
316         c->downsampled_lfe[lfes] = accum;
317
318         /* Copy in 64 new samples from input */
319         for (i = 0; i < 64; i++)
320             hist[i + hist_start] = input[(lfes * 64 + i) * c->channels + lfech];
321
322         hist_start = (hist_start + 64) & 511;
323     }
324 }
325
326 typedef struct {
327     int32_t re;
328     int32_t im;
329 } cplx32;
330
331 static void fft(const int32_t in[2 * 256], cplx32 out[256])
332 {
333     cplx32 buf[256], rin[256], rout[256];
334     int i, j, k, l;
335
336     /* do two transforms in parallel */
337     for (i = 0; i < 256; i++) {
338         /* Apply the Hann window */
339         rin[i].re = mul32(in[2 * i], 0x3fffffff - (cos_t(8 * i + 2) >> 1));
340         rin[i].im = mul32(in[2 * i + 1], 0x3fffffff - (cos_t(8 * i + 6) >> 1));
341     }
342     /* pre-rotation */
343     for (i = 0; i < 256; i++) {
344         buf[i].re = mul32(cos_t(4 * i + 2), rin[i].re)
345                   - mul32(sin_t(4 * i + 2), rin[i].im);
346         buf[i].im = mul32(cos_t(4 * i + 2), rin[i].im)
347                   + mul32(sin_t(4 * i + 2), rin[i].re);
348     }
349
350     for (j = 256, l = 1; j != 1; j >>= 1, l <<= 1) {
351         for (k = 0; k < 256; k += j) {
352             for (i = k; i < k + j / 2; i++) {
353                 cplx32 sum, diff;
354                 int t = 8 * l * i;
355
356                 sum.re = buf[i].re + buf[i + j / 2].re;
357                 sum.im = buf[i].im + buf[i + j / 2].im;
358
359                 diff.re = buf[i].re - buf[i + j / 2].re;
360                 diff.im = buf[i].im - buf[i + j / 2].im;
361
362                 buf[i].re = half32(sum.re);
363                 buf[i].im = half32(sum.im);
364
365                 buf[i + j / 2].re = mul32(diff.re, cos_t(t))
366                                   - mul32(diff.im, sin_t(t));
367                 buf[i + j / 2].im = mul32(diff.im, cos_t(t))
368                                   + mul32(diff.re, sin_t(t));
369             }
370         }
371     }
372     /* post-rotation */
373     for (i = 0; i < 256; i++) {
374         int b = ff_reverse[i];
375         rout[i].re = mul32(buf[b].re, cos_t(4 * i))
376                    - mul32(buf[b].im, sin_t(4 * i));
377         rout[i].im = mul32(buf[b].im, cos_t(4 * i))
378                    + mul32(buf[b].re, sin_t(4 * i));
379     }
380     for (i = 0; i < 256; i++) {
381         /* separate the results of the two transforms */
382         cplx32 o1, o2;
383
384         o1.re =  rout[i].re - rout[255 - i].re;
385         o1.im =  rout[i].im + rout[255 - i].im;
386
387         o2.re =  rout[i].im - rout[255 - i].im;
388         o2.im = -rout[i].re - rout[255 - i].re;
389
390         /* combine them into one long transform */
391         out[i].re = mul32( o1.re + o2.re, cos_t(2 * i + 1))
392                   + mul32( o1.im - o2.im, sin_t(2 * i + 1));
393         out[i].im = mul32( o1.im + o2.im, cos_t(2 * i + 1))
394                   + mul32(-o1.re + o2.re, sin_t(2 * i + 1));
395     }
396 }
397
398 static int32_t get_cb(int32_t in)
399 {
400     int i, res;
401
402     res = 0;
403     if (in < 0)
404         in = -in;
405     for (i = 1024; i > 0; i >>= 1) {
406         if (cb_to_level[i + res] >= in)
407             res += i;
408     }
409     return -res;
410 }
411
412 static int32_t add_cb(int32_t a, int32_t b)
413 {
414     if (a < b)
415         FFSWAP(int32_t, a, b);
416
417     if (a - b >= 256)
418         return a;
419     return a + cb_to_add[a - b];
420 }
421
422 static void adjust_jnd(int samplerate_index,
423                        const int32_t in[512], int32_t out_cb[256])
424 {
425     int32_t power[256];
426     cplx32 out[256];
427     int32_t out_cb_unnorm[256];
428     int32_t denom;
429     const int32_t ca_cb = -1114;
430     const int32_t cs_cb = 928;
431     int i, j;
432
433     fft(in, out);
434
435     for (j = 0; j < 256; j++) {
436         power[j] = add_cb(get_cb(out[j].re), get_cb(out[j].im));
437         out_cb_unnorm[j] = -2047; /* and can only grow */
438     }
439
440     for (i = 0; i < AUBANDS; i++) {
441         denom = ca_cb; /* and can only grow */
442         for (j = 0; j < 256; j++)
443             denom = add_cb(denom, power[j] + auf[samplerate_index][i][j]);
444         for (j = 0; j < 256; j++)
445             out_cb_unnorm[j] = add_cb(out_cb_unnorm[j],
446                     -denom + auf[samplerate_index][i][j]);
447     }
448
449     for (j = 0; j < 256; j++)
450         out_cb[j] = add_cb(out_cb[j], -out_cb_unnorm[j] - ca_cb - cs_cb);
451 }
452
453 typedef void (*walk_band_t)(DCAEncContext *c, int band1, int band2, int f,
454                             int32_t spectrum1, int32_t spectrum2, int channel,
455                             int32_t * arg);
456
457 static void walk_band_low(DCAEncContext *c, int band, int channel,
458                           walk_band_t walk, int32_t *arg)
459 {
460     int f;
461
462     if (band == 0) {
463         for (f = 0; f < 4; f++)
464             walk(c, 0, 0, f, 0, -2047, channel, arg);
465     } else {
466         for (f = 0; f < 8; f++)
467             walk(c, band, band - 1, 8 * band - 4 + f,
468                     c->band_spectrum[7 - f], c->band_spectrum[f], channel, arg);
469     }
470 }
471
472 static void walk_band_high(DCAEncContext *c, int band, int channel,
473                            walk_band_t walk, int32_t *arg)
474 {
475     int f;
476
477     if (band == 31) {
478         for (f = 0; f < 4; f++)
479             walk(c, 31, 31, 256 - 4 + f, 0, -2047, channel, arg);
480     } else {
481         for (f = 0; f < 8; f++)
482             walk(c, band, band + 1, 8 * band + 4 + f,
483                     c->band_spectrum[f], c->band_spectrum[7 - f], channel, arg);
484     }
485 }
486
487 static void update_band_masking(DCAEncContext *c, int band1, int band2,
488                                 int f, int32_t spectrum1, int32_t spectrum2,
489                                 int channel, int32_t * arg)
490 {
491     int32_t value = c->eff_masking_curve_cb[f] - spectrum1;
492
493     if (value < c->band_masking_cb[band1])
494         c->band_masking_cb[band1] = value;
495 }
496
497 static void calc_masking(DCAEncContext *c, const int32_t *input)
498 {
499     int i, k, band, ch, ssf;
500     int32_t data[512];
501
502     for (i = 0; i < 256; i++)
503         for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
504             c->masking_curve_cb[ssf][i] = -2047;
505
506     for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
507         for (ch = 0; ch < c->fullband_channels; ch++) {
508             const int chi = c->channel_order_tab[ch];
509
510             for (i = 0, k = 128 + 256 * ssf; k < 512; i++, k++)
511                 data[i] = c->history[k][ch];
512             for (k -= 512; i < 512; i++, k++)
513                 data[i] = input[k * c->channels + chi];
514             adjust_jnd(c->samplerate_index, data, c->masking_curve_cb[ssf]);
515         }
516     for (i = 0; i < 256; i++) {
517         int32_t m = 2048;
518
519         for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
520             if (c->masking_curve_cb[ssf][i] < m)
521                 m = c->masking_curve_cb[ssf][i];
522         c->eff_masking_curve_cb[i] = m;
523     }
524
525     for (band = 0; band < 32; band++) {
526         c->band_masking_cb[band] = 2048;
527         walk_band_low(c, band, 0, update_band_masking, NULL);
528         walk_band_high(c, band, 0, update_band_masking, NULL);
529     }
530 }
531
532 static void find_peaks(DCAEncContext *c)
533 {
534     int band, ch;
535
536     for (band = 0; band < 32; band++)
537         for (ch = 0; ch < c->fullband_channels; ch++) {
538             int sample;
539             int32_t m = 0;
540
541             for (sample = 0; sample < SUBBAND_SAMPLES; sample++) {
542                 int32_t s = abs(c->subband[sample][band][ch]);
543                 if (m < s)
544                     m = s;
545             }
546             c->peak_cb[band][ch] = get_cb(m);
547         }
548
549     if (c->lfe_channel) {
550         int sample;
551         int32_t m = 0;
552
553         for (sample = 0; sample < DCA_LFE_SAMPLES; sample++)
554             if (m < abs(c->downsampled_lfe[sample]))
555                 m = abs(c->downsampled_lfe[sample]);
556         c->lfe_peak_cb = get_cb(m);
557     }
558 }
559
560 static const int snr_fudge = 128;
561 #define USED_1ABITS 1
562 #define USED_NABITS 2
563 #define USED_26ABITS 4
564
565 static int init_quantization_noise(DCAEncContext *c, int noise)
566 {
567     int ch, band, ret = 0;
568
569     c->consumed_bits = 132 + 493 * c->fullband_channels;
570     if (c->lfe_channel)
571         c->consumed_bits += 72;
572
573     /* attempt to guess the bit distribution based on the prevoius frame */
574     for (ch = 0; ch < c->fullband_channels; ch++) {
575         for (band = 0; band < 32; band++) {
576             int snr_cb = c->peak_cb[band][ch] - c->band_masking_cb[band] - noise;
577
578             if (snr_cb >= 1312) {
579                 c->abits[band][ch] = 26;
580                 ret |= USED_26ABITS;
581             } else if (snr_cb >= 222) {
582                 c->abits[band][ch] = 8 + mul32(snr_cb - 222, 69000000);
583                 ret |= USED_NABITS;
584             } else if (snr_cb >= 0) {
585                 c->abits[band][ch] = 2 + mul32(snr_cb, 106000000);
586                 ret |= USED_NABITS;
587             } else {
588                 c->abits[band][ch] = 1;
589                 ret |= USED_1ABITS;
590             }
591         }
592     }
593
594     for (band = 0; band < 32; band++)
595         for (ch = 0; ch < c->fullband_channels; ch++) {
596             c->consumed_bits += bit_consumption[c->abits[band][ch]];
597         }
598
599     return ret;
600 }
601
602 static void assign_bits(DCAEncContext *c)
603 {
604     /* Find the bounds where the binary search should work */
605     int low, high, down;
606     int used_abits = 0;
607
608     init_quantization_noise(c, c->worst_quantization_noise);
609     low = high = c->worst_quantization_noise;
610     if (c->consumed_bits > c->frame_bits) {
611         while (c->consumed_bits > c->frame_bits) {
612             av_assert0(used_abits != USED_1ABITS);
613             low = high;
614             high += snr_fudge;
615             used_abits = init_quantization_noise(c, high);
616         }
617     } else {
618         while (c->consumed_bits <= c->frame_bits) {
619             high = low;
620             if (used_abits == USED_26ABITS)
621                 goto out; /* The requested bitrate is too high, pad with zeros */
622             low -= snr_fudge;
623             used_abits = init_quantization_noise(c, low);
624         }
625     }
626
627     /* Now do a binary search between low and high to see what fits */
628     for (down = snr_fudge >> 1; down; down >>= 1) {
629         init_quantization_noise(c, high - down);
630         if (c->consumed_bits <= c->frame_bits)
631             high -= down;
632     }
633     init_quantization_noise(c, high);
634 out:
635     c->worst_quantization_noise = high;
636     if (high > c->worst_noise_ever)
637         c->worst_noise_ever = high;
638 }
639
640 static void shift_history(DCAEncContext *c, const int32_t *input)
641 {
642     int k, ch;
643
644     for (k = 0; k < 512; k++)
645         for (ch = 0; ch < c->channels; ch++) {
646             const int chi = c->channel_order_tab[ch];
647
648             c->history[k][ch] = input[k * c->channels + chi];
649         }
650 }
651
652 static int32_t quantize_value(int32_t value, softfloat quant)
653 {
654     int32_t offset = 1 << (quant.e - 1);
655
656     value = mul32(value, quant.m) + offset;
657     value = value >> quant.e;
658     return value;
659 }
660
661 static int calc_one_scale(int32_t peak_cb, int abits, softfloat *quant)
662 {
663     int32_t peak;
664     int our_nscale, try_remove;
665     softfloat our_quant;
666
667     av_assert0(peak_cb <= 0);
668     av_assert0(peak_cb >= -2047);
669
670     our_nscale = 127;
671     peak = cb_to_level[-peak_cb];
672
673     for (try_remove = 64; try_remove > 0; try_remove >>= 1) {
674         if (scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e <= 17)
675             continue;
676         our_quant.m = mul32(scalefactor_inv[our_nscale - try_remove].m, stepsize_inv[abits].m);
677         our_quant.e = scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e - 17;
678         if ((quant_levels[abits] - 1) / 2 < quantize_value(peak, our_quant))
679             continue;
680         our_nscale -= try_remove;
681     }
682
683     if (our_nscale >= 125)
684         our_nscale = 124;
685
686     quant->m = mul32(scalefactor_inv[our_nscale].m, stepsize_inv[abits].m);
687     quant->e = scalefactor_inv[our_nscale].e + stepsize_inv[abits].e - 17;
688     av_assert0((quant_levels[abits] - 1) / 2 >= quantize_value(peak, *quant));
689
690     return our_nscale;
691 }
692
693 static void calc_scales(DCAEncContext *c)
694 {
695     int band, ch;
696
697     for (band = 0; band < 32; band++)
698         for (ch = 0; ch < c->fullband_channels; ch++)
699             c->scale_factor[band][ch] = calc_one_scale(c->peak_cb[band][ch],
700                                                        c->abits[band][ch],
701                                                        &c->quant[band][ch]);
702
703     if (c->lfe_channel)
704         c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);
705 }
706
707 static void quantize_all(DCAEncContext *c)
708 {
709     int sample, band, ch;
710
711     for (sample = 0; sample < SUBBAND_SAMPLES; sample++)
712         for (band = 0; band < 32; band++)
713             for (ch = 0; ch < c->fullband_channels; ch++)
714                 c->quantized[sample][band][ch] = quantize_value(c->subband[sample][band][ch], c->quant[band][ch]);
715 }
716
717 static void put_frame_header(DCAEncContext *c)
718 {
719     /* SYNC */
720     put_bits(&c->pb, 16, 0x7ffe);
721     put_bits(&c->pb, 16, 0x8001);
722
723     /* Frame type: normal */
724     put_bits(&c->pb, 1, 1);
725
726     /* Deficit sample count: none */
727     put_bits(&c->pb, 5, 31);
728
729     /* CRC is not present */
730     put_bits(&c->pb, 1, 0);
731
732     /* Number of PCM sample blocks */
733     put_bits(&c->pb, 7, SUBBAND_SAMPLES - 1);
734
735     /* Primary frame byte size */
736     put_bits(&c->pb, 14, c->frame_size - 1);
737
738     /* Audio channel arrangement */
739     put_bits(&c->pb, 6, c->channel_config);
740
741     /* Core audio sampling frequency */
742     put_bits(&c->pb, 4, bitstream_sfreq[c->samplerate_index]);
743
744     /* Transmission bit rate */
745     put_bits(&c->pb, 5, c->bitrate_index);
746
747     /* Embedded down mix: disabled */
748     put_bits(&c->pb, 1, 0);
749
750     /* Embedded dynamic range flag: not present */
751     put_bits(&c->pb, 1, 0);
752
753     /* Embedded time stamp flag: not present */
754     put_bits(&c->pb, 1, 0);
755
756     /* Auxiliary data flag: not present */
757     put_bits(&c->pb, 1, 0);
758
759     /* HDCD source: no */
760     put_bits(&c->pb, 1, 0);
761
762     /* Extension audio ID: N/A */
763     put_bits(&c->pb, 3, 0);
764
765     /* Extended audio data: not present */
766     put_bits(&c->pb, 1, 0);
767
768     /* Audio sync word insertion flag: after each sub-frame */
769     put_bits(&c->pb, 1, 0);
770
771     /* Low frequency effects flag: not present or 64x subsampling */
772     put_bits(&c->pb, 2, c->lfe_channel ? 2 : 0);
773
774     /* Predictor history switch flag: on */
775     put_bits(&c->pb, 1, 1);
776
777     /* No CRC */
778     /* Multirate interpolator switch: non-perfect reconstruction */
779     put_bits(&c->pb, 1, 0);
780
781     /* Encoder software revision: 7 */
782     put_bits(&c->pb, 4, 7);
783
784     /* Copy history: 0 */
785     put_bits(&c->pb, 2, 0);
786
787     /* Source PCM resolution: 16 bits, not DTS ES */
788     put_bits(&c->pb, 3, 0);
789
790     /* Front sum/difference coding: no */
791     put_bits(&c->pb, 1, 0);
792
793     /* Surrounds sum/difference coding: no */
794     put_bits(&c->pb, 1, 0);
795
796     /* Dialog normalization: 0 dB */
797     put_bits(&c->pb, 4, 0);
798 }
799
800 static void put_primary_audio_header(DCAEncContext *c)
801 {
802     static const int bitlen[11] = { 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3 };
803     static const int thr[11]    = { 0, 1, 3, 3, 3, 3, 7, 7, 7, 7, 7 };
804
805     int ch, i;
806     /* Number of subframes */
807     put_bits(&c->pb, 4, SUBFRAMES - 1);
808
809     /* Number of primary audio channels */
810     put_bits(&c->pb, 3, c->fullband_channels - 1);
811
812     /* Subband activity count */
813     for (ch = 0; ch < c->fullband_channels; ch++)
814         put_bits(&c->pb, 5, DCAENC_SUBBANDS - 2);
815
816     /* High frequency VQ start subband */
817     for (ch = 0; ch < c->fullband_channels; ch++)
818         put_bits(&c->pb, 5, DCAENC_SUBBANDS - 1);
819
820     /* Joint intensity coding index: 0, 0 */
821     for (ch = 0; ch < c->fullband_channels; ch++)
822         put_bits(&c->pb, 3, 0);
823
824     /* Transient mode codebook: A4, A4 (arbitrary) */
825     for (ch = 0; ch < c->fullband_channels; ch++)
826         put_bits(&c->pb, 2, 0);
827
828     /* Scale factor code book: 7 bit linear, 7-bit sqrt table (for each channel) */
829     for (ch = 0; ch < c->fullband_channels; ch++)
830         put_bits(&c->pb, 3, 6);
831
832     /* Bit allocation quantizer select: linear 5-bit */
833     for (ch = 0; ch < c->fullband_channels; ch++)
834         put_bits(&c->pb, 3, 6);
835
836     /* Quantization index codebook select: dummy data
837        to avoid transmission of scale factor adjustment */
838     for (i = 1; i < 11; i++)
839         for (ch = 0; ch < c->fullband_channels; ch++)
840             put_bits(&c->pb, bitlen[i], thr[i]);
841
842     /* Scale factor adjustment index: not transmitted */
843     /* Audio header CRC check word: not transmitted */
844 }
845
846 static void put_subframe_samples(DCAEncContext *c, int ss, int band, int ch)
847 {
848     if (c->abits[band][ch] <= 7) {
849         int sum, i, j;
850         for (i = 0; i < 8; i += 4) {
851             sum = 0;
852             for (j = 3; j >= 0; j--) {
853                 sum *= quant_levels[c->abits[band][ch]];
854                 sum += c->quantized[ss * 8 + i + j][band][ch];
855                 sum += (quant_levels[c->abits[band][ch]] - 1) / 2;
856             }
857             put_bits(&c->pb, bit_consumption[c->abits[band][ch]] / 4, sum);
858         }
859     } else {
860         int i;
861         for (i = 0; i < 8; i++) {
862             int bits = bit_consumption[c->abits[band][ch]] / 16;
863             put_sbits(&c->pb, bits, c->quantized[ss * 8 + i][band][ch]);
864         }
865     }
866 }
867
868 static void put_subframe(DCAEncContext *c, int subframe)
869 {
870     int i, band, ss, ch;
871
872     /* Subsubframes count */
873     put_bits(&c->pb, 2, SUBSUBFRAMES -1);
874
875     /* Partial subsubframe sample count: dummy */
876     put_bits(&c->pb, 3, 0);
877
878     /* Prediction mode: no ADPCM, in each channel and subband */
879     for (ch = 0; ch < c->fullband_channels; ch++)
880         for (band = 0; band < DCAENC_SUBBANDS; band++)
881             put_bits(&c->pb, 1, 0);
882
883     /* Prediction VQ address: not transmitted */
884     /* Bit allocation index */
885     for (ch = 0; ch < c->fullband_channels; ch++)
886         for (band = 0; band < DCAENC_SUBBANDS; band++)
887             put_bits(&c->pb, 5, c->abits[band][ch]);
888
889     if (SUBSUBFRAMES > 1) {
890         /* Transition mode: none for each channel and subband */
891         for (ch = 0; ch < c->fullband_channels; ch++)
892             for (band = 0; band < DCAENC_SUBBANDS; band++)
893                 put_bits(&c->pb, 1, 0); /* codebook A4 */
894     }
895
896     /* Scale factors */
897     for (ch = 0; ch < c->fullband_channels; ch++)
898         for (band = 0; band < DCAENC_SUBBANDS; band++)
899             put_bits(&c->pb, 7, c->scale_factor[band][ch]);
900
901     /* Joint subband scale factor codebook select: not transmitted */
902     /* Scale factors for joint subband coding: not transmitted */
903     /* Stereo down-mix coefficients: not transmitted */
904     /* Dynamic range coefficient: not transmitted */
905     /* Stde information CRC check word: not transmitted */
906     /* VQ encoded high frequency subbands: not transmitted */
907
908     /* LFE data: 8 samples and scalefactor */
909     if (c->lfe_channel) {
910         for (i = 0; i < DCA_LFE_SAMPLES; i++)
911             put_bits(&c->pb, 8, quantize_value(c->downsampled_lfe[i], c->lfe_quant) & 0xff);
912         put_bits(&c->pb, 8, c->lfe_scale_factor);
913     }
914
915     /* Audio data (subsubframes) */
916     for (ss = 0; ss < SUBSUBFRAMES ; ss++)
917         for (ch = 0; ch < c->fullband_channels; ch++)
918             for (band = 0; band < DCAENC_SUBBANDS; band++)
919                     put_subframe_samples(c, ss, band, ch);
920
921     /* DSYNC */
922     put_bits(&c->pb, 16, 0xffff);
923 }
924
925 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
926                         const AVFrame *frame, int *got_packet_ptr)
927 {
928     DCAEncContext *c = avctx->priv_data;
929     const int32_t *samples;
930     int ret, i;
931
932     if ((ret = ff_alloc_packet2(avctx, avpkt, c->frame_size , 0)) < 0)
933         return ret;
934
935     samples = (const int32_t *)frame->data[0];
936
937     subband_transform(c, samples);
938     if (c->lfe_channel)
939         lfe_downsample(c, samples);
940
941     calc_masking(c, samples);
942     find_peaks(c);
943     assign_bits(c);
944     calc_scales(c);
945     quantize_all(c);
946     shift_history(c, samples);
947
948     init_put_bits(&c->pb, avpkt->data, avpkt->size);
949     put_frame_header(c);
950     put_primary_audio_header(c);
951     for (i = 0; i < SUBFRAMES; i++)
952         put_subframe(c, i);
953
954
955     for (i = put_bits_count(&c->pb); i < 8*c->frame_size; i++)
956         put_bits(&c->pb, 1, 0);
957
958     flush_put_bits(&c->pb);
959
960     avpkt->pts      = frame->pts;
961     avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
962     avpkt->size     = c->frame_size + 1;
963     *got_packet_ptr = 1;
964     return 0;
965 }
966
967 static const AVCodecDefault defaults[] = {
968     { "b",          "1411200" },
969     { NULL },
970 };
971
972 AVCodec ff_dca_encoder = {
973     .name                  = "dca",
974     .long_name             = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
975     .type                  = AVMEDIA_TYPE_AUDIO,
976     .id                    = AV_CODEC_ID_DTS,
977     .priv_data_size        = sizeof(DCAEncContext),
978     .init                  = encode_init,
979     .encode2               = encode_frame,
980     .capabilities          = AV_CODEC_CAP_EXPERIMENTAL,
981     .sample_fmts           = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32,
982                                                             AV_SAMPLE_FMT_NONE },
983     .supported_samplerates = sample_rates,
984     .channel_layouts       = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
985                                                   AV_CH_LAYOUT_STEREO,
986                                                   AV_CH_LAYOUT_2_2,
987                                                   AV_CH_LAYOUT_5POINT0,
988                                                   AV_CH_LAYOUT_5POINT1,
989                                                   0 },
990     .defaults              = defaults,
991 };