• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavcodec/aacpsy.c

Go to the documentation of this file.
00001 /*
00002  * AAC encoder psychoacoustic model
00003  * Copyright (C) 2008 Konstantin Shishkov
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00027 #include "avcodec.h"
00028 #include "aactab.h"
00029 #include "psymodel.h"
00030 
00031 /***********************************
00032  *              TODOs:
00033  * try other bitrate controlling mechanism (maybe use ratecontrol.c?)
00034  * control quality for quality-based output
00035  **********************************/
00036 
00041 #define PSY_3GPP_THR_SPREAD_HI   1.5f // spreading factor for low-to-hi threshold spreading  (15 dB/Bark)
00042 #define PSY_3GPP_THR_SPREAD_LOW  3.0f // spreading factor for hi-to-low threshold spreading  (30 dB/Bark)
00043 /* spreading factor for low-to-hi energy spreading, long block, > 22kbps/channel (20dB/Bark) */
00044 #define PSY_3GPP_EN_SPREAD_HI_L1 2.0f
00045 /* spreading factor for low-to-hi energy spreading, long block, <= 22kbps/channel (15dB/Bark) */
00046 #define PSY_3GPP_EN_SPREAD_HI_L2 1.5f
00047 /* spreading factor for low-to-hi energy spreading, short block (15 dB/Bark) */
00048 #define PSY_3GPP_EN_SPREAD_HI_S  1.5f
00049 /* spreading factor for hi-to-low energy spreading, long block (30dB/Bark) */
00050 #define PSY_3GPP_EN_SPREAD_LOW_L 3.0f
00051 /* spreading factor for hi-to-low energy spreading, short block (20dB/Bark) */
00052 #define PSY_3GPP_EN_SPREAD_LOW_S 2.0f
00053 
00054 #define PSY_3GPP_RPEMIN      0.01f
00055 #define PSY_3GPP_RPELEV      2.0f
00056 
00057 #define PSY_3GPP_C1          3.0f           /* log2(8) */
00058 #define PSY_3GPP_C2          1.3219281f     /* log2(2.5) */
00059 #define PSY_3GPP_C3          0.55935729f    /* 1 - C2 / C1 */
00060 
00061 #define PSY_SNR_1DB          7.9432821e-1f  /* -1dB */
00062 #define PSY_SNR_25DB         3.1622776e-3f  /* -25dB */
00063 
00064 #define PSY_3GPP_SAVE_SLOPE_L  -0.46666667f
00065 #define PSY_3GPP_SAVE_SLOPE_S  -0.36363637f
00066 #define PSY_3GPP_SAVE_ADD_L    -0.84285712f
00067 #define PSY_3GPP_SAVE_ADD_S    -0.75f
00068 #define PSY_3GPP_SPEND_SLOPE_L  0.66666669f
00069 #define PSY_3GPP_SPEND_SLOPE_S  0.81818181f
00070 #define PSY_3GPP_SPEND_ADD_L   -0.35f
00071 #define PSY_3GPP_SPEND_ADD_S   -0.26111111f
00072 #define PSY_3GPP_CLIP_LO_L      0.2f
00073 #define PSY_3GPP_CLIP_LO_S      0.2f
00074 #define PSY_3GPP_CLIP_HI_L      0.95f
00075 #define PSY_3GPP_CLIP_HI_S      0.75f
00076 
00077 #define PSY_3GPP_AH_THR_LONG    0.5f
00078 #define PSY_3GPP_AH_THR_SHORT   0.63f
00079 
00080 enum {
00081     PSY_3GPP_AH_NONE,
00082     PSY_3GPP_AH_INACTIVE,
00083     PSY_3GPP_AH_ACTIVE
00084 };
00085 
00086 #define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f)
00087 
00088 /* LAME psy model constants */
00089 #define PSY_LAME_FIR_LEN 21         ///< LAME psy model FIR order
00090 #define AAC_BLOCK_SIZE_LONG 1024    ///< long block size
00091 #define AAC_BLOCK_SIZE_SHORT 128    ///< short block size
00092 #define AAC_NUM_BLOCKS_SHORT 8      ///< number of blocks in a short sequence
00093 #define PSY_LAME_NUM_SUBBLOCKS 3    ///< Number of sub-blocks in each short block
00094 
00102 typedef struct AacPsyBand{
00103     float energy;       
00104     float thr;          
00105     float thr_quiet;    
00106     float nz_lines;     
00107     float active_lines; 
00108     float pe;           
00109     float pe_const;     
00110     float norm_fac;     
00111     int   avoid_holes;  
00112 }AacPsyBand;
00113 
00117 typedef struct AacPsyChannel{
00118     AacPsyBand band[128];               
00119     AacPsyBand prev_band[128];          
00120 
00121     float       win_energy;              
00122     float       iir_state[2];            
00123     uint8_t     next_grouping;           
00124     enum WindowSequence next_window_seq; 
00125     /* LAME psy model specific members */
00126     float attack_threshold;              
00127     float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
00128     int   prev_attack;                   
00129 }AacPsyChannel;
00130 
00134 typedef struct AacPsyCoeffs{
00135     float ath;           
00136     float barks;         
00137     float spread_low[2]; 
00138     float spread_hi [2]; 
00139     float min_snr;       
00140 }AacPsyCoeffs;
00141 
00145 typedef struct AacPsyContext{
00146     int chan_bitrate;     
00147     int frame_bits;       
00148     int fill_level;       
00149     struct {
00150         float min;        
00151         float max;        
00152         float previous;   
00153         float correction; 
00154     } pe;
00155     AacPsyCoeffs psy_coef[2][64];
00156     AacPsyChannel *ch;
00157 }AacPsyContext;
00158 
00162 typedef struct {
00163     int   quality;  
00164      /* This is overloaded to be both kbps per channel in ABR mode, and
00165       * requested quality in constant quality mode.
00166       */
00167     float st_lrm;   
00168 } PsyLamePreset;
00169 
00173 static const PsyLamePreset psy_abr_map[] = {
00174 /* TODO: Tuning. These were taken from LAME. */
00175 /* kbps/ch st_lrm   */
00176     {  8,  6.60},
00177     { 16,  6.60},
00178     { 24,  6.60},
00179     { 32,  6.60},
00180     { 40,  6.60},
00181     { 48,  6.60},
00182     { 56,  6.60},
00183     { 64,  6.40},
00184     { 80,  6.00},
00185     { 96,  5.60},
00186     {112,  5.20},
00187     {128,  5.20},
00188     {160,  5.20}
00189 };
00190 
00194 static const PsyLamePreset psy_vbr_map[] = {
00195 /* vbr_q  st_lrm    */
00196     { 0,  4.20},
00197     { 1,  4.20},
00198     { 2,  4.20},
00199     { 3,  4.20},
00200     { 4,  4.20},
00201     { 5,  4.20},
00202     { 6,  4.20},
00203     { 7,  4.20},
00204     { 8,  4.20},
00205     { 9,  4.20},
00206     {10,  4.20}
00207 };
00208 
00212 static const float psy_fir_coeffs[] = {
00213     -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
00214     -3.36639e-17 * 2, -0.0438162 * 2,  -1.54175e-17 * 2, 0.0931738 * 2,
00215     -5.52212e-17 * 2, -0.313819 * 2
00216 };
00217 
00221 static float lame_calc_attack_threshold(int bitrate)
00222 {
00223     /* Assume max bitrate to start with */
00224     int lower_range = 12, upper_range = 12;
00225     int lower_range_kbps = psy_abr_map[12].quality;
00226     int upper_range_kbps = psy_abr_map[12].quality;
00227     int i;
00228 
00229     /* Determine which bitrates the value specified falls between.
00230      * If the loop ends without breaking our above assumption of 320kbps was correct.
00231      */
00232     for (i = 1; i < 13; i++) {
00233         if (FFMAX(bitrate, psy_abr_map[i].quality) != bitrate) {
00234             upper_range = i;
00235             upper_range_kbps = psy_abr_map[i    ].quality;
00236             lower_range = i - 1;
00237             lower_range_kbps = psy_abr_map[i - 1].quality;
00238             break; /* Upper range found */
00239         }
00240     }
00241 
00242     /* Determine which range the value specified is closer to */
00243     if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
00244         return psy_abr_map[lower_range].st_lrm;
00245     return psy_abr_map[upper_range].st_lrm;
00246 }
00247 
00251 static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
00252     int i, j;
00253 
00254     for (i = 0; i < avctx->channels; i++) {
00255         AacPsyChannel *pch = &ctx->ch[i];
00256 
00257         if (avctx->flags & CODEC_FLAG_QSCALE)
00258             pch->attack_threshold = psy_vbr_map[avctx->global_quality / FF_QP2LAMBDA].st_lrm;
00259         else
00260             pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->channels / 1000);
00261 
00262         for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
00263             pch->prev_energy_subshort[j] = 10.0f;
00264     }
00265 }
00266 
00270 static av_cold float calc_bark(float f)
00271 {
00272     return 13.3f * atanf(0.00076f * f) + 3.5f * atanf((f / 7500.0f) * (f / 7500.0f));
00273 }
00274 
00275 #define ATH_ADD 4
00276 
00280 static av_cold float ath(float f, float add)
00281 {
00282     f /= 1000.0f;
00283     return    3.64 * pow(f, -0.8)
00284             - 6.8  * exp(-0.6  * (f - 3.4) * (f - 3.4))
00285             + 6.0  * exp(-0.15 * (f - 8.7) * (f - 8.7))
00286             + (0.6 + 0.04 * add) * 0.001 * f * f * f * f;
00287 }
00288 
00289 static av_cold int psy_3gpp_init(FFPsyContext *ctx) {
00290     AacPsyContext *pctx;
00291     float bark;
00292     int i, j, g, start;
00293     float prev, minscale, minath, minsnr, pe_min;
00294     const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;
00295     const int bandwidth    = ctx->avctx->cutoff ? ctx->avctx->cutoff : ctx->avctx->sample_rate / 2;
00296     const float num_bark   = calc_bark((float)bandwidth);
00297 
00298     ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
00299     pctx = (AacPsyContext*) ctx->model_priv_data;
00300 
00301     pctx->chan_bitrate = chan_bitrate;
00302     pctx->frame_bits   = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;
00303     pctx->pe.min       =  8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
00304     pctx->pe.max       = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
00305     ctx->bitres.size   = 6144 - pctx->frame_bits;
00306     ctx->bitres.size  -= ctx->bitres.size % 8;
00307     pctx->fill_level   = ctx->bitres.size;
00308     minath = ath(3410, ATH_ADD);
00309     for (j = 0; j < 2; j++) {
00310         AacPsyCoeffs *coeffs = pctx->psy_coef[j];
00311         const uint8_t *band_sizes = ctx->bands[j];
00312         float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
00313         float avg_chan_bits = chan_bitrate / ctx->avctx->sample_rate * (j ? 128.0f : 1024.0f);
00314         /* reference encoder uses 2.4% here instead of 60% like the spec says */
00315         float bark_pe = 0.024f * PSY_3GPP_BITS_TO_PE(avg_chan_bits) / num_bark;
00316         float en_spread_low = j ? PSY_3GPP_EN_SPREAD_LOW_S : PSY_3GPP_EN_SPREAD_LOW_L;
00317         /* High energy spreading for long blocks <= 22kbps/channel and short blocks are the same. */
00318         float en_spread_hi  = (j || (chan_bitrate <= 22.0f)) ? PSY_3GPP_EN_SPREAD_HI_S : PSY_3GPP_EN_SPREAD_HI_L1;
00319 
00320         i = 0;
00321         prev = 0.0;
00322         for (g = 0; g < ctx->num_bands[j]; g++) {
00323             i += band_sizes[g];
00324             bark = calc_bark((i-1) * line_to_frequency);
00325             coeffs[g].barks = (bark + prev) / 2.0;
00326             prev = bark;
00327         }
00328         for (g = 0; g < ctx->num_bands[j] - 1; g++) {
00329             AacPsyCoeffs *coeff = &coeffs[g];
00330             float bark_width = coeffs[g+1].barks - coeffs->barks;
00331             coeff->spread_low[0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_LOW);
00332             coeff->spread_hi [0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_HI);
00333             coeff->spread_low[1] = pow(10.0, -bark_width * en_spread_low);
00334             coeff->spread_hi [1] = pow(10.0, -bark_width * en_spread_hi);
00335             pe_min = bark_pe * bark_width;
00336             minsnr = pow(2.0f, pe_min / band_sizes[g]) - 1.5f;
00337             coeff->min_snr = av_clipf(1.0f / minsnr, PSY_SNR_25DB, PSY_SNR_1DB);
00338         }
00339         start = 0;
00340         for (g = 0; g < ctx->num_bands[j]; g++) {
00341             minscale = ath(start * line_to_frequency, ATH_ADD);
00342             for (i = 1; i < band_sizes[g]; i++)
00343                 minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
00344             coeffs[g].ath = minscale - minath;
00345             start += band_sizes[g];
00346         }
00347     }
00348 
00349     pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);
00350 
00351     lame_window_init(pctx, ctx->avctx);
00352 
00353     return 0;
00354 }
00355 
00359 static float iir_filter(int in, float state[2])
00360 {
00361     float ret;
00362 
00363     ret = 0.7548f * (in - state[0]) + 0.5095f * state[1];
00364     state[0] = in;
00365     state[1] = ret;
00366     return ret;
00367 }
00368 
00372 static const uint8_t window_grouping[9] = {
00373     0xB6, 0x6C, 0xD8, 0xB2, 0x66, 0xC6, 0x96, 0x36, 0x36
00374 };
00375 
00380 static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
00381                                                  const int16_t *audio,
00382                                                  const int16_t *la,
00383                                                  int channel, int prev_type)
00384 {
00385     int i, j;
00386     int br               = ctx->avctx->bit_rate / ctx->avctx->channels;
00387     int attack_ratio     = br <= 16000 ? 18 : 10;
00388     AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
00389     AacPsyChannel *pch  = &pctx->ch[channel];
00390     uint8_t grouping     = 0;
00391     int next_type        = pch->next_window_seq;
00392     FFPsyWindowInfo wi;
00393 
00394     memset(&wi, 0, sizeof(wi));
00395     if (la) {
00396         float s[8], v;
00397         int switch_to_eight = 0;
00398         float sum = 0.0, sum2 = 0.0;
00399         int attack_n = 0;
00400         int stay_short = 0;
00401         for (i = 0; i < 8; i++) {
00402             for (j = 0; j < 128; j++) {
00403                 v = iir_filter(la[(i*128+j)*ctx->avctx->channels], pch->iir_state);
00404                 sum += v*v;
00405             }
00406             s[i]  = sum;
00407             sum2 += sum;
00408         }
00409         for (i = 0; i < 8; i++) {
00410             if (s[i] > pch->win_energy * attack_ratio) {
00411                 attack_n        = i + 1;
00412                 switch_to_eight = 1;
00413                 break;
00414             }
00415         }
00416         pch->win_energy = pch->win_energy*7/8 + sum2/64;
00417 
00418         wi.window_type[1] = prev_type;
00419         switch (prev_type) {
00420         case ONLY_LONG_SEQUENCE:
00421             wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
00422             next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
00423             break;
00424         case LONG_START_SEQUENCE:
00425             wi.window_type[0] = EIGHT_SHORT_SEQUENCE;
00426             grouping = pch->next_grouping;
00427             next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
00428             break;
00429         case LONG_STOP_SEQUENCE:
00430             wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
00431             next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
00432             break;
00433         case EIGHT_SHORT_SEQUENCE:
00434             stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
00435             wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
00436             grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
00437             next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
00438             break;
00439         }
00440 
00441         pch->next_grouping = window_grouping[attack_n];
00442         pch->next_window_seq = next_type;
00443     } else {
00444         for (i = 0; i < 3; i++)
00445             wi.window_type[i] = prev_type;
00446         grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;
00447     }
00448 
00449     wi.window_shape   = 1;
00450     if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
00451         wi.num_windows = 1;
00452         wi.grouping[0] = 1;
00453     } else {
00454         int lastgrp = 0;
00455         wi.num_windows = 8;
00456         for (i = 0; i < 8; i++) {
00457             if (!((grouping >> i) & 1))
00458                 lastgrp = i;
00459             wi.grouping[lastgrp]++;
00460         }
00461     }
00462 
00463     return wi;
00464 }
00465 
00466 /* 5.6.1.2 "Calculation of Bit Demand" */
00467 static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,
00468                            int short_window)
00469 {
00470     const float bitsave_slope  = short_window ? PSY_3GPP_SAVE_SLOPE_S  : PSY_3GPP_SAVE_SLOPE_L;
00471     const float bitsave_add    = short_window ? PSY_3GPP_SAVE_ADD_S    : PSY_3GPP_SAVE_ADD_L;
00472     const float bitspend_slope = short_window ? PSY_3GPP_SPEND_SLOPE_S : PSY_3GPP_SPEND_SLOPE_L;
00473     const float bitspend_add   = short_window ? PSY_3GPP_SPEND_ADD_S   : PSY_3GPP_SPEND_ADD_L;
00474     const float clip_low       = short_window ? PSY_3GPP_CLIP_LO_S     : PSY_3GPP_CLIP_LO_L;
00475     const float clip_high      = short_window ? PSY_3GPP_CLIP_HI_S     : PSY_3GPP_CLIP_HI_L;
00476     float clipped_pe, bit_save, bit_spend, bit_factor, fill_level;
00477 
00478     ctx->fill_level += ctx->frame_bits - bits;
00479     ctx->fill_level  = av_clip(ctx->fill_level, 0, size);
00480     fill_level = av_clipf((float)ctx->fill_level / size, clip_low, clip_high);
00481     clipped_pe = av_clipf(pe, ctx->pe.min, ctx->pe.max);
00482     bit_save   = (fill_level + bitsave_add) * bitsave_slope;
00483     assert(bit_save <= 0.3f && bit_save >= -0.05000001f);
00484     bit_spend  = (fill_level + bitspend_add) * bitspend_slope;
00485     assert(bit_spend <= 0.5f && bit_spend >= -0.1f);
00486     /* The bit factor graph in the spec is obviously incorrect.
00487      *      bit_spend + ((bit_spend - bit_spend))...
00488      * The reference encoder subtracts everything from 1, but also seems incorrect.
00489      *      1 - bit_save + ((bit_spend + bit_save))...
00490      * Hopefully below is correct.
00491      */
00492     bit_factor = 1.0f - bit_save + ((bit_spend - bit_save) / (ctx->pe.max - ctx->pe.min)) * (clipped_pe - ctx->pe.min);
00493     /* NOTE: The reference encoder attempts to center pe max/min around the current pe. */
00494     ctx->pe.max = FFMAX(pe, ctx->pe.max);
00495     ctx->pe.min = FFMIN(pe, ctx->pe.min);
00496 
00497     return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits);
00498 }
00499 
00500 static float calc_pe_3gpp(AacPsyBand *band)
00501 {
00502     float pe, a;
00503 
00504     band->pe           = 0.0f;
00505     band->pe_const     = 0.0f;
00506     band->active_lines = 0.0f;
00507     if (band->energy > band->thr) {
00508         a  = log2f(band->energy);
00509         pe = a - log2f(band->thr);
00510         band->active_lines = band->nz_lines;
00511         if (pe < PSY_3GPP_C1) {
00512             pe = pe * PSY_3GPP_C3 + PSY_3GPP_C2;
00513             a  = a  * PSY_3GPP_C3 + PSY_3GPP_C2;
00514             band->active_lines *= PSY_3GPP_C3;
00515         }
00516         band->pe       = pe * band->nz_lines;
00517         band->pe_const = a  * band->nz_lines;
00518     }
00519 
00520     return band->pe;
00521 }
00522 
00523 static float calc_reduction_3gpp(float a, float desired_pe, float pe,
00524                                  float active_lines)
00525 {
00526     float thr_avg, reduction;
00527 
00528     thr_avg   = powf(2.0f, (a - pe) / (4.0f * active_lines));
00529     reduction = powf(2.0f, (a - desired_pe) / (4.0f * active_lines)) - thr_avg;
00530 
00531     return FFMAX(reduction, 0.0f);
00532 }
00533 
00534 static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,
00535                                    float reduction)
00536 {
00537     float thr = band->thr;
00538 
00539     if (band->energy > thr) {
00540         thr = powf(thr, 0.25f) + reduction;
00541         thr = powf(thr, 4.0f);
00542 
00543         /* This deviates from the 3GPP spec to match the reference encoder.
00544          * It performs min(thr_reduced, max(thr, energy/min_snr)) only for bands
00545          * that have hole avoidance on (active or inactive). It always reduces the
00546          * threshold of bands with hole avoidance off.
00547          */
00548         if (thr > band->energy * min_snr && band->avoid_holes != PSY_3GPP_AH_NONE) {
00549             thr = FFMAX(band->thr, band->energy * min_snr);
00550             band->avoid_holes = PSY_3GPP_AH_ACTIVE;
00551         }
00552     }
00553 
00554     return thr;
00555 }
00556 
00560 static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,
00561                                      const float *coefs, const FFPsyWindowInfo *wi)
00562 {
00563     AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
00564     AacPsyChannel *pch  = &pctx->ch[channel];
00565     int start = 0;
00566     int i, w, g;
00567     float desired_bits, desired_pe, delta_pe, reduction, spread_en[128] = {0};
00568     float a = 0.0f, active_lines = 0.0f, norm_fac = 0.0f;
00569     float pe = pctx->chan_bitrate > 32000 ? 0.0f : FFMAX(50.0f, 100.0f - pctx->chan_bitrate * 100.0f / 32000.0f);
00570     const int      num_bands   = ctx->num_bands[wi->num_windows == 8];
00571     const uint8_t *band_sizes  = ctx->bands[wi->num_windows == 8];
00572     AacPsyCoeffs  *coeffs      = pctx->psy_coef[wi->num_windows == 8];
00573     const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
00574 
00575     //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
00576     for (w = 0; w < wi->num_windows*16; w += 16) {
00577         for (g = 0; g < num_bands; g++) {
00578             AacPsyBand *band = &pch->band[w+g];
00579 
00580             float form_factor = 0.0f;
00581             band->energy = 0.0f;
00582             for (i = 0; i < band_sizes[g]; i++) {
00583                 band->energy += coefs[start+i] * coefs[start+i];
00584                 form_factor  += sqrtf(fabs(coefs[start+i]));
00585             }
00586             band->thr      = band->energy * 0.001258925f;
00587             band->nz_lines = form_factor / powf(band->energy / band_sizes[g], 0.25f);
00588 
00589             start += band_sizes[g];
00590         }
00591     }
00592     //modify thresholds and energies - spread, threshold in quiet, pre-echo control
00593     for (w = 0; w < wi->num_windows*16; w += 16) {
00594         AacPsyBand *bands = &pch->band[w];
00595 
00596         //5.4.2.3 "Spreading" & 5.4.3 "Spreaded Energy Calculation"
00597         spread_en[0] = bands[0].energy;
00598         for (g = 1; g < num_bands; g++) {
00599             bands[g].thr   = FFMAX(bands[g].thr,    bands[g-1].thr * coeffs[g].spread_hi[0]);
00600             spread_en[w+g] = FFMAX(bands[g].energy, spread_en[w+g-1] * coeffs[g].spread_hi[1]);
00601         }
00602         for (g = num_bands - 2; g >= 0; g--) {
00603             bands[g].thr   = FFMAX(bands[g].thr,   bands[g+1].thr * coeffs[g].spread_low[0]);
00604             spread_en[w+g] = FFMAX(spread_en[w+g], spread_en[w+g+1] * coeffs[g].spread_low[1]);
00605         }
00606         //5.4.2.4 "Threshold in quiet"
00607         for (g = 0; g < num_bands; g++) {
00608             AacPsyBand *band = &bands[g];
00609 
00610             band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
00611             //5.4.2.5 "Pre-echo control"
00612             if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))
00613                 band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
00614                                   PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
00615 
00616             /* 5.6.1.3.1 "Prepatory steps of the perceptual entropy calculation" */
00617             pe += calc_pe_3gpp(band);
00618             a  += band->pe_const;
00619             active_lines += band->active_lines;
00620 
00621             /* 5.6.1.3.3 "Selection of the bands for avoidance of holes" */
00622             if (spread_en[w+g] * avoid_hole_thr > band->energy || coeffs[g].min_snr > 1.0f)
00623                 band->avoid_holes = PSY_3GPP_AH_NONE;
00624             else
00625                 band->avoid_holes = PSY_3GPP_AH_INACTIVE;
00626         }
00627     }
00628 
00629     /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
00630     ctx->ch[channel].entropy = pe;
00631     desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
00632     desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
00633     /* NOTE: PE correction is kept simple. During initial testing it had very
00634      *       little effect on the final bitrate. Probably a good idea to come
00635      *       back and do more testing later.
00636      */
00637     if (ctx->bitres.bits > 0)
00638         desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
00639                                0.85f, 1.15f);
00640     pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
00641 
00642     if (desired_pe < pe) {
00643         /* 5.6.1.3.4 "First Estimation of the reduction value" */
00644         for (w = 0; w < wi->num_windows*16; w += 16) {
00645             reduction = calc_reduction_3gpp(a, desired_pe, pe, active_lines);
00646             pe = 0.0f;
00647             a  = 0.0f;
00648             active_lines = 0.0f;
00649             for (g = 0; g < num_bands; g++) {
00650                 AacPsyBand *band = &pch->band[w+g];
00651 
00652                 band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
00653                 /* recalculate PE */
00654                 pe += calc_pe_3gpp(band);
00655                 a  += band->pe_const;
00656                 active_lines += band->active_lines;
00657             }
00658         }
00659 
00660         /* 5.6.1.3.5 "Second Estimation of the reduction value" */
00661         for (i = 0; i < 2; i++) {
00662             float pe_no_ah = 0.0f, desired_pe_no_ah;
00663             active_lines = a = 0.0f;
00664             for (w = 0; w < wi->num_windows*16; w += 16) {
00665                 for (g = 0; g < num_bands; g++) {
00666                     AacPsyBand *band = &pch->band[w+g];
00667 
00668                     if (band->avoid_holes != PSY_3GPP_AH_ACTIVE) {
00669                         pe_no_ah += band->pe;
00670                         a        += band->pe_const;
00671                         active_lines += band->active_lines;
00672                     }
00673                 }
00674             }
00675             desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
00676             if (active_lines > 0.0f)
00677                 reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
00678 
00679             pe = 0.0f;
00680             for (w = 0; w < wi->num_windows*16; w += 16) {
00681                 for (g = 0; g < num_bands; g++) {
00682                     AacPsyBand *band = &pch->band[w+g];
00683 
00684                     if (active_lines > 0.0f)
00685                         band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
00686                     pe += calc_pe_3gpp(band);
00687                     band->norm_fac = band->active_lines / band->thr;
00688                     norm_fac += band->norm_fac;
00689                 }
00690             }
00691             delta_pe = desired_pe - pe;
00692             if (fabs(delta_pe) > 0.05f * desired_pe)
00693                 break;
00694         }
00695 
00696         if (pe < 1.15f * desired_pe) {
00697             /* 6.6.1.3.6 "Final threshold modification by linearization" */
00698             norm_fac = 1.0f / norm_fac;
00699             for (w = 0; w < wi->num_windows*16; w += 16) {
00700                 for (g = 0; g < num_bands; g++) {
00701                     AacPsyBand *band = &pch->band[w+g];
00702 
00703                     if (band->active_lines > 0.5f) {
00704                         float delta_sfb_pe = band->norm_fac * norm_fac * delta_pe;
00705                         float thr = band->thr;
00706 
00707                         thr *= powf(2.0f, delta_sfb_pe / band->active_lines);
00708                         if (thr > coeffs[g].min_snr * band->energy && band->avoid_holes == PSY_3GPP_AH_INACTIVE)
00709                             thr = FFMAX(band->thr, coeffs[g].min_snr * band->energy);
00710                         band->thr = thr;
00711                     }
00712                 }
00713             }
00714         } else {
00715             /* 5.6.1.3.7 "Further perceptual entropy reduction" */
00716             g = num_bands;
00717             while (pe > desired_pe && g--) {
00718                 for (w = 0; w < wi->num_windows*16; w+= 16) {
00719                     AacPsyBand *band = &pch->band[w+g];
00720                     if (band->avoid_holes != PSY_3GPP_AH_NONE && coeffs[g].min_snr < PSY_SNR_1DB) {
00721                         coeffs[g].min_snr = PSY_SNR_1DB;
00722                         band->thr = band->energy * PSY_SNR_1DB;
00723                         pe += band->active_lines * 1.5f - band->pe;
00724                     }
00725                 }
00726             }
00727             /* TODO: allow more holes (unused without mid/side) */
00728         }
00729     }
00730 
00731     for (w = 0; w < wi->num_windows*16; w += 16) {
00732         for (g = 0; g < num_bands; g++) {
00733             AacPsyBand *band     = &pch->band[w+g];
00734             FFPsyBand  *psy_band = &ctx->ch[channel].psy_bands[w+g];
00735 
00736             psy_band->threshold = band->thr;
00737             psy_band->energy    = band->energy;
00738         }
00739     }
00740 
00741     memcpy(pch->prev_band, pch->band, sizeof(pch->band));
00742 }
00743 
00744 static void psy_3gpp_analyze(FFPsyContext *ctx, int channel,
00745                                    const float **coeffs, const FFPsyWindowInfo *wi)
00746 {
00747     int ch;
00748     FFPsyChannelGroup *group = ff_psy_find_group(ctx, channel);
00749 
00750     for (ch = 0; ch < group->num_ch; ch++)
00751         psy_3gpp_analyze_channel(ctx, channel + ch, coeffs[ch], &wi[ch]);
00752 }
00753 
00754 static av_cold void psy_3gpp_end(FFPsyContext *apc)
00755 {
00756     AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
00757     av_freep(&pctx->ch);
00758     av_freep(&apc->model_priv_data);
00759 }
00760 
00761 static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
00762 {
00763     int blocktype = ONLY_LONG_SEQUENCE;
00764     if (uselongblock) {
00765         if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
00766             blocktype = LONG_STOP_SEQUENCE;
00767     } else {
00768         blocktype = EIGHT_SHORT_SEQUENCE;
00769         if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
00770             ctx->next_window_seq = LONG_START_SEQUENCE;
00771         if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
00772             ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
00773     }
00774 
00775     wi->window_type[0] = ctx->next_window_seq;
00776     ctx->next_window_seq = blocktype;
00777 }
00778 
00779 static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx,
00780                                        const int16_t *audio, const int16_t *la,
00781                                        int channel, int prev_type)
00782 {
00783     AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
00784     AacPsyChannel *pch  = &pctx->ch[channel];
00785     int grouping     = 0;
00786     int uselongblock = 1;
00787     int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
00788     int i;
00789     FFPsyWindowInfo wi;
00790 
00791     memset(&wi, 0, sizeof(wi));
00792     if (la) {
00793         float hpfsmpl[AAC_BLOCK_SIZE_LONG];
00794         float const *pf = hpfsmpl;
00795         float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
00796         float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
00797         float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
00798         int chans = ctx->avctx->channels;
00799         const int16_t *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN) * chans;
00800         int j, att_sum = 0;
00801 
00802         /* LAME comment: apply high pass filter of fs/4 */
00803         for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
00804             float sum1, sum2;
00805             sum1 = firbuf[(i + ((PSY_LAME_FIR_LEN - 1) / 2)) * chans];
00806             sum2 = 0.0;
00807             for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
00808                 sum1 += psy_fir_coeffs[j] * (firbuf[(i + j) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j) * chans]);
00809                 sum2 += psy_fir_coeffs[j + 1] * (firbuf[(i + j + 1) * chans] + firbuf[(i + PSY_LAME_FIR_LEN - j - 1) * chans]);
00810             }
00811             hpfsmpl[i] = sum1 + sum2;
00812         }
00813 
00814         /* Calculate the energies of each sub-shortblock */
00815         for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
00816             energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
00817             assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);
00818             attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];
00819             energy_short[0] += energy_subshort[i];
00820         }
00821 
00822         for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
00823             float const *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
00824             float p = 1.0f;
00825             for (; pf < pfe; pf++)
00826                 if (p < fabsf(*pf))
00827                     p = fabsf(*pf);
00828             pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
00829             energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
00830             /* FIXME: The indexes below are [i + 3 - 2] in the LAME source.
00831              *          Obviously the 3 and 2 have some significance, or this would be just [i + 1]
00832              *          (which is what we use here). What the 3 stands for is ambigious, as it is both
00833              *          number of short blocks, and the number of sub-short blocks.
00834              *          It seems that LAME is comparing each sub-block to sub-block + 1 in the
00835              *          previous block.
00836              */
00837             if (p > energy_subshort[i + 1])
00838                 p = p / energy_subshort[i + 1];
00839             else if (energy_subshort[i + 1] > p * 10.0f)
00840                 p = energy_subshort[i + 1] / (p * 10.0f);
00841             else
00842                 p = 0.0;
00843             attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
00844         }
00845 
00846         /* compare energy between sub-short blocks */
00847         for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
00848             if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])
00849                 if (attack_intensity[i] > pch->attack_threshold)
00850                     attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
00851 
00852         /* should have energy change between short blocks, in order to avoid periodic signals */
00853         /* Good samples to show the effect are Trumpet test songs */
00854         /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
00855         /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
00856         for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
00857             float const u = energy_short[i - 1];
00858             float const v = energy_short[i];
00859             float const m = FFMAX(u, v);
00860             if (m < 40000) {                          /* (2) */
00861                 if (u < 1.7f * v && v < 1.7f * u) {   /* (1) */
00862                     if (i == 1 && attacks[0] < attacks[i])
00863                         attacks[0] = 0;
00864                     attacks[i] = 0;
00865                 }
00866             }
00867             att_sum += attacks[i];
00868         }
00869 
00870         if (attacks[0] <= pch->prev_attack)
00871             attacks[0] = 0;
00872 
00873         att_sum += attacks[0];
00874         /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */
00875         if (pch->prev_attack == 3 || att_sum) {
00876             uselongblock = 0;
00877 
00878             for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
00879                 if (attacks[i] && attacks[i-1])
00880                     attacks[i] = 0;
00881         }
00882     } else {
00883         /* We have no lookahead info, so just use same type as the previous sequence. */
00884         uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
00885     }
00886 
00887     lame_apply_block_type(pch, &wi, uselongblock);
00888 
00889     wi.window_type[1] = prev_type;
00890     if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
00891         wi.num_windows  = 1;
00892         wi.grouping[0]  = 1;
00893         if (wi.window_type[0] == LONG_START_SEQUENCE)
00894             wi.window_shape = 0;
00895         else
00896             wi.window_shape = 1;
00897     } else {
00898         int lastgrp = 0;
00899 
00900         wi.num_windows = 8;
00901         wi.window_shape = 0;
00902         for (i = 0; i < 8; i++) {
00903             if (!((pch->next_grouping >> i) & 1))
00904                 lastgrp = i;
00905             wi.grouping[lastgrp]++;
00906         }
00907     }
00908 
00909     /* Determine grouping, based on the location of the first attack, and save for
00910      * the next frame.
00911      * FIXME: Move this to analysis.
00912      * TODO: Tune groupings depending on attack location
00913      * TODO: Handle more than one attack in a group
00914      */
00915     for (i = 0; i < 9; i++) {
00916         if (attacks[i]) {
00917             grouping = i;
00918             break;
00919         }
00920     }
00921     pch->next_grouping = window_grouping[grouping];
00922 
00923     pch->prev_attack = attacks[8];
00924 
00925     return wi;
00926 }
00927 
00928 const FFPsyModel ff_aac_psy_model =
00929 {
00930     .name    = "3GPP TS 26.403-inspired model",
00931     .init    = psy_3gpp_init,
00932     .window  = psy_lame_window,
00933     .analyze = psy_3gpp_analyze,
00934     .end     = psy_3gpp_end,
00935 };
Generated on Thu Jul 11 2013 15:38:18 for Libav by doxygen 1.7.1