]> git.sesse.net Git - ffmpeg/blob - libavcodec/dcaenc.c
dd601ffae0077f2fa0bc2cab589cf09d019e9a7e
[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.", 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_26ABITS 4
660
661 static inline int32_t get_step_size(const DCAEncContext *c, int ch, int band)
662 {
663     int32_t step_size;
664
665     if (c->bitrate_index == 3)
666         step_size = ff_dca_lossless_quant[c->abits[ch][band]];
667     else
668         step_size = ff_dca_lossy_quant[c->abits[ch][band]];
669
670     return step_size;
671 }
672
673 static int calc_one_scale(int32_t peak_cb, int abits, softfloat *quant)
674 {
675     int32_t peak;
676     int our_nscale, try_remove;
677     softfloat our_quant;
678
679     av_assert0(peak_cb <= 0);
680     av_assert0(peak_cb >= -2047);
681
682     our_nscale = 127;
683     peak = cb_to_level[-peak_cb];
684
685     for (try_remove = 64; try_remove > 0; try_remove >>= 1) {
686         if (scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e <= 17)
687             continue;
688         our_quant.m = mul32(scalefactor_inv[our_nscale - try_remove].m, stepsize_inv[abits].m);
689         our_quant.e = scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e - 17;
690         if ((ff_dca_quant_levels[abits] - 1) / 2 < quantize_value(peak, our_quant))
691             continue;
692         our_nscale -= try_remove;
693     }
694
695     if (our_nscale >= 125)
696         our_nscale = 124;
697
698     quant->m = mul32(scalefactor_inv[our_nscale].m, stepsize_inv[abits].m);
699     quant->e = scalefactor_inv[our_nscale].e + stepsize_inv[abits].e - 17;
700     av_assert0((ff_dca_quant_levels[abits] - 1) / 2 >= quantize_value(peak, *quant));
701
702     return our_nscale;
703 }
704
705 static inline void quantize_adpcm_subband(DCAEncContext *c, int ch, int band)
706 {
707     int32_t step_size;
708     int32_t diff_peak_cb = c->diff_peak_cb[ch][band];
709     c->scale_factor[ch][band] = calc_one_scale(diff_peak_cb,
710                                                c->abits[ch][band],
711                                                &c->quant[ch][band]);
712
713     step_size = get_step_size(c, ch, band);
714     ff_dcaadpcm_do_real(c->prediction_mode[ch][band],
715                         c->quant[ch][band], ff_dca_scale_factor_quant7[c->scale_factor[ch][band]], step_size,
716                         c->adpcm_history[ch][band], c->subband[ch][band], c->adpcm_history[ch][band]+4, c->quantized[ch][band],
717                         SUBBAND_SAMPLES, cb_to_level[-diff_peak_cb]);
718 }
719
720 static void quantize_adpcm(DCAEncContext *c)
721 {
722     int band, ch;
723
724     for (ch = 0; ch < c->fullband_channels; ch++)
725         for (band = 0; band < 32; band++)
726             if (c->prediction_mode[ch][band] >= 0)
727                 quantize_adpcm_subband(c, ch, band);
728 }
729
730 static void quantize_pcm(DCAEncContext *c)
731 {
732     int sample, band, ch;
733
734     for (ch = 0; ch < c->fullband_channels; ch++)
735         for (band = 0; band < 32; band++)
736             if (c->prediction_mode[ch][band] == -1)
737                 for (sample = 0; sample < SUBBAND_SAMPLES; sample++)
738                     c->quantized[ch][band][sample] = quantize_value(c->subband[ch][band][sample], c->quant[ch][band]);
739 }
740
741 static void accumulate_huff_bit_consumption(int abits, int32_t *quantized, uint32_t *result)
742 {
743     uint8_t sel, id = abits - 1;
744     for (sel = 0; sel < ff_dca_quant_index_group_size[id]; sel++)
745         result[sel] += ff_dca_vlc_calc_quant_bits(quantized, SUBBAND_SAMPLES, sel, id);
746 }
747
748 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])
749 {
750     uint8_t i, sel;
751     uint32_t best_sel_bits[DCA_CODE_BOOKS];
752     int32_t best_sel_id[DCA_CODE_BOOKS];
753     uint32_t t, bits = 0;
754
755     for (i = 0; i < DCA_CODE_BOOKS; i++) {
756
757         av_assert0(!((!!vlc_bits[i][0]) ^ (!!clc_bits[i])));
758         if (vlc_bits[i][0] == 0) {
759             /* do not transmit adjustment index for empty codebooks */
760             res[i] = ff_dca_quant_index_group_size[i];
761             /* and skip it */
762             continue;
763         }
764
765         best_sel_bits[i] = vlc_bits[i][0];
766         best_sel_id[i] = 0;
767         for (sel = 0; sel < ff_dca_quant_index_group_size[i]; sel++) {
768             if (best_sel_bits[i] > vlc_bits[i][sel] && vlc_bits[i][sel]) {
769                 best_sel_bits[i] = vlc_bits[i][sel];
770                 best_sel_id[i] = sel;
771             }
772         }
773
774         /* 2 bits to transmit scale factor adjustment index */
775         t = best_sel_bits[i] + 2;
776         if (t < clc_bits[i]) {
777             res[i] = best_sel_id[i];
778             bits += t;
779         } else {
780             res[i] = ff_dca_quant_index_group_size[i];
781             bits += clc_bits[i];
782         }
783     }
784     return bits;
785 }
786
787 static uint32_t set_best_abits_code(int abits[DCAENC_SUBBANDS], int bands, int32_t *res)
788 {
789     uint8_t i;
790     uint32_t t;
791     int32_t best_sel = 6;
792     int32_t best_bits = bands * 5;
793
794     /* Check do we have subband which cannot be encoded by Huffman tables */
795     for (i = 0; i < bands; i++) {
796         if (abits[i] > 12 || abits[i] == 0) {
797             *res = best_sel;
798             return best_bits;
799         }
800     }
801
802     for (i = 0; i < DCA_BITALLOC_12_COUNT; i++) {
803         t = ff_dca_vlc_calc_alloc_bits(abits, bands, i);
804         if (t < best_bits) {
805             best_bits = t;
806             best_sel = i;
807         }
808     }
809
810     *res = best_sel;
811     return best_bits;
812 }
813
814 static int init_quantization_noise(DCAEncContext *c, int noise, int forbid_zero)
815 {
816     int ch, band, ret = USED_26ABITS | USED_1ABITS;
817     uint32_t huff_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS][7];
818     uint32_t clc_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS];
819     uint32_t bits_counter = 0;
820
821     c->consumed_bits = 132 + 333 * c->fullband_channels;
822     c->consumed_bits += c->consumed_adpcm_bits;
823     if (c->lfe_channel)
824         c->consumed_bits += 72;
825
826     /* attempt to guess the bit distribution based on the prevoius frame */
827     for (ch = 0; ch < c->fullband_channels; ch++) {
828         for (band = 0; band < 32; band++) {
829             int snr_cb = c->peak_cb[ch][band] - c->band_masking_cb[band] - noise;
830
831             if (snr_cb >= 1312) {
832                 c->abits[ch][band] = 26;
833                 ret &= ~USED_1ABITS;
834             } else if (snr_cb >= 222) {
835                 c->abits[ch][band] = 8 + mul32(snr_cb - 222, 69000000);
836                 ret &= ~(USED_26ABITS | USED_1ABITS);
837             } else if (snr_cb >= 0) {
838                 c->abits[ch][band] = 2 + mul32(snr_cb, 106000000);
839                 ret &= ~(USED_26ABITS | USED_1ABITS);
840             } else if (forbid_zero || snr_cb >= -140) {
841                 c->abits[ch][band] = 1;
842                 ret &= ~USED_26ABITS;
843             } else {
844                 c->abits[ch][band] = 0;
845                 ret &= ~(USED_26ABITS | USED_1ABITS);
846             }
847         }
848         c->consumed_bits += set_best_abits_code(c->abits[ch], 32, &c->bit_allocation_sel[ch]);
849     }
850
851     /* Recalc scale_factor each time to get bits consumption in case of Huffman coding.
852        It is suboptimal solution */
853     /* TODO: May be cache scaled values */
854     for (ch = 0; ch < c->fullband_channels; ch++) {
855         for (band = 0; band < 32; band++) {
856             if (c->prediction_mode[ch][band] == -1) {
857                 c->scale_factor[ch][band] = calc_one_scale(c->peak_cb[ch][band],
858                                                            c->abits[ch][band],
859                                                            &c->quant[ch][band]);
860             }
861         }
862     }
863     quantize_adpcm(c);
864     quantize_pcm(c);
865
866     memset(huff_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * 7 * sizeof(uint32_t));
867     memset(clc_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * sizeof(uint32_t));
868     for (ch = 0; ch < c->fullband_channels; ch++) {
869         for (band = 0; band < 32; band++) {
870             if (c->abits[ch][band] && c->abits[ch][band] <= DCA_CODE_BOOKS) {
871                 accumulate_huff_bit_consumption(c->abits[ch][band], c->quantized[ch][band], huff_bit_count_accum[ch][c->abits[ch][band] - 1]);
872                 clc_bit_count_accum[ch][c->abits[ch][band] - 1] += bit_consumption[c->abits[ch][band]];
873             } else {
874                 bits_counter += bit_consumption[c->abits[ch][band]];
875             }
876         }
877     }
878
879     for (ch = 0; ch < c->fullband_channels; ch++) {
880         bits_counter += set_best_code(huff_bit_count_accum[ch], clc_bit_count_accum[ch], c->quant_index_sel[ch]);
881     }
882
883     c->consumed_bits += bits_counter;
884
885     return ret;
886 }
887
888 static void assign_bits(DCAEncContext *c)
889 {
890     /* Find the bounds where the binary search should work */
891     int low, high, down;
892     int used_abits = 0;
893     int forbid_zero = 1;
894 restart:
895     init_quantization_noise(c, c->worst_quantization_noise, forbid_zero);
896     low = high = c->worst_quantization_noise;
897     if (c->consumed_bits > c->frame_bits) {
898         while (c->consumed_bits > c->frame_bits) {
899             if (used_abits == USED_1ABITS && forbid_zero) {
900                 forbid_zero = 0;
901                 goto restart;
902             }
903             low = high;
904             high += snr_fudge;
905             used_abits = init_quantization_noise(c, high, forbid_zero);
906         }
907     } else {
908         while (c->consumed_bits <= c->frame_bits) {
909             high = low;
910             if (used_abits == USED_26ABITS)
911                 goto out; /* The requested bitrate is too high, pad with zeros */
912             low -= snr_fudge;
913             used_abits = init_quantization_noise(c, low, forbid_zero);
914         }
915     }
916
917     /* Now do a binary search between low and high to see what fits */
918     for (down = snr_fudge >> 1; down; down >>= 1) {
919         init_quantization_noise(c, high - down, forbid_zero);
920         if (c->consumed_bits <= c->frame_bits)
921             high -= down;
922     }
923     init_quantization_noise(c, high, forbid_zero);
924 out:
925     c->worst_quantization_noise = high;
926     if (high > c->worst_noise_ever)
927         c->worst_noise_ever = high;
928 }
929
930 static void shift_history(DCAEncContext *c, const int32_t *input)
931 {
932     int k, ch;
933
934     for (k = 0; k < 512; k++)
935         for (ch = 0; ch < c->channels; ch++) {
936             const int chi = c->channel_order_tab[ch];
937
938             c->history[ch][k] = input[k * c->channels + chi];
939         }
940 }
941
942 static void fill_in_adpcm_bufer(DCAEncContext *c)
943 {
944      int ch, band;
945      int32_t step_size;
946      /* We fill in ADPCM work buffer for subbands which hasn't been ADPCM coded
947       * in current frame - we need this data if subband of next frame is
948       * ADPCM
949       */
950      for (ch = 0; ch < c->channels; ch++) {
951         for (band = 0; band < 32; band++) {
952             int32_t *samples = c->subband[ch][band] - DCA_ADPCM_COEFFS;
953             if (c->prediction_mode[ch][band] == -1) {
954                 step_size = get_step_size(c, ch, band);
955
956                 ff_dca_core_dequantize(c->adpcm_history[ch][band],
957                                        c->quantized[ch][band]+12, step_size, ff_dca_scale_factor_quant7[c->scale_factor[ch][band]], 0, 4);
958             } else {
959                 AV_COPY128U(c->adpcm_history[ch][band], c->adpcm_history[ch][band]+4);
960             }
961             /* Copy dequantized values for LPC analysis.
962              * It reduces artifacts in case of extreme quantization,
963              * example: in current frame abits is 1 and has no prediction flag,
964              * but end of this frame is sine like signal. In this case, if LPC analysis uses
965              * original values, likely LPC analysis returns good prediction gain, and sets prediction flag.
966              * But there are no proper value in decoder history, so likely result will be no good.
967              * Bitstream has "Predictor history flag switch", but this flag disables history for all subbands
968              */
969             samples[0] = c->adpcm_history[ch][band][0] << 7;
970             samples[1] = c->adpcm_history[ch][band][1] << 7;
971             samples[2] = c->adpcm_history[ch][band][2] << 7;
972             samples[3] = c->adpcm_history[ch][band][3] << 7;
973         }
974      }
975 }
976
977 static void calc_lfe_scales(DCAEncContext *c)
978 {
979     if (c->lfe_channel)
980         c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);
981 }
982
983 static void put_frame_header(DCAEncContext *c)
984 {
985     /* SYNC */
986     put_bits(&c->pb, 16, 0x7ffe);
987     put_bits(&c->pb, 16, 0x8001);
988
989     /* Frame type: normal */
990     put_bits(&c->pb, 1, 1);
991
992     /* Deficit sample count: none */
993     put_bits(&c->pb, 5, 31);
994
995     /* CRC is not present */
996     put_bits(&c->pb, 1, 0);
997
998     /* Number of PCM sample blocks */
999     put_bits(&c->pb, 7, SUBBAND_SAMPLES - 1);
1000
1001     /* Primary frame byte size */
1002     put_bits(&c->pb, 14, c->frame_size - 1);
1003
1004     /* Audio channel arrangement */
1005     put_bits(&c->pb, 6, c->channel_config);
1006
1007     /* Core audio sampling frequency */
1008     put_bits(&c->pb, 4, bitstream_sfreq[c->samplerate_index]);
1009
1010     /* Transmission bit rate */
1011     put_bits(&c->pb, 5, c->bitrate_index);
1012
1013     /* Embedded down mix: disabled */
1014     put_bits(&c->pb, 1, 0);
1015
1016     /* Embedded dynamic range flag: not present */
1017     put_bits(&c->pb, 1, 0);
1018
1019     /* Embedded time stamp flag: not present */
1020     put_bits(&c->pb, 1, 0);
1021
1022     /* Auxiliary data flag: not present */
1023     put_bits(&c->pb, 1, 0);
1024
1025     /* HDCD source: no */
1026     put_bits(&c->pb, 1, 0);
1027
1028     /* Extension audio ID: N/A */
1029     put_bits(&c->pb, 3, 0);
1030
1031     /* Extended audio data: not present */
1032     put_bits(&c->pb, 1, 0);
1033
1034     /* Audio sync word insertion flag: after each sub-frame */
1035     put_bits(&c->pb, 1, 0);
1036
1037     /* Low frequency effects flag: not present or 64x subsampling */
1038     put_bits(&c->pb, 2, c->lfe_channel ? 2 : 0);
1039
1040     /* Predictor history switch flag: on */
1041     put_bits(&c->pb, 1, 1);
1042
1043     /* No CRC */
1044     /* Multirate interpolator switch: non-perfect reconstruction */
1045     put_bits(&c->pb, 1, 0);
1046
1047     /* Encoder software revision: 7 */
1048     put_bits(&c->pb, 4, 7);
1049
1050     /* Copy history: 0 */
1051     put_bits(&c->pb, 2, 0);
1052
1053     /* Source PCM resolution: 16 bits, not DTS ES */
1054     put_bits(&c->pb, 3, 0);
1055
1056     /* Front sum/difference coding: no */
1057     put_bits(&c->pb, 1, 0);
1058
1059     /* Surrounds sum/difference coding: no */
1060     put_bits(&c->pb, 1, 0);
1061
1062     /* Dialog normalization: 0 dB */
1063     put_bits(&c->pb, 4, 0);
1064 }
1065
1066 static void put_primary_audio_header(DCAEncContext *c)
1067 {
1068     int ch, i;
1069     /* Number of subframes */
1070     put_bits(&c->pb, 4, SUBFRAMES - 1);
1071
1072     /* Number of primary audio channels */
1073     put_bits(&c->pb, 3, c->fullband_channels - 1);
1074
1075     /* Subband activity count */
1076     for (ch = 0; ch < c->fullband_channels; ch++)
1077         put_bits(&c->pb, 5, DCAENC_SUBBANDS - 2);
1078
1079     /* High frequency VQ start subband */
1080     for (ch = 0; ch < c->fullband_channels; ch++)
1081         put_bits(&c->pb, 5, DCAENC_SUBBANDS - 1);
1082
1083     /* Joint intensity coding index: 0, 0 */
1084     for (ch = 0; ch < c->fullband_channels; ch++)
1085         put_bits(&c->pb, 3, 0);
1086
1087     /* Transient mode codebook: A4, A4 (arbitrary) */
1088     for (ch = 0; ch < c->fullband_channels; ch++)
1089         put_bits(&c->pb, 2, 0);
1090
1091     /* Scale factor code book: 7 bit linear, 7-bit sqrt table (for each channel) */
1092     for (ch = 0; ch < c->fullband_channels; ch++)
1093         put_bits(&c->pb, 3, 6);
1094
1095     /* Bit allocation quantizer select: linear 5-bit */
1096     for (ch = 0; ch < c->fullband_channels; ch++)
1097         put_bits(&c->pb, 3, c->bit_allocation_sel[ch]);
1098
1099     /* Quantization index codebook select */
1100     for (i = 0; i < DCA_CODE_BOOKS; i++)
1101         for (ch = 0; ch < c->fullband_channels; ch++)
1102             put_bits(&c->pb, ff_dca_quant_index_sel_nbits[i], c->quant_index_sel[ch][i]);
1103
1104     /* Scale factor adjustment index: transmitted in case of Huffman coding */
1105     for (i = 0; i < DCA_CODE_BOOKS; i++)
1106         for (ch = 0; ch < c->fullband_channels; ch++)
1107             if (c->quant_index_sel[ch][i] < ff_dca_quant_index_group_size[i])
1108                 put_bits(&c->pb, 2, 0);
1109
1110     /* Audio header CRC check word: not transmitted */
1111 }
1112
1113 static void put_subframe_samples(DCAEncContext *c, int ss, int band, int ch)
1114 {
1115     int i, j, sum, bits, sel;
1116     if (c->abits[ch][band] <= DCA_CODE_BOOKS) {
1117         av_assert0(c->abits[ch][band] > 0);
1118         sel = c->quant_index_sel[ch][c->abits[ch][band] - 1];
1119         // Huffman codes
1120         if (sel < ff_dca_quant_index_group_size[c->abits[ch][band] - 1]) {
1121             ff_dca_vlc_enc_quant(&c->pb, &c->quantized[ch][band][ss * 8], 8, sel, c->abits[ch][band] - 1);
1122             return;
1123         }
1124
1125         // Block codes
1126         if (c->abits[ch][band] <= 7) {
1127             for (i = 0; i < 8; i += 4) {
1128                 sum = 0;
1129                 for (j = 3; j >= 0; j--) {
1130                     sum *= ff_dca_quant_levels[c->abits[ch][band]];
1131                     sum += c->quantized[ch][band][ss * 8 + i + j];
1132                     sum += (ff_dca_quant_levels[c->abits[ch][band]] - 1) / 2;
1133                 }
1134                 put_bits(&c->pb, bit_consumption[c->abits[ch][band]] / 4, sum);
1135             }
1136             return;
1137         }
1138     }
1139
1140     for (i = 0; i < 8; i++) {
1141         bits = bit_consumption[c->abits[ch][band]] / 16;
1142         put_sbits(&c->pb, bits, c->quantized[ch][band][ss * 8 + i]);
1143     }
1144 }
1145
1146 static void put_subframe(DCAEncContext *c, int subframe)
1147 {
1148     int i, band, ss, ch;
1149
1150     /* Subsubframes count */
1151     put_bits(&c->pb, 2, SUBSUBFRAMES -1);
1152
1153     /* Partial subsubframe sample count: dummy */
1154     put_bits(&c->pb, 3, 0);
1155
1156     /* Prediction mode: no ADPCM, in each channel and subband */
1157     for (ch = 0; ch < c->fullband_channels; ch++)
1158         for (band = 0; band < DCAENC_SUBBANDS; band++)
1159             put_bits(&c->pb, 1, !(c->prediction_mode[ch][band] == -1));
1160
1161     /* Prediction VQ address */
1162     for (ch = 0; ch < c->fullband_channels; ch++)
1163         for (band = 0; band < DCAENC_SUBBANDS; band++)
1164             if (c->prediction_mode[ch][band] >= 0)
1165                 put_bits(&c->pb, 12, c->prediction_mode[ch][band]);
1166
1167     /* Bit allocation index */
1168     for (ch = 0; ch < c->fullband_channels; ch++) {
1169         if (c->bit_allocation_sel[ch] == 6) {
1170             for (band = 0; band < DCAENC_SUBBANDS; band++) {
1171                 put_bits(&c->pb, 5, c->abits[ch][band]);
1172             }
1173         } else {
1174             ff_dca_vlc_enc_alloc(&c->pb, c->abits[ch], DCAENC_SUBBANDS, c->bit_allocation_sel[ch]);
1175         }
1176     }
1177
1178     if (SUBSUBFRAMES > 1) {
1179         /* Transition mode: none for each channel and subband */
1180         for (ch = 0; ch < c->fullband_channels; ch++)
1181             for (band = 0; band < DCAENC_SUBBANDS; band++)
1182                 if (c->abits[ch][band])
1183                     put_bits(&c->pb, 1, 0); /* codebook A4 */
1184     }
1185
1186     /* Scale factors */
1187     for (ch = 0; ch < c->fullband_channels; ch++)
1188         for (band = 0; band < DCAENC_SUBBANDS; band++)
1189             if (c->abits[ch][band])
1190                 put_bits(&c->pb, 7, c->scale_factor[ch][band]);
1191
1192     /* Joint subband scale factor codebook select: not transmitted */
1193     /* Scale factors for joint subband coding: not transmitted */
1194     /* Stereo down-mix coefficients: not transmitted */
1195     /* Dynamic range coefficient: not transmitted */
1196     /* Stde information CRC check word: not transmitted */
1197     /* VQ encoded high frequency subbands: not transmitted */
1198
1199     /* LFE data: 8 samples and scalefactor */
1200     if (c->lfe_channel) {
1201         for (i = 0; i < DCA_LFE_SAMPLES; i++)
1202             put_bits(&c->pb, 8, quantize_value(c->downsampled_lfe[i], c->lfe_quant) & 0xff);
1203         put_bits(&c->pb, 8, c->lfe_scale_factor);
1204     }
1205
1206     /* Audio data (subsubframes) */
1207     for (ss = 0; ss < SUBSUBFRAMES ; ss++)
1208         for (ch = 0; ch < c->fullband_channels; ch++)
1209             for (band = 0; band < DCAENC_SUBBANDS; band++)
1210                 if (c->abits[ch][band])
1211                     put_subframe_samples(c, ss, band, ch);
1212
1213     /* DSYNC */
1214     put_bits(&c->pb, 16, 0xffff);
1215 }
1216
1217 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1218                         const AVFrame *frame, int *got_packet_ptr)
1219 {
1220     DCAEncContext *c = avctx->priv_data;
1221     const int32_t *samples;
1222     int ret, i;
1223
1224     if ((ret = ff_alloc_packet2(avctx, avpkt, c->frame_size, 0)) < 0)
1225         return ret;
1226
1227     samples = (const int32_t *)frame->data[0];
1228
1229     subband_transform(c, samples);
1230     if (c->lfe_channel)
1231         lfe_downsample(c, samples);
1232
1233     calc_masking(c, samples);
1234     if (c->options.adpcm_mode)
1235         adpcm_analysis(c);
1236     find_peaks(c);
1237     assign_bits(c);
1238     calc_lfe_scales(c);
1239     shift_history(c, samples);
1240
1241     init_put_bits(&c->pb, avpkt->data, avpkt->size);
1242     fill_in_adpcm_bufer(c);
1243     put_frame_header(c);
1244     put_primary_audio_header(c);
1245     for (i = 0; i < SUBFRAMES; i++)
1246         put_subframe(c, i);
1247
1248
1249     for (i = put_bits_count(&c->pb); i < 8*c->frame_size; i++)
1250         put_bits(&c->pb, 1, 0);
1251
1252     flush_put_bits(&c->pb);
1253
1254     avpkt->pts      = frame->pts;
1255     avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1256     avpkt->size     = put_bits_count(&c->pb) >> 3;
1257     *got_packet_ptr = 1;
1258     return 0;
1259 }
1260
1261 #define DCAENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1262
1263 static const AVOption options[] = {
1264     { "dca_adpcm", "Use ADPCM encoding", offsetof(DCAEncContext, options.adpcm_mode), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DCAENC_FLAGS },
1265     { NULL },
1266 };
1267
1268 static const AVClass dcaenc_class = {
1269     .class_name = "DCA (DTS Coherent Acoustics)",
1270     .item_name = av_default_item_name,
1271     .option = options,
1272     .version = LIBAVUTIL_VERSION_INT,
1273 };
1274
1275 static const AVCodecDefault defaults[] = {
1276     { "b",          "1411200" },
1277     { NULL },
1278 };
1279
1280 AVCodec ff_dca_encoder = {
1281     .name                  = "dca",
1282     .long_name             = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1283     .type                  = AVMEDIA_TYPE_AUDIO,
1284     .id                    = AV_CODEC_ID_DTS,
1285     .priv_data_size        = sizeof(DCAEncContext),
1286     .init                  = encode_init,
1287     .close                 = encode_close,
1288     .encode2               = encode_frame,
1289     .capabilities          = AV_CODEC_CAP_EXPERIMENTAL,
1290     .sample_fmts           = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32,
1291                                                             AV_SAMPLE_FMT_NONE },
1292     .supported_samplerates = sample_rates,
1293     .channel_layouts       = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
1294                                                   AV_CH_LAYOUT_STEREO,
1295                                                   AV_CH_LAYOUT_2_2,
1296                                                   AV_CH_LAYOUT_5POINT0,
1297                                                   AV_CH_LAYOUT_5POINT1,
1298                                                   0 },
1299     .defaults              = defaults,
1300     .priv_class            = &dcaenc_class,
1301 };