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