LCOV - code coverage report
Current view: top level - libavcodec - dcaenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 519 603 86.1 %
Date: 2018-05-20 11:54:08 Functions: 34 37 91.9 %

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

Generated by: LCOV version 1.13