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