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"
36 #define MAX_CHANNELS 6
37 #define DCA_MAX_FRAME_SIZE 16384
38 #define DCA_HEADER_SIZE 13
39 #define DCA_LFE_SAMPLES 8
41 #define DCAENC_SUBBANDS 32
43 #define SUBSUBFRAMES 2
44 #define SUBBAND_SAMPLES (SUBFRAMES * SUBSUBFRAMES * 8)
47 typedef struct DCAEncContext {
51 int fullband_channels;
57 const int32_t *band_interpolation;
58 const int32_t *band_spectrum;
62 const int8_t *channel_order_tab; ///< channel reordering table, lfe and non lfe
64 int32_t history[MAX_CHANNELS][512]; /* This is a circular buffer */
65 int32_t subband[MAX_CHANNELS][DCAENC_SUBBANDS][SUBBAND_SAMPLES];
66 int32_t quantized[MAX_CHANNELS][DCAENC_SUBBANDS][SUBBAND_SAMPLES];
67 int32_t peak_cb[MAX_CHANNELS][DCAENC_SUBBANDS];
68 int32_t downsampled_lfe[DCA_LFE_SAMPLES];
69 int32_t masking_curve_cb[SUBSUBFRAMES][256];
70 int abits[MAX_CHANNELS][DCAENC_SUBBANDS];
71 int scale_factor[MAX_CHANNELS][DCAENC_SUBBANDS];
72 softfloat quant[MAX_CHANNELS][DCAENC_SUBBANDS];
73 int32_t quant_index_sel[MAX_CHANNELS][DCA_CODE_BOOKS];
74 int32_t eff_masking_curve_cb[256];
75 int32_t band_masking_cb[32];
76 int32_t worst_quantization_noise;
77 int32_t worst_noise_ever;
81 static int32_t cos_table[2048];
82 static int32_t band_interpolation[2][512];
83 static int32_t band_spectrum[2][8];
84 static int32_t auf[9][AUBANDS][256];
85 static int32_t cb_to_add[256];
86 static int32_t cb_to_level[2048];
87 static int32_t lfe_fir_64i[512];
89 /* Transfer function of outer and middle ear, Hz -> dB */
90 static double hom(double f)
94 return -3.64 * pow(f1, -0.8)
95 + 6.8 * exp(-0.6 * (f1 - 3.4) * (f1 - 3.4))
96 - 6.0 * exp(-0.15 * (f1 - 8.7) * (f1 - 8.7))
97 - 0.0006 * (f1 * f1) * (f1 * f1);
100 static double gammafilter(int i, double f)
102 double h = (f - fc[i]) / erb[i];
106 return 20 * log10(h);
109 static int encode_init(AVCodecContext *avctx)
111 DCAEncContext *c = avctx->priv_data;
112 uint64_t layout = avctx->channel_layout;
113 int i, j, min_frame_bits;
115 c->fullband_channels = c->channels = avctx->channels;
116 c->lfe_channel = (avctx->channels == 3 || avctx->channels == 6);
117 c->band_interpolation = band_interpolation[1];
118 c->band_spectrum = band_spectrum[1];
119 c->worst_quantization_noise = -2047;
120 c->worst_noise_ever = -2047;
123 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
124 "encoder will guess the layout, but it "
125 "might be incorrect.\n");
126 layout = av_get_default_channel_layout(avctx->channels);
129 case AV_CH_LAYOUT_MONO: c->channel_config = 0; break;
130 case AV_CH_LAYOUT_STEREO: c->channel_config = 2; break;
131 case AV_CH_LAYOUT_2_2: c->channel_config = 8; break;
132 case AV_CH_LAYOUT_5POINT0: c->channel_config = 9; break;
133 case AV_CH_LAYOUT_5POINT1: c->channel_config = 9; break;
135 av_log(avctx, AV_LOG_ERROR, "Unsupported channel layout!\n");
136 return AVERROR_PATCHWELCOME;
139 if (c->lfe_channel) {
140 c->fullband_channels--;
141 c->channel_order_tab = channel_reorder_lfe[c->channel_config];
143 c->channel_order_tab = channel_reorder_nolfe[c->channel_config];
146 for (i = 0; i < MAX_CHANNELS; i++) {
147 for (j = 0; j < DCA_CODE_BOOKS; j++) {
148 c->quant_index_sel[i][j] = ff_dca_quant_index_group_size[j];
152 for (i = 0; i < 9; i++) {
153 if (sample_rates[i] == avctx->sample_rate)
157 return AVERROR(EINVAL);
158 c->samplerate_index = i;
160 if (avctx->bit_rate < 32000 || avctx->bit_rate > 3840000) {
161 av_log(avctx, AV_LOG_ERROR, "Bit rate %"PRId64" not supported.", (int64_t)avctx->bit_rate);
162 return AVERROR(EINVAL);
164 for (i = 0; ff_dca_bit_rates[i] < avctx->bit_rate; i++)
166 c->bitrate_index = i;
167 c->frame_bits = FFALIGN((avctx->bit_rate * 512 + avctx->sample_rate - 1) / avctx->sample_rate, 32);
168 min_frame_bits = 132 + (493 + 28 * 32) * c->fullband_channels + c->lfe_channel * 72;
169 if (c->frame_bits < min_frame_bits || c->frame_bits > (DCA_MAX_FRAME_SIZE << 3))
170 return AVERROR(EINVAL);
172 c->frame_size = (c->frame_bits + 7) / 8;
174 avctx->frame_size = 32 * SUBBAND_SAMPLES;
179 cos_table[0] = 0x7fffffff;
181 cos_table[1024] = -cos_table[0];
182 for (i = 1; i < 512; i++) {
183 cos_table[i] = (int32_t)(0x7fffffff * cos(M_PI * i / 1024));
184 cos_table[1024-i] = -cos_table[i];
185 cos_table[1024+i] = -cos_table[i];
186 cos_table[2048-i] = cos_table[i];
188 for (i = 0; i < 2048; i++) {
189 cb_to_level[i] = (int32_t)(0x7fffffff * ff_exp10(-0.005 * i));
192 for (k = 0; k < 32; k++) {
193 for (j = 0; j < 8; j++) {
194 lfe_fir_64i[64 * j + k] = (int32_t)(0xffffff800000ULL * ff_dca_lfe_fir_64[8 * k + j]);
195 lfe_fir_64i[64 * (7-j) + (63 - k)] = (int32_t)(0xffffff800000ULL * ff_dca_lfe_fir_64[8 * k + j]);
199 for (i = 0; i < 512; i++) {
200 band_interpolation[0][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_perfect[i]);
201 band_interpolation[1][i] = (int32_t)(0x1000000000ULL * ff_dca_fir_32bands_nonperfect[i]);
204 for (i = 0; i < 9; i++) {
205 for (j = 0; j < AUBANDS; j++) {
206 for (k = 0; k < 256; k++) {
207 double freq = sample_rates[i] * (k + 0.5) / 512;
209 auf[i][j][k] = (int32_t)(10 * (hom(freq) + gammafilter(j, freq)));
214 for (i = 0; i < 256; i++) {
215 double add = 1 + ff_exp10(-0.01 * i);
216 cb_to_add[i] = (int32_t)(100 * log10(add));
218 for (j = 0; j < 8; j++) {
220 for (i = 0; i < 512; i++) {
221 double reconst = ff_dca_fir_32bands_perfect[i] * ((i & 64) ? (-1) : 1);
222 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
224 band_spectrum[0][j] = (int32_t)(200 * log10(accum));
226 for (j = 0; j < 8; j++) {
228 for (i = 0; i < 512; i++) {
229 double reconst = ff_dca_fir_32bands_nonperfect[i] * ((i & 64) ? (-1) : 1);
230 accum += reconst * cos(2 * M_PI * (i + 0.5 - 256) * (j + 0.5) / 512);
232 band_spectrum[1][j] = (int32_t)(200 * log10(accum));
238 static inline int32_t cos_t(int x)
240 return cos_table[x & 2047];
243 static inline int32_t sin_t(int x)
245 return cos_t(x - 512);
248 static inline int32_t half32(int32_t a)
253 static inline int32_t mul32(int32_t a, int32_t b)
255 int64_t r = (int64_t)a * b + 0x80000000ULL;
259 static void subband_transform(DCAEncContext *c, const int32_t *input)
261 int ch, subs, i, k, j;
263 for (ch = 0; ch < c->fullband_channels; ch++) {
264 /* History is copied because it is also needed for PSY */
267 const int chi = c->channel_order_tab[ch];
269 memcpy(hist, &c->history[ch][0], 512 * sizeof(int32_t));
271 for (subs = 0; subs < SUBBAND_SAMPLES; subs++) {
276 /* Calculate the convolutions at once */
277 memset(accum, 0, 64 * sizeof(int32_t));
279 for (k = 0, i = hist_start, j = 0;
280 i < 512; k = (k + 1) & 63, i++, j++)
281 accum[k] += mul32(hist[i], c->band_interpolation[j]);
282 for (i = 0; i < hist_start; k = (k + 1) & 63, i++, j++)
283 accum[k] += mul32(hist[i], c->band_interpolation[j]);
285 for (k = 16; k < 32; k++)
286 accum[k] = accum[k] - accum[31 - k];
287 for (k = 32; k < 48; k++)
288 accum[k] = accum[k] + accum[95 - k];
290 for (band = 0; band < 32; band++) {
292 for (i = 16; i < 48; i++) {
293 int s = (2 * band + 1) * (2 * (i + 16) + 1);
294 resp += mul32(accum[i], cos_t(s << 3)) >> 3;
297 c->subband[ch][band][subs] = ((band + 1) & 2) ? -resp : resp;
300 /* Copy in 32 new samples from input */
301 for (i = 0; i < 32; i++)
302 hist[i + hist_start] = input[(subs * 32 + i) * c->channels + chi];
304 hist_start = (hist_start + 32) & 511;
309 static void lfe_downsample(DCAEncContext *c, const int32_t *input)
311 /* FIXME: make 128x LFE downsampling possible */
312 const int lfech = lfe_index[c->channel_config];
318 memcpy(hist, &c->history[c->channels - 1][0], 512 * sizeof(int32_t));
320 for (lfes = 0; lfes < DCA_LFE_SAMPLES; lfes++) {
321 /* Calculate the convolution */
324 for (i = hist_start, j = 0; i < 512; i++, j++)
325 accum += mul32(hist[i], lfe_fir_64i[j]);
326 for (i = 0; i < hist_start; i++, j++)
327 accum += mul32(hist[i], lfe_fir_64i[j]);
329 c->downsampled_lfe[lfes] = accum;
331 /* Copy in 64 new samples from input */
332 for (i = 0; i < 64; i++)
333 hist[i + hist_start] = input[(lfes * 64 + i) * c->channels + lfech];
335 hist_start = (hist_start + 64) & 511;
344 static void fft(const int32_t in[2 * 256], cplx32 out[256])
346 cplx32 buf[256], rin[256], rout[256];
349 /* do two transforms in parallel */
350 for (i = 0; i < 256; i++) {
351 /* Apply the Hann window */
352 rin[i].re = mul32(in[2 * i], 0x3fffffff - (cos_t(8 * i + 2) >> 1));
353 rin[i].im = mul32(in[2 * i + 1], 0x3fffffff - (cos_t(8 * i + 6) >> 1));
356 for (i = 0; i < 256; i++) {
357 buf[i].re = mul32(cos_t(4 * i + 2), rin[i].re)
358 - mul32(sin_t(4 * i + 2), rin[i].im);
359 buf[i].im = mul32(cos_t(4 * i + 2), rin[i].im)
360 + mul32(sin_t(4 * i + 2), rin[i].re);
363 for (j = 256, l = 1; j != 1; j >>= 1, l <<= 1) {
364 for (k = 0; k < 256; k += j) {
365 for (i = k; i < k + j / 2; i++) {
369 sum.re = buf[i].re + buf[i + j / 2].re;
370 sum.im = buf[i].im + buf[i + j / 2].im;
372 diff.re = buf[i].re - buf[i + j / 2].re;
373 diff.im = buf[i].im - buf[i + j / 2].im;
375 buf[i].re = half32(sum.re);
376 buf[i].im = half32(sum.im);
378 buf[i + j / 2].re = mul32(diff.re, cos_t(t))
379 - mul32(diff.im, sin_t(t));
380 buf[i + j / 2].im = mul32(diff.im, cos_t(t))
381 + mul32(diff.re, sin_t(t));
386 for (i = 0; i < 256; i++) {
387 int b = ff_reverse[i];
388 rout[i].re = mul32(buf[b].re, cos_t(4 * i))
389 - mul32(buf[b].im, sin_t(4 * i));
390 rout[i].im = mul32(buf[b].im, cos_t(4 * i))
391 + mul32(buf[b].re, sin_t(4 * i));
393 for (i = 0; i < 256; i++) {
394 /* separate the results of the two transforms */
397 o1.re = rout[i].re - rout[255 - i].re;
398 o1.im = rout[i].im + rout[255 - i].im;
400 o2.re = rout[i].im - rout[255 - i].im;
401 o2.im = -rout[i].re - rout[255 - i].re;
403 /* combine them into one long transform */
404 out[i].re = mul32( o1.re + o2.re, cos_t(2 * i + 1))
405 + mul32( o1.im - o2.im, sin_t(2 * i + 1));
406 out[i].im = mul32( o1.im + o2.im, cos_t(2 * i + 1))
407 + mul32(-o1.re + o2.re, sin_t(2 * i + 1));
411 static int32_t get_cb(int32_t in)
418 for (i = 1024; i > 0; i >>= 1) {
419 if (cb_to_level[i + res] >= in)
425 static int32_t add_cb(int32_t a, int32_t b)
428 FFSWAP(int32_t, a, b);
432 return a + cb_to_add[a - b];
435 static void adjust_jnd(int samplerate_index,
436 const int32_t in[512], int32_t out_cb[256])
440 int32_t out_cb_unnorm[256];
442 const int32_t ca_cb = -1114;
443 const int32_t cs_cb = 928;
448 for (j = 0; j < 256; j++) {
449 power[j] = add_cb(get_cb(out[j].re), get_cb(out[j].im));
450 out_cb_unnorm[j] = -2047; /* and can only grow */
453 for (i = 0; i < AUBANDS; i++) {
454 denom = ca_cb; /* and can only grow */
455 for (j = 0; j < 256; j++)
456 denom = add_cb(denom, power[j] + auf[samplerate_index][i][j]);
457 for (j = 0; j < 256; j++)
458 out_cb_unnorm[j] = add_cb(out_cb_unnorm[j],
459 -denom + auf[samplerate_index][i][j]);
462 for (j = 0; j < 256; j++)
463 out_cb[j] = add_cb(out_cb[j], -out_cb_unnorm[j] - ca_cb - cs_cb);
466 typedef void (*walk_band_t)(DCAEncContext *c, int band1, int band2, int f,
467 int32_t spectrum1, int32_t spectrum2, int channel,
470 static void walk_band_low(DCAEncContext *c, int band, int channel,
471 walk_band_t walk, int32_t *arg)
476 for (f = 0; f < 4; f++)
477 walk(c, 0, 0, f, 0, -2047, channel, arg);
479 for (f = 0; f < 8; f++)
480 walk(c, band, band - 1, 8 * band - 4 + f,
481 c->band_spectrum[7 - f], c->band_spectrum[f], channel, arg);
485 static void walk_band_high(DCAEncContext *c, int band, int channel,
486 walk_band_t walk, int32_t *arg)
491 for (f = 0; f < 4; f++)
492 walk(c, 31, 31, 256 - 4 + f, 0, -2047, channel, arg);
494 for (f = 0; f < 8; f++)
495 walk(c, band, band + 1, 8 * band + 4 + f,
496 c->band_spectrum[f], c->band_spectrum[7 - f], channel, arg);
500 static void update_band_masking(DCAEncContext *c, int band1, int band2,
501 int f, int32_t spectrum1, int32_t spectrum2,
502 int channel, int32_t * arg)
504 int32_t value = c->eff_masking_curve_cb[f] - spectrum1;
506 if (value < c->band_masking_cb[band1])
507 c->band_masking_cb[band1] = value;
510 static void calc_masking(DCAEncContext *c, const int32_t *input)
512 int i, k, band, ch, ssf;
515 for (i = 0; i < 256; i++)
516 for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
517 c->masking_curve_cb[ssf][i] = -2047;
519 for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
520 for (ch = 0; ch < c->fullband_channels; ch++) {
521 const int chi = c->channel_order_tab[ch];
523 for (i = 0, k = 128 + 256 * ssf; k < 512; i++, k++)
524 data[i] = c->history[ch][k];
525 for (k -= 512; i < 512; i++, k++)
526 data[i] = input[k * c->channels + chi];
527 adjust_jnd(c->samplerate_index, data, c->masking_curve_cb[ssf]);
529 for (i = 0; i < 256; i++) {
532 for (ssf = 0; ssf < SUBSUBFRAMES; ssf++)
533 if (c->masking_curve_cb[ssf][i] < m)
534 m = c->masking_curve_cb[ssf][i];
535 c->eff_masking_curve_cb[i] = m;
538 for (band = 0; band < 32; band++) {
539 c->band_masking_cb[band] = 2048;
540 walk_band_low(c, band, 0, update_band_masking, NULL);
541 walk_band_high(c, band, 0, update_band_masking, NULL);
545 static void find_peaks(DCAEncContext *c)
549 for (ch = 0; ch < c->fullband_channels; ch++)
550 for (band = 0; band < 32; band++) {
554 for (sample = 0; sample < SUBBAND_SAMPLES; sample++) {
555 int32_t s = abs(c->subband[ch][band][sample]);
559 c->peak_cb[ch][band] = get_cb(m);
562 if (c->lfe_channel) {
566 for (sample = 0; sample < DCA_LFE_SAMPLES; sample++)
567 if (m < abs(c->downsampled_lfe[sample]))
568 m = abs(c->downsampled_lfe[sample]);
569 c->lfe_peak_cb = get_cb(m);
573 static const int snr_fudge = 128;
574 #define USED_1ABITS 1
575 #define USED_NABITS 2
576 #define USED_26ABITS 4
578 static int32_t quantize_value(int32_t value, softfloat quant)
580 int32_t offset = 1 << (quant.e - 1);
582 value = mul32(value, quant.m) + offset;
583 value = value >> quant.e;
587 static int calc_one_scale(int32_t peak_cb, int abits, softfloat *quant)
590 int our_nscale, try_remove;
593 av_assert0(peak_cb <= 0);
594 av_assert0(peak_cb >= -2047);
597 peak = cb_to_level[-peak_cb];
599 for (try_remove = 64; try_remove > 0; try_remove >>= 1) {
600 if (scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e <= 17)
602 our_quant.m = mul32(scalefactor_inv[our_nscale - try_remove].m, stepsize_inv[abits].m);
603 our_quant.e = scalefactor_inv[our_nscale - try_remove].e + stepsize_inv[abits].e - 17;
604 if ((ff_dca_quant_levels[abits] - 1) / 2 < quantize_value(peak, our_quant))
606 our_nscale -= try_remove;
609 if (our_nscale >= 125)
612 quant->m = mul32(scalefactor_inv[our_nscale].m, stepsize_inv[abits].m);
613 quant->e = scalefactor_inv[our_nscale].e + stepsize_inv[abits].e - 17;
614 av_assert0((ff_dca_quant_levels[abits] - 1) / 2 >= quantize_value(peak, *quant));
619 static void quantize_all(DCAEncContext *c)
621 int sample, band, ch;
623 for (ch = 0; ch < c->fullband_channels; ch++)
624 for (band = 0; band < 32; band++)
625 for (sample = 0; sample < SUBBAND_SAMPLES; sample++)
626 c->quantized[ch][band][sample] = quantize_value(c->subband[ch][band][sample], c->quant[ch][band]);
629 static void accumulate_huff_bit_consumption(int abits, int32_t *quantized, uint32_t *result)
631 uint8_t sel, id = abits - 1;
632 for (sel = 0; sel < ff_dca_quant_index_group_size[id]; sel++)
633 result[sel] += ff_dca_vlc_calc_quant_bits(quantized, SUBBAND_SAMPLES, sel, id);
636 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])
639 uint32_t best_sel_bits[DCA_CODE_BOOKS];
640 int32_t best_sel_id[DCA_CODE_BOOKS];
641 uint32_t t, bits = 0;
643 for (i = 0; i < DCA_CODE_BOOKS; i++) {
645 av_assert0(!((!!vlc_bits[i][0]) ^ (!!clc_bits[i])));
646 if (vlc_bits[i][0] == 0) {
647 /* do not transmit adjustment index for empty codebooks */
648 res[i] = ff_dca_quant_index_group_size[i];
653 best_sel_bits[i] = vlc_bits[i][0];
655 for (sel = 0; sel < ff_dca_quant_index_group_size[i]; sel++) {
656 if (best_sel_bits[i] > vlc_bits[i][sel] && vlc_bits[i][sel]) {
657 best_sel_bits[i] = vlc_bits[i][sel];
658 best_sel_id[i] = sel;
662 /* 2 bits to transmit scale factor adjustment index */
663 t = best_sel_bits[i] + 2;
664 if (t < clc_bits[i]) {
665 res[i] = best_sel_id[i];
668 res[i] = ff_dca_quant_index_group_size[i];
675 static int init_quantization_noise(DCAEncContext *c, int noise)
677 int ch, band, ret = 0;
678 uint32_t huff_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS][7];
679 uint32_t clc_bit_count_accum[MAX_CHANNELS][DCA_CODE_BOOKS];
680 uint32_t bits_counter = 0;
682 c->consumed_bits = 132 + 493 * c->fullband_channels;
684 c->consumed_bits += 72;
686 /* attempt to guess the bit distribution based on the prevoius frame */
687 for (ch = 0; ch < c->fullband_channels; ch++) {
688 for (band = 0; band < 32; band++) {
689 int snr_cb = c->peak_cb[ch][band] - c->band_masking_cb[band] - noise;
691 if (snr_cb >= 1312) {
692 c->abits[ch][band] = 26;
694 } else if (snr_cb >= 222) {
695 c->abits[ch][band] = 8 + mul32(snr_cb - 222, 69000000);
697 } else if (snr_cb >= 0) {
698 c->abits[ch][band] = 2 + mul32(snr_cb, 106000000);
701 c->abits[ch][band] = 1;
707 /* Recalc scale_factor each time to get bits consumption in case of Huffman coding.
708 It is suboptimal solution */
709 /* TODO: May be cache scaled values */
710 for (ch = 0; ch < c->fullband_channels; ch++) {
711 for (band = 0; band < 32; band++) {
712 c->scale_factor[ch][band] = calc_one_scale(c->peak_cb[ch][band],
714 &c->quant[ch][band]);
719 memset(huff_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * 7 * sizeof(uint32_t));
720 memset(clc_bit_count_accum, 0, MAX_CHANNELS * DCA_CODE_BOOKS * sizeof(uint32_t));
721 for (ch = 0; ch < c->fullband_channels; ch++) {
722 for (band = 0; band < 32; band++) {
723 if (c->abits[ch][band] && c->abits[ch][band] <= DCA_CODE_BOOKS) {
724 accumulate_huff_bit_consumption(c->abits[ch][band], c->quantized[ch][band], huff_bit_count_accum[ch][c->abits[ch][band] - 1]);
725 clc_bit_count_accum[ch][c->abits[ch][band] - 1] += bit_consumption[c->abits[ch][band]];
727 bits_counter += bit_consumption[c->abits[ch][band]];
732 for (ch = 0; ch < c->fullband_channels; ch++) {
733 bits_counter += set_best_code(huff_bit_count_accum[ch], clc_bit_count_accum[ch], c->quant_index_sel[ch]);
736 c->consumed_bits += bits_counter;
741 static void assign_bits(DCAEncContext *c)
743 /* Find the bounds where the binary search should work */
747 init_quantization_noise(c, c->worst_quantization_noise);
748 low = high = c->worst_quantization_noise;
749 if (c->consumed_bits > c->frame_bits) {
750 while (c->consumed_bits > c->frame_bits) {
751 av_assert0(used_abits != USED_1ABITS);
754 used_abits = init_quantization_noise(c, high);
757 while (c->consumed_bits <= c->frame_bits) {
759 if (used_abits == USED_26ABITS)
760 goto out; /* The requested bitrate is too high, pad with zeros */
762 used_abits = init_quantization_noise(c, low);
766 /* Now do a binary search between low and high to see what fits */
767 for (down = snr_fudge >> 1; down; down >>= 1) {
768 init_quantization_noise(c, high - down);
769 if (c->consumed_bits <= c->frame_bits)
772 init_quantization_noise(c, high);
774 c->worst_quantization_noise = high;
775 if (high > c->worst_noise_ever)
776 c->worst_noise_ever = high;
779 static void shift_history(DCAEncContext *c, const int32_t *input)
783 for (k = 0; k < 512; k++)
784 for (ch = 0; ch < c->channels; ch++) {
785 const int chi = c->channel_order_tab[ch];
787 c->history[ch][k] = input[k * c->channels + chi];
791 static void calc_lfe_scales(DCAEncContext *c)
794 c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);
797 static void put_frame_header(DCAEncContext *c)
800 put_bits(&c->pb, 16, 0x7ffe);
801 put_bits(&c->pb, 16, 0x8001);
803 /* Frame type: normal */
804 put_bits(&c->pb, 1, 1);
806 /* Deficit sample count: none */
807 put_bits(&c->pb, 5, 31);
809 /* CRC is not present */
810 put_bits(&c->pb, 1, 0);
812 /* Number of PCM sample blocks */
813 put_bits(&c->pb, 7, SUBBAND_SAMPLES - 1);
815 /* Primary frame byte size */
816 put_bits(&c->pb, 14, c->frame_size - 1);
818 /* Audio channel arrangement */
819 put_bits(&c->pb, 6, c->channel_config);
821 /* Core audio sampling frequency */
822 put_bits(&c->pb, 4, bitstream_sfreq[c->samplerate_index]);
824 /* Transmission bit rate */
825 put_bits(&c->pb, 5, c->bitrate_index);
827 /* Embedded down mix: disabled */
828 put_bits(&c->pb, 1, 0);
830 /* Embedded dynamic range flag: not present */
831 put_bits(&c->pb, 1, 0);
833 /* Embedded time stamp flag: not present */
834 put_bits(&c->pb, 1, 0);
836 /* Auxiliary data flag: not present */
837 put_bits(&c->pb, 1, 0);
839 /* HDCD source: no */
840 put_bits(&c->pb, 1, 0);
842 /* Extension audio ID: N/A */
843 put_bits(&c->pb, 3, 0);
845 /* Extended audio data: not present */
846 put_bits(&c->pb, 1, 0);
848 /* Audio sync word insertion flag: after each sub-frame */
849 put_bits(&c->pb, 1, 0);
851 /* Low frequency effects flag: not present or 64x subsampling */
852 put_bits(&c->pb, 2, c->lfe_channel ? 2 : 0);
854 /* Predictor history switch flag: on */
855 put_bits(&c->pb, 1, 1);
858 /* Multirate interpolator switch: non-perfect reconstruction */
859 put_bits(&c->pb, 1, 0);
861 /* Encoder software revision: 7 */
862 put_bits(&c->pb, 4, 7);
864 /* Copy history: 0 */
865 put_bits(&c->pb, 2, 0);
867 /* Source PCM resolution: 16 bits, not DTS ES */
868 put_bits(&c->pb, 3, 0);
870 /* Front sum/difference coding: no */
871 put_bits(&c->pb, 1, 0);
873 /* Surrounds sum/difference coding: no */
874 put_bits(&c->pb, 1, 0);
876 /* Dialog normalization: 0 dB */
877 put_bits(&c->pb, 4, 0);
880 static void put_primary_audio_header(DCAEncContext *c)
883 /* Number of subframes */
884 put_bits(&c->pb, 4, SUBFRAMES - 1);
886 /* Number of primary audio channels */
887 put_bits(&c->pb, 3, c->fullband_channels - 1);
889 /* Subband activity count */
890 for (ch = 0; ch < c->fullband_channels; ch++)
891 put_bits(&c->pb, 5, DCAENC_SUBBANDS - 2);
893 /* High frequency VQ start subband */
894 for (ch = 0; ch < c->fullband_channels; ch++)
895 put_bits(&c->pb, 5, DCAENC_SUBBANDS - 1);
897 /* Joint intensity coding index: 0, 0 */
898 for (ch = 0; ch < c->fullband_channels; ch++)
899 put_bits(&c->pb, 3, 0);
901 /* Transient mode codebook: A4, A4 (arbitrary) */
902 for (ch = 0; ch < c->fullband_channels; ch++)
903 put_bits(&c->pb, 2, 0);
905 /* Scale factor code book: 7 bit linear, 7-bit sqrt table (for each channel) */
906 for (ch = 0; ch < c->fullband_channels; ch++)
907 put_bits(&c->pb, 3, 6);
909 /* Bit allocation quantizer select: linear 5-bit */
910 for (ch = 0; ch < c->fullband_channels; ch++)
911 put_bits(&c->pb, 3, 6);
913 /* Quantization index codebook select */
914 for (i = 0; i < DCA_CODE_BOOKS; i++)
915 for (ch = 0; ch < c->fullband_channels; ch++)
916 put_bits(&c->pb, ff_dca_quant_index_sel_nbits[i], c->quant_index_sel[ch][i]);
918 /* Scale factor adjustment index: transmitted in case of Huffman coding */
919 for (i = 0; i < DCA_CODE_BOOKS; i++)
920 for (ch = 0; ch < c->fullband_channels; ch++)
921 if (c->quant_index_sel[ch][i] < ff_dca_quant_index_group_size[i])
922 put_bits(&c->pb, 2, 0);
924 /* Audio header CRC check word: not transmitted */
927 static void put_subframe_samples(DCAEncContext *c, int ss, int band, int ch)
929 int i, j, sum, bits, sel;
930 if (c->abits[ch][band] <= DCA_CODE_BOOKS) {
931 av_assert0(c->abits[ch][band] > 0);
932 sel = c->quant_index_sel[ch][c->abits[ch][band] - 1];
934 if (sel < ff_dca_quant_index_group_size[c->abits[ch][band] - 1]) {
935 ff_dca_vlc_enc_quant(&c->pb, &c->quantized[ch][band][ss * 8], 8, sel, c->abits[ch][band] - 1);
940 if (c->abits[ch][band] <= 7) {
941 for (i = 0; i < 8; i += 4) {
943 for (j = 3; j >= 0; j--) {
944 sum *= ff_dca_quant_levels[c->abits[ch][band]];
945 sum += c->quantized[ch][band][ss * 8 + i + j];
946 sum += (ff_dca_quant_levels[c->abits[ch][band]] - 1) / 2;
948 put_bits(&c->pb, bit_consumption[c->abits[ch][band]] / 4, sum);
954 for (i = 0; i < 8; i++) {
955 bits = bit_consumption[c->abits[ch][band]] / 16;
956 put_sbits(&c->pb, bits, c->quantized[ch][band][ss * 8 + i]);
960 static void put_subframe(DCAEncContext *c, int subframe)
964 /* Subsubframes count */
965 put_bits(&c->pb, 2, SUBSUBFRAMES -1);
967 /* Partial subsubframe sample count: dummy */
968 put_bits(&c->pb, 3, 0);
970 /* Prediction mode: no ADPCM, in each channel and subband */
971 for (ch = 0; ch < c->fullband_channels; ch++)
972 for (band = 0; band < DCAENC_SUBBANDS; band++)
973 put_bits(&c->pb, 1, 0);
975 /* Prediction VQ address: not transmitted */
976 /* Bit allocation index */
977 for (ch = 0; ch < c->fullband_channels; ch++)
978 for (band = 0; band < DCAENC_SUBBANDS; band++)
979 put_bits(&c->pb, 5, c->abits[ch][band]);
981 if (SUBSUBFRAMES > 1) {
982 /* Transition mode: none for each channel and subband */
983 for (ch = 0; ch < c->fullband_channels; ch++)
984 for (band = 0; band < DCAENC_SUBBANDS; band++)
985 put_bits(&c->pb, 1, 0); /* codebook A4 */
989 for (ch = 0; ch < c->fullband_channels; ch++)
990 for (band = 0; band < DCAENC_SUBBANDS; band++)
991 put_bits(&c->pb, 7, c->scale_factor[ch][band]);
993 /* Joint subband scale factor codebook select: not transmitted */
994 /* Scale factors for joint subband coding: not transmitted */
995 /* Stereo down-mix coefficients: not transmitted */
996 /* Dynamic range coefficient: not transmitted */
997 /* Stde information CRC check word: not transmitted */
998 /* VQ encoded high frequency subbands: not transmitted */
1000 /* LFE data: 8 samples and scalefactor */
1001 if (c->lfe_channel) {
1002 for (i = 0; i < DCA_LFE_SAMPLES; i++)
1003 put_bits(&c->pb, 8, quantize_value(c->downsampled_lfe[i], c->lfe_quant) & 0xff);
1004 put_bits(&c->pb, 8, c->lfe_scale_factor);
1007 /* Audio data (subsubframes) */
1008 for (ss = 0; ss < SUBSUBFRAMES ; ss++)
1009 for (ch = 0; ch < c->fullband_channels; ch++)
1010 for (band = 0; band < DCAENC_SUBBANDS; band++)
1011 put_subframe_samples(c, ss, band, ch);
1014 put_bits(&c->pb, 16, 0xffff);
1017 static int encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1018 const AVFrame *frame, int *got_packet_ptr)
1020 DCAEncContext *c = avctx->priv_data;
1021 const int32_t *samples;
1024 if ((ret = ff_alloc_packet2(avctx, avpkt, c->frame_size, 0)) < 0)
1027 samples = (const int32_t *)frame->data[0];
1029 subband_transform(c, samples);
1031 lfe_downsample(c, samples);
1033 calc_masking(c, samples);
1037 shift_history(c, samples);
1039 init_put_bits(&c->pb, avpkt->data, avpkt->size);
1040 put_frame_header(c);
1041 put_primary_audio_header(c);
1042 for (i = 0; i < SUBFRAMES; i++)
1046 for (i = put_bits_count(&c->pb); i < 8*c->frame_size; i++)
1047 put_bits(&c->pb, 1, 0);
1049 flush_put_bits(&c->pb);
1051 avpkt->pts = frame->pts;
1052 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1053 avpkt->size = put_bits_count(&c->pb) >> 3;
1054 *got_packet_ptr = 1;
1058 static const AVCodecDefault defaults[] = {
1063 AVCodec ff_dca_encoder = {
1065 .long_name = NULL_IF_CONFIG_SMALL("DCA (DTS Coherent Acoustics)"),
1066 .type = AVMEDIA_TYPE_AUDIO,
1067 .id = AV_CODEC_ID_DTS,
1068 .priv_data_size = sizeof(DCAEncContext),
1069 .init = encode_init,
1070 .encode2 = encode_frame,
1071 .capabilities = AV_CODEC_CAP_EXPERIMENTAL,
1072 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32,
1073 AV_SAMPLE_FMT_NONE },
1074 .supported_samplerates = sample_rates,
1075 .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_MONO,
1076 AV_CH_LAYOUT_STEREO,
1078 AV_CH_LAYOUT_5POINT0,
1079 AV_CH_LAYOUT_5POINT1,
1081 .defaults = defaults,