3 * Copyright (C) 2008-2012 Alexander E. Patrakov
4 * 2010 Benjamin Larsson
7 * This file is part of FFmpeg.
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.
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.
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
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"
40 #define MAX_CHANNELS 6
41 #define DCA_MAX_FRAME_SIZE 16384
42 #define DCA_HEADER_SIZE 13
43 #define DCA_LFE_SAMPLES 8
45 #define DCAENC_SUBBANDS 32
47 #define SUBSUBFRAMES 2
48 #define SUBBAND_SAMPLES (SUBFRAMES * SUBSUBFRAMES * 8)
51 typedef struct CompressionOptions {
55 typedef struct DCAEncContext {
58 DCAADPCMEncContext adpcm_ctx;
59 CompressionOptions options;
62 int fullband_channels;
68 const int32_t *band_interpolation;
69 const int32_t *band_spectrum;
73 const int8_t *channel_order_tab; ///< channel reordering table, lfe and non lfe
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;
94 int consumed_adpcm_bits; ///< Number of bits to transmit ADPCM related info
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];
105 /* Transfer function of outer and middle ear, Hz -> dB */
106 static double hom(double f)
108 double f1 = f / 1000;
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);
116 static double gammafilter(int i, double f)
118 double h = (f - fc[i]) / erb[i];
122 return 20 * log10(h);
125 static int subband_bufer_alloc(DCAEncContext *c)
128 int32_t *bufer = av_calloc(MAX_CHANNELS * DCAENC_SUBBANDS *
129 (SUBBAND_SAMPLES + DCA_ADPCM_COEFFS),
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;
146 static void subband_bufer_free(DCAEncContext *c)
148 int32_t *bufer = c->subband[0][0] - DCA_ADPCM_COEFFS;
152 static int encode_init(AVCodecContext *avctx)
154 DCAEncContext *c = avctx->priv_data;
155 uint64_t layout = avctx->channel_layout;
156 int i, j, min_frame_bits;
158 if (subband_bufer_alloc(c))
159 return AVERROR(ENOMEM);
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;
169 if (ff_dcaadpcm_init(&c->adpcm_ctx))
170 return AVERROR(ENOMEM);
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);
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;
185 av_log(avctx, AV_LOG_ERROR, "Unsupported channel layout!\n");
186 return AVERROR_PATCHWELCOME;
189 if (c->lfe_channel) {
190 c->fullband_channels--;
191 c->channel_order_tab = channel_reorder_lfe[c->channel_config];
193 c->channel_order_tab = channel_reorder_nolfe[c->channel_config];
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];
201 c->bit_allocation_sel[i] = 6;
203 for (j = 0; j < DCAENC_SUBBANDS; j++) {
205 c->prediction_mode[i][j] = -1;
206 memset(c->adpcm_history[i][j], 0, sizeof(int32_t)*DCA_ADPCM_COEFFS);
210 for (i = 0; i < 9; i++) {
211 if (sample_rates[i] == avctx->sample_rate)
215 return AVERROR(EINVAL);
216 c->samplerate_index = i;
218 if (avctx->bit_rate < 32000 || avctx->bit_rate > 3840000) {
219 av_log(avctx, AV_LOG_ERROR, "Bit rate %"PRId64" not supported.", (int64_t)avctx->bit_rate);
220 return AVERROR(EINVAL);
222 for (i = 0; ff_dca_bit_rates[i] < avctx->bit_rate; i++)
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);
230 c->frame_size = (c->frame_bits + 7) / 8;
232 avctx->frame_size = 32 * SUBBAND_SAMPLES;
237 cos_table[0] = 0x7fffffff;
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];
246 for (i = 0; i < 2048; i++) {
247 cb_to_level[i] = (int32_t)(0x7fffffff * ff_exp10(-0.005 * i));
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]);
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]);
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;
267 auf[i][j][k] = (int32_t)(10 * (hom(freq) + gammafilter(j, freq)));
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));
276 for (j = 0; j < 8; j++) {
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);
282 band_spectrum[0][j] = (int32_t)(200 * log10(accum));
284 for (j = 0; j < 8; j++) {
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);
290 band_spectrum[1][j] = (int32_t)(200 * log10(accum));
296 static av_cold int encode_close(AVCodecContext *avctx)
298 if (avctx->priv_data) {
299 DCAEncContext *c = avctx->priv_data;
300 subband_bufer_free(c);
301 ff_dcaadpcm_free(&c->adpcm_ctx);
306 static inline int32_t cos_t(int x)
308 return cos_table[x & 2047];
311 static inline int32_t sin_t(int x)
313 return cos_t(x - 512);
316 static inline int32_t half32(int32_t a)
321 static void subband_transform(DCAEncContext *c, const int32_t *input)
323 int ch, subs, i, k, j;
325 for (ch = 0; ch < c->fullband_channels; ch++) {
326 /* History is copied because it is also needed for PSY */
329 const int chi = c->channel_order_tab[ch];
331 memcpy(hist, &c->history[ch][0], 512 * sizeof(int32_t));
333 for (subs = 0; subs < SUBBAND_SAMPLES; subs++) {
338 /* Calculate the convolutions at once */
339 memset(accum, 0, 64 * sizeof(int32_t));
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]);
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];
352 for (band = 0; band < 32; band++) {
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;
359 c->subband[ch][band][subs] = ((band + 1) & 2) ? -resp : resp;
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];
366 hist_start = (hist_start + 32) & 511;
371 static void lfe_downsample(DCAEncContext *c, const int32_t *input)
373 /* FIXME: make 128x LFE downsampling possible */
374 const int lfech = lfe_index[c->channel_config];
380 memcpy(hist, &c->history[c->channels - 1][0], 512 * sizeof(int32_t));
382 for (lfes = 0; lfes < DCA_LFE_SAMPLES; lfes++) {
383 /* Calculate the convolution */
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]);
391 c->downsampled_lfe[lfes] = accum;
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];
397 hist_start = (hist_start + 64) & 511;
406 static void fft(const int32_t in[2 * 256], cplx32 out[256])
408 cplx32 buf[256], rin[256], rout[256];
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));
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);
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++) {
431 sum.re = buf[i].re + buf[i + j / 2].re;
432 sum.im = buf[i].im + buf[i + j / 2].im;
434 diff.re = buf[i].re - buf[i + j / 2].re;
435 diff.im = buf[i].im - buf[i + j / 2].im;
437 buf[i].re = half32(sum.re);
438 buf[i].im = half32(sum.im);
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));
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));
455 for (i = 0; i < 256; i++) {
456 /* separate the results of the two transforms */
459 o1.re = rout[i].re - rout[255 - i].re;
460 o1.im = rout[i].im + rout[255 - i].im;
462 o2.re = rout[i].im - rout[255 - i].im;
463 o2.im = -rout[i].re - rout[255 - i].re;
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));
473 static int32_t get_cb(int32_t in)
480 for (i = 1024; i > 0; i >>= 1) {
481 if (cb_to_level[i + res] >= in)
487 static int32_t add_cb(int32_t a, int32_t b)
490 FFSWAP(int32_t, a, b);
494 return a + cb_to_add[a - b];
497 static void adjust_jnd(int samplerate_index,
498 const int32_t in[512], int32_t out_cb[256])
502 int32_t out_cb_unnorm[256];
504 const int32_t ca_cb = -1114;
505 const int32_t cs_cb = 928;
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 */
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]);
524 for (j = 0; j < 256; j++)
525 out_cb[j] = add_cb(out_cb[j], -out_cb_unnorm[j] - ca_cb - cs_cb);
528 typedef void (*walk_band_t)(DCAEncContext *c, int band1, int band2, int f,
529 int32_t spectrum1, int32_t spectrum2, int channel,
532 static void walk_band_low(DCAEncContext *c, int band, int channel,
533 walk_band_t walk, int32_t *arg)
538 for (f = 0; f < 4; f++)
539 walk(c, 0, 0, f, 0, -2047, channel, arg);
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);
547 static void walk_band_high(DCAEncContext *c, int band, int channel,
548 walk_band_t walk, int32_t *arg)
553 for (f = 0; f < 4; f++)
554 walk(c, 31, 31, 256 - 4 + f, 0, -2047, channel, arg);
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);
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)
566 int32_t value = c->eff_masking_curve_cb[f] - spectrum1;
568 if (value < c->band_masking_cb[band1])
569 c->band_masking_cb[band1] = value;
572 static void calc_masking(DCAEncContext *c, const int32_t *input)
574 int i, k, band, ch, ssf;
577 for (i = 0; i < 256; i++)
578 for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
579 c->masking_curve_cb[ssf][i] = -2047;
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];
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]);
591 for (i = 0; i < 256; i++) {
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;
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);
607 static inline int32_t find_peak(const int32_t *in, int len) {
610 for (sample = 0; sample < len; sample++) {
611 int32_t s = abs(in[sample]);
619 static void find_peaks(DCAEncContext *c)
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);
629 if (c->lfe_channel) {
630 c->lfe_peak_cb = find_peak(c->downsampled_lfe, DCA_LFE_SAMPLES);
634 static void adpcm_analysis(DCAEncContext *c)
639 int32_t estimated_diff[SUBBAND_SAMPLES];
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);
651 c->prediction_mode[ch][band] = -1;
657 static const int snr_fudge = 128;
658 #define USED_1ABITS 1
659 #define USED_NABITS 2
660 #define USED_26ABITS 4
662 static inline int32_t get_step_size(const DCAEncContext *c, int ch, int band)
666 if (c->bitrate_index == 3)
667 step_size = ff_dca_lossless_quant[c->abits[ch][band]];
669 step_size = ff_dca_lossy_quant[c->abits[ch][band]];
674 static int calc_one_scale(int32_t peak_cb, int abits, softfloat *quant)
677 int our_nscale, try_remove;
680 av_assert0(peak_cb <= 0);
681 av_assert0(peak_cb >= -2047);
684 peak = cb_to_level[-peak_cb];
686 for (try_remove = 64; try_remove > 0; try_remove >>= 1) {
687 if (scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e <= 17)
689 our_quant.m = mul32(scalefactor_inv[our_nscale - try_remove].m, stepsize_inv[abits].m);
690 our_quant.e = scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e - 17;
691 if ((ff_dca_quant_levels[abits] - 1) / 2 < quantize_value(peak, our_quant))
693 our_nscale -= try_remove;
696 if (our_nscale >= 125)
699 quant->m = mul32(scalefactor_inv[our_nscale].m, stepsize_inv[abits].m);
700 quant->e = scalefactor_inv[our_nscale].e + stepsize_inv[abits].e - 17;
701 av_assert0((ff_dca_quant_levels[abits] - 1) / 2 >= quantize_value(peak, *quant));
706 static inline void quantize_adpcm_subband(DCAEncContext *c, int ch, int band)
709 int32_t diff_peak_cb = c->diff_peak_cb[ch][band];
710 c->scale_factor[ch][band] = calc_one_scale(diff_peak_cb,
712 &c->quant[ch][band]);
714 step_size = get_step_size(c, ch, band);
715 ff_dcaadpcm_do_real(c->prediction_mode[ch][band],
716 c->quant[ch][band], ff_dca_scale_factor_quant7[c->scale_factor[ch][band]], step_size,
717 c->adpcm_history[ch][band], c->subband[ch][band], c->adpcm_history[ch][band]+4, c->quantized[ch][band],
718 SUBBAND_SAMPLES, cb_to_level[-diff_peak_cb]);
721 static void quantize_adpcm(DCAEncContext *c)
725 for (ch = 0; ch < c->fullband_channels; ch++)
726 for (band = 0; band < 32; band++)
727 if (c->prediction_mode[ch][band] >= 0)
728 quantize_adpcm_subband(c, ch, band);
731 static void quantize_pcm(DCAEncContext *c)
733 int sample, band, ch;
735 for (ch = 0; ch < c->fullband_channels; ch++)
736 for (band = 0; band < 32; band++)
737 if (c->prediction_mode[ch][band] == -1)
738 for (sample = 0; sample < SUBBAND_SAMPLES; sample++)
739 c->quantized[ch][band][sample] = quantize_value(c->subband[ch][band][sample], c->quant[ch][band]);
742 static void accumulate_huff_bit_consumption(int abits, int32_t *quantized, uint32_t *result)
744 uint8_t sel, id = abits - 1;
745 for (sel = 0; sel < ff_dca_quant_index_group_size[id]; sel++)
746 result[sel] += ff_dca_vlc_calc_quant_bits(quantized, SUBBAND_SAMPLES, sel, id);
749 static uint32_t set_best_code(uint32_t vlc_bits[DCA_CODE_BOOKS][7], uint32_t clc_bits[DCA_CODE_BOOKS], int32_t res[DCA_CODE_BOOKS])
752 uint32_t best_sel_bits[DCA_CODE_BOOKS];
753 int32_t best_sel_id[DCA_CODE_BOOKS];
754 uint32_t t, bits = 0;
756 for (i = 0; i < DCA_CODE_BOOKS; i++) {
758 av_assert0(!((!!vlc_bits[i][0]) ^ (!!clc_bits[i])));
759 if (vlc_bits[i][0] == 0) {
760 /* do not transmit adjustment index for empty codebooks */
761 res[i] = ff_dca_quant_index_group_size[i];
766 best_sel_bits[i] = vlc_bits[i][0];
768 for (sel = 0; sel < ff_dca_quant_index_group_size[i]; sel++) {
769 if (best_sel_bits[i] > vlc_bits[i][sel] && vlc_bits[i][sel]) {
770 best_sel_bits[i] = vlc_bits[i][sel];
771 best_sel_id[i] = sel;
775 /* 2 bits to transmit scale factor adjustment index */
776 t = best_sel_bits[i] + 2;
777 if (t < clc_bits[i]) {
778 res[i] = best_sel_id[i];
781 res[i] = ff_dca_quant_index_group_size[i];
788 static uint32_t set_best_abits_code(int abits[DCAENC_SUBBANDS], int bands, int32_t *res)
792 int32_t best_sel = 6;
793 int32_t best_bits = bands * 5;
795 /* Check do we have subband which cannot be encoded by Huffman tables */
796 for (i = 0; i < bands; i++) {
803 for (i = 0; i < DCA_BITALLOC_12_COUNT; i++) {
804 t = ff_dca_vlc_calc_alloc_bits(abits, bands, i);
815 static int init_quantization_noise(DCAEncContext *c, int noise)
817 int ch, band, ret = 0;
818 uint32_t huff_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS][7];
819 uint32_t clc_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS];
820 uint32_t bits_counter = 0;
822 c->consumed_bits = 132 + 333 * c->fullband_channels;
823 c->consumed_bits += c->consumed_adpcm_bits;
825 c->consumed_bits += 72;
827 /* attempt to guess the bit distribution based on the prevoius frame */
828 for (ch = 0; ch < c->fullband_channels; ch++) {
829 for (band = 0; band < 32; band++) {
830 int snr_cb = c->peak_cb[ch][band] - c->band_masking_cb[band] - noise;
832 if (snr_cb >= 1312) {
833 c->abits[ch][band] = 26;
835 } else if (snr_cb >= 222) {
836 c->abits[ch][band] = 8 + mul32(snr_cb - 222, 69000000);
838 } else if (snr_cb >= 0) {
839 c->abits[ch][band] = 2 + mul32(snr_cb, 106000000);
842 c->abits[ch][band] = 1;
846 c->consumed_bits += set_best_abits_code(c->abits[ch], 32, &c->bit_allocation_sel[ch]);
849 /* Recalc scale_factor each time to get bits consumption in case of Huffman coding.
850 It is suboptimal solution */
851 /* TODO: May be cache scaled values */
852 for (ch = 0; ch < c->fullband_channels; ch++) {
853 for (band = 0; band < 32; band++) {
854 if (c->prediction_mode[ch][band] == -1) {
855 c->scale_factor[ch][band] = calc_one_scale(c->peak_cb[ch][band],
857 &c->quant[ch][band]);
864 memset(huff_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * 7 * sizeof(uint32_t));
865 memset(clc_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * sizeof(uint32_t));
866 for (ch = 0; ch < c->fullband_channels; ch++) {
867 for (band = 0; band < 32; band++) {
868 if (c->abits[ch][band] && c->abits[ch][band] <= DCA_CODE_BOOKS) {
869 accumulate_huff_bit_consumption(c->abits[ch][band], c->quantized[ch][band], huff_bit_count_accum[ch][c->abits[ch][band] - 1]);
870 clc_bit_count_accum[ch][c->abits[ch][band] - 1] += bit_consumption[c->abits[ch][band]];
872 bits_counter += bit_consumption[c->abits[ch][band]];
877 for (ch = 0; ch < c->fullband_channels; ch++) {
878 bits_counter += set_best_code(huff_bit_count_accum[ch], clc_bit_count_accum[ch], c->quant_index_sel[ch]);
881 c->consumed_bits += bits_counter;
886 static void assign_bits(DCAEncContext *c)
888 /* Find the bounds where the binary search should work */
892 init_quantization_noise(c, c->worst_quantization_noise);
893 low = high = c->worst_quantization_noise;
894 if (c->consumed_bits > c->frame_bits) {
895 while (c->consumed_bits > c->frame_bits) {
896 av_assert0(used_abits != USED_1ABITS);
899 used_abits = init_quantization_noise(c, high);
902 while (c->consumed_bits <= c->frame_bits) {
904 if (used_abits == USED_26ABITS)
905 goto out; /* The requested bitrate is too high, pad with zeros */
907 used_abits = init_quantization_noise(c, low);
911 /* Now do a binary search between low and high to see what fits */
912 for (down = snr_fudge >> 1; down; down >>= 1) {
913 init_quantization_noise(c, high - down);
914 if (c->consumed_bits <= c->frame_bits)
917 init_quantization_noise(c, high);
919 c->worst_quantization_noise = high;
920 if (high > c->worst_noise_ever)
921 c->worst_noise_ever = high;
924 static void shift_history(DCAEncContext *c, const int32_t *input)
928 for (k = 0; k < 512; k++)
929 for (ch = 0; ch < c->channels; ch++) {
930 const int chi = c->channel_order_tab[ch];
932 c->history[ch][k] = input[k * c->channels + chi];
936 static void fill_in_adpcm_bufer(DCAEncContext *c)
940 /* We fill in ADPCM work buffer for subbands which hasn't been ADPCM coded
941 * in current frame - we need this data if subband of next frame is
944 for (ch = 0; ch < c->channels; ch++) {
945 for (band = 0; band < 32; band++) {
946 int32_t *samples = c->subband[ch][band] - DCA_ADPCM_COEFFS;
947 if (c->prediction_mode[ch][band] == -1) {
948 step_size = get_step_size(c, ch, band);
950 ff_dca_core_dequantize(c->adpcm_history[ch][band],
951 c->quantized[ch][band]+12, step_size, ff_dca_scale_factor_quant7[c->scale_factor[ch][band]], 0, 4);
953 AV_COPY128U(c->adpcm_history[ch][band], c->adpcm_history[ch][band]+4);
955 /* Copy dequantized values for LPC analysis.
956 * It reduces artifacts in case of extreme quantization,
957 * example: in current frame abits is 1 and has no prediction flag,
958 * but end of this frame is sine like signal. In this case, if LPC analysis uses
959 * original values, likely LPC analysis returns good prediction gain, and sets prediction flag.
960 * But there are no proper value in decoder history, so likely result will be no good.
961 * Bitstream has "Predictor history flag switch", but this flag disables history for all subbands
963 samples[0] = c->adpcm_history[ch][band][0] << 7;
964 samples[1] = c->adpcm_history[ch][band][1] << 7;
965 samples[2] = c->adpcm_history[ch][band][2] << 7;
966 samples[3] = c->adpcm_history[ch][band][3] << 7;
971 static void calc_lfe_scales(DCAEncContext *c)
974 c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);
977 static void put_frame_header(DCAEncContext *c)
980 put_bits(&c->pb, 16, 0x7ffe);
981 put_bits(&c->pb, 16, 0x8001);
983 /* Frame type: normal */
984 put_bits(&c->pb, 1, 1);
986 /* Deficit sample count: none */
987 put_bits(&c->pb, 5, 31);
989 /* CRC is not present */
990 put_bits(&c->pb, 1, 0);
992 /* Number of PCM sample blocks */
993 put_bits(&c->pb, 7, SUBBAND_SAMPLES - 1);
995 /* Primary frame byte size */
996 put_bits(&c->pb, 14, c->frame_size - 1);
998 /* Audio channel arrangement */
999 put_bits(&c->pb, 6, c->channel_config);
1001 /* Core audio sampling frequency */
1002 put_bits(&c->pb, 4, bitstream_sfreq[c->samplerate_index]);
1004 /* Transmission bit rate */
1005 put_bits(&c->pb, 5, c->bitrate_index);
1007 /* Embedded down mix: disabled */
1008 put_bits(&c->pb, 1, 0);
1010 /* Embedded dynamic range flag: not present */
1011 put_bits(&c->pb, 1, 0);
1013 /* Embedded time stamp flag: not present */
1014 put_bits(&c->pb, 1, 0);
1016 /* Auxiliary data flag: not present */
1017 put_bits(&c->pb, 1, 0);
1019 /* HDCD source: no */
1020 put_bits(&c->pb, 1, 0);
1022 /* Extension audio ID: N/A */
1023 put_bits(&c->pb, 3, 0);
1025 /* Extended audio data: not present */
1026 put_bits(&c->pb, 1, 0);
1028 /* Audio sync word insertion flag: after each sub-frame */
1029 put_bits(&c->pb, 1, 0);
1031 /* Low frequency effects flag: not present or 64x subsampling */
1032 put_bits(&c->pb, 2, c->lfe_channel ? 2 : 0);
1034 /* Predictor history switch flag: on */
1035 put_bits(&c->pb, 1, 1);
1038 /* Multirate interpolator switch: non-perfect reconstruction */
1039 put_bits(&c->pb, 1, 0);
1041 /* Encoder software revision: 7 */
1042 put_bits(&c->pb, 4, 7);
1044 /* Copy history: 0 */
1045 put_bits(&c->pb, 2, 0);
1047 /* Source PCM resolution: 16 bits, not DTS ES */
1048 put_bits(&c->pb, 3, 0);
1050 /* Front sum/difference coding: no */
1051 put_bits(&c->pb, 1, 0);
1053 /* Surrounds sum/difference coding: no */
1054 put_bits(&c->pb, 1, 0);
1056 /* Dialog normalization: 0 dB */
1057 put_bits(&c->pb, 4, 0);
1060 static void put_primary_audio_header(DCAEncContext *c)
1063 /* Number of subframes */
1064 put_bits(&c->pb, 4, SUBFRAMES - 1);
1066 /* Number of primary audio channels */
1067 put_bits(&c->pb, 3, c->fullband_channels - 1);
1069 /* Subband activity count */
1070 for (ch = 0; ch < c->fullband_channels; ch++)
1071 put_bits(&c->pb, 5, DCAENC_SUBBANDS - 2);
1073 /* High frequency VQ start subband */
1074 for (ch = 0; ch < c->fullband_channels; ch++)
1075 put_bits(&c->pb, 5, DCAENC_SUBBANDS - 1);
1077 /* Joint intensity coding index: 0, 0 */
1078 for (ch = 0; ch < c->fullband_channels; ch++)
1079 put_bits(&c->pb, 3, 0);
1081 /* Transient mode codebook: A4, A4 (arbitrary) */
1082 for (ch = 0; ch < c->fullband_channels; ch++)
1083 put_bits(&c->pb, 2, 0);
1085 /* Scale factor code book: 7 bit linear, 7-bit sqrt table (for each channel) */
1086 for (ch = 0; ch < c->fullband_channels; ch++)
1087 put_bits(&c->pb, 3, 6);
1089 /* Bit allocation quantizer select: linear 5-bit */
1090 for (ch = 0; ch < c->fullband_channels; ch++)
1091 put_bits(&c->pb, 3, c->bit_allocation_sel[ch]);
1093 /* Quantization index codebook select */
1094 for (i = 0; i < DCA_CODE_BOOKS; i++)
1095 for (ch = 0; ch < c->fullband_channels; ch++)
1096 put_bits(&c->pb, ff_dca_quant_index_sel_nbits[i], c->quant_index_sel[ch][i]);
1098 /* Scale factor adjustment index: transmitted in case of Huffman coding */
1099 for (i = 0; i < DCA_CODE_BOOKS; i++)
1100 for (ch = 0; ch < c->fullband_channels; ch++)
1101 if (c->quant_index_sel[ch][i] < ff_dca_quant_index_group_size[i])
1102 put_bits(&c->pb, 2, 0);
1104 /* Audio header CRC check word: not transmitted */
1107 static void put_subframe_samples(DCAEncContext *c, int ss, int band, int ch)
1109 int i, j, sum, bits, sel;
1110 if (c->abits[ch][band] <= DCA_CODE_BOOKS) {
1111 av_assert0(c->abits[ch][band] > 0);
1112 sel = c->quant_index_sel[ch][c->abits[ch][band] - 1];
1114 if (sel < ff_dca_quant_index_group_size[c->abits[ch][band] - 1]) {
1115 ff_dca_vlc_enc_quant(&c->pb, &c->quantized[ch][band][ss * 8], 8, sel, c->abits[ch][band] - 1);
1120 if (c->abits[ch][band] <= 7) {
1121 for (i = 0; i < 8; i += 4) {
1123 for (j = 3; j >= 0; j--) {
1124 sum *= ff_dca_quant_levels[c->abits[ch][band]];
1125 sum += c->quantized[ch][band][ss * 8 + i + j];
1126 sum += (ff_dca_quant_levels[c->abits[ch][band]] - 1) / 2;
1128 put_bits(&c->pb, bit_consumption[c->abits[ch][band]] / 4, sum);
1134 for (i = 0; i < 8; i++) {
1135 bits = bit_consumption[c->abits[ch][band]] / 16;
1136 put_sbits(&c->pb, bits, c->quantized[ch][band][ss * 8 + i]);
1140 static void put_subframe(DCAEncContext *c, int subframe)
1142 int i, band, ss, ch;
1144 /* Subsubframes count */
1145 put_bits(&c->pb, 2, SUBSUBFRAMES -1);
1147 /* Partial subsubframe sample count: dummy */
1148 put_bits(&c->pb, 3, 0);
1150 /* Prediction mode: no ADPCM, in each channel and subband */
1151 for (ch = 0; ch < c->fullband_channels; ch++)
1152 for (band = 0; band < DCAENC_SUBBANDS; band++)
1153 put_bits(&c->pb, 1, !(c->prediction_mode[ch][band] == -1));
1155 /* Prediction VQ address */
1156 for (ch = 0; ch < c->fullband_channels; ch++)
1157 for (band = 0; band < DCAENC_SUBBANDS; band++)
1158 if (c->prediction_mode[ch][band] >= 0)
1159 put_bits(&c->pb, 12, c->prediction_mode[ch][band]);
1161 /* Bit allocation index */
1162 for (ch = 0; ch < c->fullband_channels; ch++) {
1163 if (c->bit_allocation_sel[ch] == 6) {
1164 for (band = 0; band < DCAENC_SUBBANDS; band++) {
1165 put_bits(&c->pb, 5, c->abits[ch][band]);
1168 ff_dca_vlc_enc_alloc(&c->pb, c->abits[ch], DCAENC_SUBBANDS, c->bit_allocation_sel[ch]);
1172 if (SUBSUBFRAMES > 1) {
1173 /* Transition mode: none for each channel and subband */
1174 for (ch = 0; ch < c->fullband_channels; ch++)
1175 for (band = 0; band < DCAENC_SUBBANDS; band++)
1176 put_bits(&c->pb, 1, 0); /* codebook A4 */
1180 for (ch = 0; ch < c->fullband_channels; ch++)
1181 for (band = 0; band < DCAENC_SUBBANDS; band++)
1182 put_bits(&c->pb, 7, c->scale_factor[ch][band]);
1184 /* Joint subband scale factor codebook select: not transmitted */
1185 /* Scale factors for joint subband coding: not transmitted */
1186 /* Stereo down-mix coefficients: not transmitted */
1187 /* Dynamic range coefficient: not transmitted */
1188 /* Stde information CRC check word: not transmitted */
1189 /* VQ encoded high frequency subbands: not transmitted */
1191 /* LFE data: 8 samples and scalefactor */
1192 if (c->lfe_channel) {
1193 for (i = 0; i < DCA_LFE_SAMPLES; i++)
1194 put_bits(&c->pb, 8, quantize_value(c->downsampled_lfe[i], c->lfe_quant) & 0xff);
1195 put_bits(&c->pb, 8, c->lfe_scale_factor);
1198 /* Audio data (subsubframes) */
1199 for (ss = 0; ss < SUBSUBFRAMES ; ss++)
1200 for (ch = 0; ch < c->fullband_channels; ch++)
1201 for (band = 0; band < DCAENC_SUBBANDS; band++)
1202 put_subframe_samples(c, ss, band, ch);
1205 put_bits(&c->pb, 16, 0xffff);
1208 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1209 const AVFrame *frame, int *got_packet_ptr)
1211 DCAEncContext *c = avctx->priv_data;
1212 const int32_t *samples;
1215 if ((ret = ff_alloc_packet2(avctx, avpkt, c->frame_size, 0)) < 0)
1218 samples = (const int32_t *)frame->data[0];
1220 subband_transform(c, samples);
1222 lfe_downsample(c, samples);
1224 calc_masking(c, samples);
1225 if (c->options.adpcm_mode)
1230 shift_history(c, samples);
1232 init_put_bits(&c->pb, avpkt->data, avpkt->size);
1233 fill_in_adpcm_bufer(c);
1234 put_frame_header(c);
1235 put_primary_audio_header(c);
1236 for (i = 0; i < SUBFRAMES; i++)
1240 for (i = put_bits_count(&c->pb); i < 8*c->frame_size; i++)
1241 put_bits(&c->pb, 1, 0);
1243 flush_put_bits(&c->pb);
1245 avpkt->pts = frame->pts;
1246 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1247 avpkt->size = put_bits_count(&c->pb) >> 3;
1248 *got_packet_ptr = 1;
1252 #define DCAENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1254 static const AVOption options[] = {
1255 { "dca_adpcm", "Use ADPCM encoding", offsetof(DCAEncContext, options.adpcm_mode), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DCAENC_FLAGS },
1259 static const AVClass dcaenc_class = {
1260 .class_name = "DCA (DTS Coherent Acoustics)",
1261 .item_name = av_default_item_name,
1263 .version = LIBAVUTIL_VERSION_INT,
1266 static const AVCodecDefault defaults[] = {
1271 AVCodec ff_dca_encoder = {
1273 .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1274 .type = AVMEDIA_TYPE_AUDIO,
1275 .id = AV_CODEC_ID_DTS,
1276 .priv_data_size = sizeof(DCAEncContext),
1277 .init = encode_init,
1278 .close = encode_close,
1279 .encode2 = encode_frame,
1280 .capabilities = AV_CODEC_CAP_EXPERIMENTAL,
1281 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32,
1282 AV_SAMPLE_FMT_NONE },
1283 .supported_samplerates = sample_rates,
1284 .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
1285 AV_CH_LAYOUT_STEREO,
1287 AV_CH_LAYOUT_5POINT0,
1288 AV_CH_LAYOUT_5POINT1,
1290 .defaults = defaults,
1291 .priv_class = &dcaenc_class,