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