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