Ticket #2686: aac-improvements-wip-v8g.patch
| File aac-improvements-wip-v8g.patch, 76.6 KB (added by , 12 years ago) |
|---|
-
libavcodec/aac.h
diff --git a/libavcodec/aac.h b/libavcodec/aac.h index 89f463e..d7a2303 100644
a b typedef struct LongTermPrediction { 157 157 typedef struct IndividualChannelStream { 158 158 uint8_t max_sfb; ///< number of scalefactor bands per group 159 159 enum WindowSequence window_sequence[2]; 160 uint8_t use_kb_window[2]; ///< If set, use Kaiser-Bessel window, otherwise use a sin ewindow.160 uint8_t use_kb_window[2]; ///< If set, use Kaiser-Bessel window, otherwise use a sinus window. 161 161 int num_window_groups; 162 162 uint8_t group_len[8]; 163 163 LongTermPrediction ltp; … … typedef struct IndividualChannelStream { 170 170 int predictor_initialized; 171 171 int predictor_reset_group; 172 172 uint8_t prediction_used[41]; 173 uint8_t window_clipping[8]; ///< set if a certain window is near clipping 173 174 } IndividualChannelStream; 174 175 175 176 /** … … typedef struct SingleChannelElement { 233 234 float sf[120]; ///< scalefactors 234 235 int sf_idx[128]; ///< scalefactor indices (used by encoder) 235 236 uint8_t zeroes[128]; ///< band is not coded (used by encoder) 236 DECLARE_ALIGNED(32, float, coeffs)[1024]; ///< coefficients for IMDCT 237 DECLARE_ALIGNED(32, float, saved)[1536]; ///< overlap 237 DECLARE_ALIGNED(32, float, pcoeffs)[1024]; ///< coefficients for IMDCT, pristine 238 DECLARE_ALIGNED(32, float, coeffs)[1024]; ///< coefficients for IMDCT, maybe processed 239 DECLARE_ALIGNED(32, float, saved)[1024]; ///< overlap 238 240 DECLARE_ALIGNED(32, float, ret_buf)[2048]; ///< PCM output buffer 239 241 DECLARE_ALIGNED(16, float, ltp_state)[3072]; ///< time signal for LTP 240 242 PredictorState predictor_state[MAX_PREDICTORS]; -
libavcodec/aaccoder.c
diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c index 50a246f..a3dc19c 100644
a b static const uint8_t *run_value_bits[2] = { 57 57 run_value_bits_long, run_value_bits_short 58 58 }; 59 59 60 #define ROUND_STANDARD 0.4054f 61 #define ROUND_TO_ZERO 0.1054f 60 62 61 63 /** 62 64 * Quantize one coefficient. 63 65 * @return absolute value of the quantized coefficient 64 66 * @see 3GPP TS26.403 5.6.2 "Scalefactor determination" 65 67 */ 66 static av_always_inline int quant(float coef, const float Q )68 static av_always_inline int quant(float coef, const float Q, const float rounding) 67 69 { 68 70 float a = coef * Q; 69 return sqrtf(a * sqrtf(a)) + 0.4054;71 return sqrtf(a * sqrtf(a)) + rounding; 70 72 } 71 73 72 74 static void quantize_bands(int *out, const float *in, const float *scaled, 73 int size, float Q34, int is_signed, int maxval )75 int size, float Q34, int is_signed, int maxval, const float rounding) 74 76 { 75 77 int i; 76 78 double qc; 77 79 for (i = 0; i < size; i++) { 78 80 qc = scaled[i] * Q34; 79 out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);81 out[i] = (int)FFMIN(qc + rounding, (double)maxval); 80 82 if (is_signed && in[i] < 0.0f) { 81 83 out[i] = -out[i]; 82 84 } … … static av_always_inline float quantize_and_encode_band_cost_template( 108 110 const float *scaled, int size, int scale_idx, 109 111 int cb, const float lambda, const float uplim, 110 112 int *bits, int BT_ZERO, int BT_UNSIGNED, 111 int BT_PAIR, int BT_ESC )113 int BT_PAIR, int BT_ESC, const float ROUNDING) 112 114 { 113 115 const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512; 114 116 const float Q = ff_aac_pow2sf_tab [q_idx]; … … static av_always_inline float quantize_and_encode_band_cost_template( 134 136 abs_pow34_v(s->scoefs, in, size); 135 137 scaled = s->scoefs; 136 138 } 137 quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval );139 quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval, ROUNDING); 138 140 if (BT_UNSIGNED) { 139 141 off = 0; 140 142 } else { … … static av_always_inline float quantize_and_encode_band_cost_template( 161 163 di = t - CLIPPED_ESCAPE; 162 164 curbits += 21; 163 165 } else { 164 int c = av_clip(quant(t, Q ), 0, 8191);166 int c = av_clip(quant(t, Q, ROUNDING), 0, 8191); 165 167 di = t - c*cbrtf(c)*IQ; 166 168 curbits += av_log2(c)*2 - 4 + 1; 167 169 } … … static av_always_inline float quantize_and_encode_band_cost_template( 191 193 if (BT_ESC) { 192 194 for (j = 0; j < 2; j++) { 193 195 if (ff_aac_codebook_vectors[cb-1][curidx*2+j] == 64.0f) { 194 int coef = av_clip(quant(fabsf(in[i+j]), Q ), 0, 8191);196 int coef = av_clip(quant(fabsf(in[i+j]), Q, ROUNDING), 0, 8191); 195 197 int len = av_log2(coef); 196 198 197 199 put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2); … … static av_always_inline float quantize_and_encode_band_cost_template( 207 209 return cost; 208 210 } 209 211 210 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC ) \212 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING) \ 211 213 static float quantize_and_encode_band_cost_ ## NAME( \ 212 214 struct AACEncContext *s, \ 213 215 PutBitContext *pb, const float *in, \ … … static float quantize_and_encode_band_cost_ ## NAME( 217 219 return quantize_and_encode_band_cost_template( \ 218 220 s, pb, in, scaled, size, scale_idx, \ 219 221 BT_ESC ? ESC_BT : cb, lambda, uplim, bits, \ 220 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC );\222 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING); \ 221 223 } 222 224 223 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO, 1, 0, 0, 0) 224 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0) 225 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0) 226 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0) 227 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0) 228 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC, 0, 1, 1, 1) 225 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO, 1, 0, 0, 0, ROUND_STANDARD) 226 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, ROUND_STANDARD) 227 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, ROUND_STANDARD) 228 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, ROUND_STANDARD) 229 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, ROUND_STANDARD) 230 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC, 0, 1, 1, 1, ROUND_STANDARD) 231 232 /*QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO_RTZ, 1, 0, 0, 0, ROUND_TO_ZERO) 233 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD_RTZ, 0, 0, 0, 0, ROUND_TO_ZERO) 234 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD_RTZ, 0, 1, 0, 0, ROUND_TO_ZERO) 235 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR_RTZ, 0, 0, 1, 0, ROUND_TO_ZERO) 236 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR_RTZ, 0, 1, 1, 0, ROUND_TO_ZERO)*/ 237 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ, 0, 1, 1, 1, ROUND_TO_ZERO) 229 238 230 239 static float (*const quantize_and_encode_band_cost_arr[])( 231 240 struct AACEncContext *s, … … static float (*const quantize_and_encode_band_cost_arr[])( 247 256 quantize_and_encode_band_cost_ESC, 248 257 }; 249 258 259 static float (*const quantize_and_encode_band_cost_rtz_arr[])( 260 struct AACEncContext *s, 261 PutBitContext *pb, const float *in, 262 const float *scaled, int size, int scale_idx, 263 int cb, const float lambda, const float uplim, 264 int *bits) = { 265 quantize_and_encode_band_cost_ZERO, 266 quantize_and_encode_band_cost_SQUAD, 267 quantize_and_encode_band_cost_SQUAD, 268 quantize_and_encode_band_cost_UQUAD, 269 quantize_and_encode_band_cost_UQUAD, 270 quantize_and_encode_band_cost_SPAIR, 271 quantize_and_encode_band_cost_SPAIR, 272 quantize_and_encode_band_cost_UPAIR, 273 quantize_and_encode_band_cost_UPAIR, 274 quantize_and_encode_band_cost_UPAIR, 275 quantize_and_encode_band_cost_UPAIR, 276 quantize_and_encode_band_cost_ESC_RTZ, 277 }; 278 250 279 #define quantize_and_encode_band_cost( \ 251 280 s, pb, in, scaled, size, scale_idx, cb, \ 252 lambda, uplim, bits )\253 quantize_and_encode_band_cost_arr[cb](\281 lambda, uplim, bits, rtz) \ 282 ((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \ 254 283 s, pb, in, scaled, size, scale_idx, cb, \ 255 284 lambda, uplim, bits) 256 285 257 286 static float quantize_band_cost(struct AACEncContext *s, const float *in, 258 287 const float *scaled, int size, int scale_idx, 259 288 int cb, const float lambda, const float uplim, 260 int *bits )289 int *bits, int rtz) 261 290 { 262 291 return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx, 263 cb, lambda, uplim, bits );292 cb, lambda, uplim, bits, rtz); 264 293 } 265 294 266 295 static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb, 267 296 const float *in, int size, int scale_idx, 268 int cb, const float lambda )297 int cb, const float lambda, int rtz) 269 298 { 270 299 quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda, 271 INFINITY, NULL );300 INFINITY, NULL, rtz); 272 301 } 273 302 274 303 static float find_max_val(int group_len, int swb_size, const float *scaled) { … … static float find_max_val(int group_len, int swb_size, const float *scaled) { 282 311 return maxval; 283 312 } 284 313 314 static av_const float sqrf(float f) { 315 return f*f; 316 } 317 318 static float find_form_factor(int group_len, int swb_size, float thresh, const float *scaled, float cleanup_factor) { 319 const float iswb_size = 1.0f / swb_size; 320 const float iswb_sizem1 = 1.0f / (swb_size - 1); 321 const float ethresh = thresh; 322 float form = 0.0f, weight = 0.0f; 323 int w2, i; 324 for (w2 = 0; w2 < group_len; w2++) { 325 float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f; 326 float nzl = 0; 327 for (i = 0; i < swb_size; i++) { 328 float s = fabsf(scaled[w2*128+i]); 329 maxval = FFMAX(maxval, s); 330 e += s; 331 e2 += s *= s; 332 /* We really don't want a hard non-zero-line count, since 333 * even below-threshold lines do add up towards band spectral power. 334 * So, fall steeply towards zero, but smoothly 335 */ 336 if (s >= ethresh) 337 nzl += 1.0f; 338 else if (cleanup_factor > 1.0f) 339 nzl += powf(sqrf(s / ethresh), sqrf(FFMIN(4.0f,cleanup_factor))); 340 else 341 nzl += sqrf(s / ethresh); 342 } 343 if (e2 > thresh) { 344 float frm; 345 e *= iswb_size; 346 347 // compute variance 348 for (i = 0; i < swb_size; i++) { 349 float d = fabsf(scaled[w2*128+i]) - e; 350 var += d*d; 351 } 352 var = sqrtf(var * iswb_sizem1); 353 354 e2 *= iswb_size; 355 frm = e / FFMIN(e+4*var,maxval); 356 form += e2 * sqrtf(frm) / FFMAX(0.5f,nzl); 357 weight += e2; 358 } 359 } 360 if (weight > 0) 361 return form / weight; 362 else 363 return 1.0f; 364 } 365 366 static float find_max_absval(int group_len, int swb_size, const float *scaled) { 367 float maxval = 0.0f; 368 int w2, i; 369 for (w2 = 0; w2 < group_len; w2++) { 370 for (i = 0; i < swb_size; i++) { 371 maxval = FFMAX(maxval, fabs(scaled[w2*128+i])); 372 } 373 } 374 return maxval; 375 } 376 377 static unsigned char aac_maxval_cb[] = { 378 0, 1, 3, 5, 5, 7, 7, 7, 9, 9, 9, 9, 9, 11 379 }; 380 285 381 static int find_min_book(float maxval, int sf) { 286 382 float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512]; 287 383 float Q34 = sqrtf(Q * sqrtf(Q)); 288 384 int qmaxval, cb; 289 385 qmaxval = maxval * Q34 + 0.4054f; 290 if (qmaxval == 0) cb = 0; 291 else if (qmaxval == 1) cb = 1; 292 else if (qmaxval == 2) cb = 3; 293 else if (qmaxval <= 4) cb = 5; 294 else if (qmaxval <= 7) cb = 7; 295 else if (qmaxval <= 12) cb = 9; 296 else cb = 11; 386 if (qmaxval >= (sizeof(aac_maxval_cb) / sizeof(aac_maxval_cb[0]))) 387 cb = 11; 388 else 389 cb = aac_maxval_cb[qmaxval]; 297 390 return cb; 298 391 } 299 392 … … static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce 351 444 rd += quantize_band_cost(s, sce->coeffs + start + w*128, 352 445 s->scoefs + start + w*128, size, 353 446 sce->sf_idx[(win+w)*16+swb], cb, 354 lambda / band->threshold, INFINITY, NULL );447 lambda / band->threshold, INFINITY, NULL, 0); 355 448 } 356 449 cost_stay_here = path[swb][cb].cost + rd; 357 450 cost_get_here = minrd + rd + run_bits + 4; … … static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce, 473 566 bits += quantize_band_cost(s, sce->coeffs + start + w*128, 474 567 s->scoefs + start + w*128, size, 475 568 sce->sf_idx[(win+w)*16+swb], cb, 476 0, INFINITY, NULL );569 0, INFINITY, NULL, 0); 477 570 } 478 571 cost_stay_here = path[swb][cb].cost + bits; 479 572 cost_get_here = minbits + bits + run_bits + 4; … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 655 748 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 656 749 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 657 750 dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g], 658 q + q0, cb, lambda / band->threshold, INFINITY, NULL );751 q + q0, cb, lambda / band->threshold, INFINITY, NULL, 0); 659 752 } 660 753 minrd = FFMIN(minrd, dist); 661 754 … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 701 794 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g]; 702 795 } 703 796 797 #define sclip(x) av_clip(x,60,218) 798 704 799 /** 705 800 * two-loop quantizers search taken from ISO 13818-7 Appendix C 706 801 */ 707 802 static void search_for_quantizers_twoloop(AVCodecContext *avctx, 708 803 AACEncContext *s, 709 804 SingleChannelElement *sce, 710 constfloat lambda)805 float lambda) 711 806 { 712 807 int start = 0, i, w, w2, g; 713 int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels * (lambda / 120.f); 714 float dists[128] = { 0 }, uplims[128]; 808 int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate 809 / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels) 810 * (lambda / 120.f); 811 int refbits = destbits; 812 int toomanybits, toofewbits; 813 char nzs[128]; 814 float dists[128] = { 0 }, uplims[128], energies[128]; 715 815 float maxvals[128]; 716 int fflag, minscaler; 816 817 /* rdlambda controls the maximum tolerated distortion. Twoloop 818 * will keep iterating until it fails to lower it or it reaches 819 * ulimit * rdlambda. Keeping it low increases quality on difficult 820 * signals, but lower it too much, and bits will be taken from weak 821 * signals, creating "holes". A balance is necesary. 822 * rdmax and rdmin specify the relative deviation from rdlambda 823 * allowed for tonality compensation 824 */ 825 float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f); 826 float rdmin = 0.03125f; 827 float rdmax = 1.0f; 828 829 /* sfoffs controls an offset of optmium allocation that will be 830 * applied based on lambda. Keep it real and modest, the loop 831 * will take care of the rest, this just accelerates convergence 832 */ 833 float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10); 834 835 int fflag, minscaler, maxscaler, nminscaler, minrdsf; 717 836 int its = 0; 837 int maxits = 20; 718 838 int allz = 0; 719 float minthr = INFINITY; 839 int tbits; 840 int cutoff = 1024; 841 int cleanoff = 1024; 842 843 /* zeroscale controls a multiplier of the threshold, if band energy 844 * is below this, a zero is forced. Keep it lower than 1, unless 845 * low lambda is used, because energy < threshold doesn't mean there's 846 * no audible signal outright, it's just energy. Also make it rise 847 * slower than rdlambda, as rdscale has due compensation with 848 * noisy band depriorization below, whereas zeroing logic is rather dumb 849 */ 850 float zeroscale; 851 if (lambda > 120.f) 852 zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f); 853 else 854 zeroscale = 1.f; 855 856 if (s->psy.bitres.alloc >= 0) { 857 // Psy granted us extra bits to use, from the reservoire 858 // adjust for lambda except what psy already did 859 destbits = s->psy.bitres.alloc 860 * (lambda / (avctx->global_quality ? avctx->global_quality : 120)); 861 } 862 863 if (avctx->flags & CODEC_FLAG_QSCALE) { 864 // Constant Q-scale doesn't compensat MS coding on its own 865 // No need to be overly precise, this only controls RD 866 // adjustment CB limits when going overboard 867 if (s->options.stereo_mode && s->cur_type == TYPE_CPE) 868 destbits *= 2; 869 870 // When using a constant Q-scale, don't adjust bits, just use RD 871 // Don't let it go overboard, though... 8x psy target is enough 872 toomanybits = 5800; //av_clip(FFMAX(refbits*3, destbits * 8), 768, 5800); 873 toofewbits = 0; 874 875 // Don't offset scalers, just RD 876 sfoffs = sce->ics.num_windows - 1; 877 rdlambda = sqrtf(rdlambda); 878 879 // search further 880 maxits = 40; 881 } else { 882 // When using ABR, be strict 883 toomanybits = destbits + destbits/16; 884 toofewbits = destbits - destbits/16; 885 886 sfoffs = 0; 887 rdlambda = sqrtf(rdlambda); 888 } 889 890 // and zero out above cutoff frequency 891 { 892 int wlen = 1024 / sce->ics.num_windows; 893 int bandwidth; 894 int cleanwidth; 895 896 /* Scale, psy gives us constant quality, this LP only scales 897 * bitrate by lambda, so we save bits on subjectively unimportant HF 898 * rather than increase quantization noise. Adjust nominal bitrate 899 * to effective bitrate according to encoding parameters, _AAC_CUTOFF 900 * is calibrated for effective bitrate. 901 */ 902 float rate_bandwidth_multiplier = 1.3f; 903 int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE) 904 ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024) 905 : (avctx->bit_rate / avctx->channels); 906 907 if (avctx->cutoff > 0) 908 bandwidth = avctx->cutoff; 909 else 910 bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate)); 911 cleanwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate * 0.8f, 1, avctx->sample_rate)); 912 913 cutoff = bandwidth * 2 * wlen / avctx->sample_rate; 914 cleanoff = cleanwidth * 2 * wlen / avctx->sample_rate; 915 } 720 916 721 917 // for values above this the decoder might end up in an endless loop 722 918 // due to always having more bits than what can be encoded. 723 919 destbits = FFMIN(destbits, 5800); 920 toomanybits = FFMIN(toomanybits, 5800); 921 toofewbits = FFMIN(toofewbits, 5800); 724 922 //XXX: some heuristic to determine initial quantizers will reduce search time 725 923 //determine zero bands and upper limits 726 924 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 727 for (g = 0; g < sce->ics.num_swb; g++) {925 for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) { 728 926 int nz = 0; 729 927 float uplim = 0.0f; 928 float energy = 0.0f; 929 730 930 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 731 931 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 732 uplim += band->threshold; 733 if (band->energy <= band->threshold || band->threshold == 0.0f) { 932 if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0) { 734 933 sce->zeroes[(w+w2)*16+g] = 1; 735 934 continue; 736 935 } 737 936 nz = 1; 738 937 } 739 uplims[w*16+g] = uplim *512; 938 if (!nz) { 939 uplim = 0.0f; 940 } else { 941 nz = 0; 942 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 943 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 944 if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f) 945 continue; 946 uplim += band->threshold; 947 energy += band->energy; 948 nz++; 949 } 950 } 951 uplims[w*16+g] = uplim; 952 energies[w*16+g] = energy; 953 nzs[w*16+g] = nz; 740 954 sce->zeroes[w*16+g] = !nz; 741 if (nz)742 minthr = FFMIN(minthr, uplim);743 955 allz |= nz; 744 956 } 745 957 } 958 959 /* Compute initial scalers */ 960 minscaler = 65535; 746 961 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 747 962 for (g = 0; g < sce->ics.num_swb; g++) { 748 963 if (sce->zeroes[w*16+g]) { 749 964 sce->sf_idx[w*16+g] = SCALE_ONE_POS; 750 965 continue; 751 966 } 752 sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59); 967 /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2). 968 * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion, 969 * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus 970 * more robust. 971 */ 972 sce->sf_idx[w*16+g] = av_clip( 973 SCALE_ONE_POS 974 + 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g]) 975 + sfoffs, 976 60, SCALE_MAX_POS); 977 //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]); 978 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]); 753 979 } 980 //fprintf(stderr, "|\n"); 754 981 } 755 982 //fprintf(stderr, "\n"); 983 984 /* Clip */ 985 minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512); 986 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 987 for (g = 0; g < sce->ics.num_swb; g++) 988 if (!sce->zeroes[w*16+g]) 989 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1); 990 756 991 if (!allz) 757 992 return; 758 993 abs_pow34_v(s->scoefs, sce->coeffs, 1024); … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 766 1001 } 767 1002 } 768 1003 1004 /* Scale uplims to match rate distortion to quality 1005 * and apply noisy band depriorization and tonal band priorization. 1006 * Maxval-energy ratio gives us an idea of how noisy/tonal the band is. 1007 * If maxval^2 ~ energy, then that band is mostly noise, and we can relax 1008 * rate distortion requirements. 1009 */ 1010 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1011 /* psy already priorizes transients to some extent */ 1012 float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f; 1013 start = w*128; 1014 for (g = 0; g < sce->ics.num_swb; g++) { 1015 if (nzs[g] > 0) { 1016 float energy2uplim = find_form_factor( 1017 sce->ics.group_len[w], sce->ics.swb_sizes[g], 1018 uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]), 1019 sce->coeffs + start, 1020 start / (float)cleanoff); 1021 energy2uplim *= de_psy_factor; 1022 energy2uplim = FFMAX(0.015625f, FFMIN(1.0f,energy2uplim)); 1023 //fprintf(stderr, "%.3f ", energy2uplim); 1024 uplims[w*16+g] *= av_clipf(rdlambda * energy2uplim, rdmin, rdmax) 1025 * sce->ics.group_len[w]; 1026 } 1027 start += sce->ics.swb_sizes[g]; 1028 } 1029 //fprintf(stderr, "|"); 1030 } 1031 //fprintf(stderr, "\n"); 1032 769 1033 //perform two-loop search 770 1034 //outer loop - improve quality 771 1035 do { 772 int tbits, qstep; 773 minscaler = sce->sf_idx[0]; 1036 int qstep; 774 1037 //inner loop - quantize spectrum to fit into given number of bits 775 1038 qstep = its ? 1 : 32; 776 1039 do { … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 790 1053 start += sce->ics.swb_sizes[g]; 791 1054 continue; 792 1055 } 793 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);794 1056 cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 795 1057 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 796 1058 int b; … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 801 1063 cb, 802 1064 1.0f, 803 1065 INFINITY, 804 &b); 1066 &b, 1067 0); 805 1068 bits += b; 806 1069 } 807 1070 dists[w*16+g] = dist - bits; … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 813 1076 prev = sce->sf_idx[w*16+g]; 814 1077 } 815 1078 } 816 if (tbits > destbits) {1079 if (tbits > toomanybits) { 817 1080 for (i = 0; i < 128; i++) 818 if (sce->sf_idx[i] < 218 - qstep)819 sce->sf_idx[i] += qstep;820 } else {1081 if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512)) 1082 sce->sf_idx[i] = FFMIN(SCALE_MAX_POS, sce->sf_idx[i] + qstep); 1083 } else if (tbits < toofewbits) { 821 1084 for (i = 0; i < 128; i++) 822 if (sce->sf_idx[i] > 60 - qstep)823 sce->sf_idx[i] -= qstep;1085 if (sce->sf_idx[i] > SCALE_ONE_POS) 1086 sce->sf_idx[i] = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep); 824 1087 } 825 1088 qstep >>= 1; 826 if (!qstep && tbits > destbits*1.02&& sce->sf_idx[0] < 217)1089 if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217) 827 1090 qstep = 1; 828 1091 } while (qstep); 829 1092 1093 minscaler = SCALE_MAX_POS; 1094 maxscaler = 0; 1095 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1096 for (g = 0; g < sce->ics.num_swb; g++) { 1097 if (!sce->zeroes[w*16+g]) { 1098 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]); 1099 maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]); 1100 } 1101 } 1102 } 1103 1104 //NOTE: Emulate v4 patch with n = 0, uncommenting if (mb >= ESC_BT) break, 1105 // and replacing minscaler-1 with minscaler 830 1106 fflag = 0; 831 minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF); 1107 minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512); 1108 minrdsf = FFMAX3(60, minscaler-1, maxscaler - SCALE_MAX_DIFF); 832 1109 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1110 int depth = (avctx->flags & CODEC_FLAG_QSCALE) ? 4 : 2; 1111 int mblim; 1112 float uplmax = FFMIN(4.0f, FFMAX(1.0f, tbits / (float)FFMAX(1,destbits))); 1113 if (tbits > (destbits*6)) 1114 mblim = 9; 1115 else if (tbits < (destbits/3)) 1116 mblim = (ESC_BT + 1); 1117 else 1118 mblim = ESC_BT; 833 1119 for (g = 0; g < sce->ics.num_swb; g++) { 834 1120 int prevsc = sce->sf_idx[w*16+g]; 835 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) { 836 if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1)) 837 sce->sf_idx[w*16+g]--; 838 else //Try to make sure there is some energy in every band 839 sce->sf_idx[w*16+g]-=2; 1121 if (!sce->zeroes[w*16+g]) { 1122 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > minrdsf) { 1123 //Try to make sure there is some energy in every nonzero band 1124 //NOTE: This algorithm must be forcibly imbalanced, pushing harder 1125 // on holes or more distorted bands at first, otherwise there's 1126 // no net gain (since the next iteration will offset all bands 1127 // on the opposite direction to compensate for extra bits) 1128 int n = (its > 4 && g > sce->ics.num_swb/4) ? 0 : (depth/2); 1129 for (i = 0; i < depth; ++i) { 1130 int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1); 1131 int cmb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1132 if ((mb > cmb || cmb > mblim) && mb >= mblim && dists[w*16+g] <= uplims[w*16+g]*uplmax && sce->sf_idx[w*16+g] <= (minrdsf+1)) break; 1133 sce->sf_idx[w*16+g]--; 1134 dists[w*16+g] *= 0.5f; 1135 if (mb && (i >= n || dists[w*16+g] < uplims[w*16+g])) break; 1136 } 1137 } else if (tbits > destbits && dists[w*16+g] < (uplims[w*16+g]*0.5f) && sce->sf_idx[w*16+g] < maxscaler) { 1138 // Um... over target 1139 sce->sf_idx[w*16+g]++; 1140 dists[w*16+g] *= 2.0f; 1141 } 840 1142 } 841 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], min scaler, minscaler + SCALE_MAX_DIFF);842 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);1143 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF); 1144 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512); 843 1145 if (sce->sf_idx[w*16+g] != prevsc) 844 1146 fflag = 1; 1147 nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]); 845 1148 sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 846 1149 } 847 1150 } 1151 if (nminscaler < minscaler) { 1152 // Drecreased some scalers below minscaler. Must re-clamp. 1153 minscaler = nminscaler; 1154 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 1155 for (g = 0; g < sce->ics.num_swb; g++) 1156 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF); 1157 } 848 1158 its++; 849 } while (fflag && its < 10); 1159 } while (fflag && its < maxits); 1160 1161 /* Fill implicit zeroes */ 1162 //fprintf(stderr, "its:%d %d/%d: ", its, tbits, destbits); 1163 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1164 /* No lowly codebooks beyond cutoff zone, to clean up noisy coefs */ 1165 int scutoff = cutoff + cutoff/5; 1166 for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) { 1167 int minbt = (start < scutoff) ? 0 : 3; 1168 //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]); 1169 if (sce->band_type[w*16+g] <= minbt) { 1170 sce->zeroes[w*16+g] = 1; 1171 sce->band_type[w*16+g] = 0; 1172 } 1173 } 1174 //fprintf(stderr, "|"); 1175 } 1176 //fprintf(stderr, "\n"); 1177 //fprintf(stderr, "ba:%d br:%d \t\r", s->psy.bitres.alloc, tbits); 850 1178 } 851 1179 852 1180 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s, … … static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s, 967 1295 ESC_BT, 968 1296 lambda, 969 1297 INFINITY, 970 &b); 1298 &b, 1299 0); 971 1300 dist -= b; 972 1301 } 973 1302 dist *= 1.0f / 512.0f / lambda; 974 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512] );1303 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD); 975 1304 if (quant_max >= 8191) { // too much, return to the previous quantizer 976 1305 sce->sf_idx[w*16+g] = prev_scf; 977 1306 break; … … static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s, 1021 1350 SingleChannelElement *sce, 1022 1351 const float lambda) 1023 1352 { 1024 int i, w, w2, g; 1025 int minq = 255; 1353 int w, w2, g; 1354 float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f); 1355 float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f); 1356 const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF); 1357 const int maxq = minq + SCALE_MAX_DIFF - 1; 1026 1358 1027 1359 memset(sce->sf_idx, 0, sizeof(sce->sf_idx)); 1028 1360 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1029 1361 for (g = 0; g < sce->ics.num_swb; g++) { 1030 1362 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1031 1363 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 1032 if (band->energy <= band->threshold) {1033 sce->sf_idx[(w+w2)*16+g] = 218;1364 if (band->energy <= 0.05 * lowlambda * band->threshold) { 1365 sce->sf_idx[(w+w2)*16+g] = maxq; 1034 1366 sce->zeroes[(w+w2)*16+g] = 1; 1035 1367 } else { 1036 sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);1368 sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq); 1037 1369 sce->zeroes[(w+w2)*16+g] = 0; 1038 1370 } 1039 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);1040 1371 } 1041 1372 } 1042 1373 } 1043 for (i = 0; i < 128; i++) {1044 sce->sf_idx[i] = 140;1045 //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);1046 }1047 1374 //set the same quantizers inside window groups 1048 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 1049 for (g = 0; g < sce->ics.num_swb; g++) 1050 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) 1051 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g]; 1375 if (sce->ics.num_windows > 1) { 1376 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1377 for (g = 0; g < sce->ics.num_swb; g++) { 1378 if (sce->ics.group_len[w] > 1) { 1379 int avg_sf_idx = 0; 1380 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) 1381 avg_sf_idx += sce->sf_idx[w*16+g]; 1382 avg_sf_idx /= sce->ics.group_len[w]; 1383 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) 1384 sce->sf_idx[(w+w2)*16+g] = avg_sf_idx; 1385 } 1386 } 1387 } 1388 } 1389 } 1390 1391 static float bval2bmax(float b) 1392 { 1393 /* approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f))) */ 1394 return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f); 1052 1395 } 1053 1396 1054 1397 static void search_for_ms(AACEncContext *s, ChannelElement *cpe, 1055 1398 const float lambda) 1056 1399 { 1057 int start = 0, i, w, w2, g ;1400 int start = 0, i, w, w2, g, sid_sf_boost; 1058 1401 float M[128], S[128]; 1059 1402 float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3; 1403 float mslambda = FFMIN(1.0f, lambda / 120.0f); 1060 1404 SingleChannelElement *sce0 = &cpe->ch[0]; 1061 1405 SingleChannelElement *sce1 = &cpe->ch[1]; 1406 1062 1407 if (!cpe->common_window) 1063 1408 return; 1409 1064 1410 for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) { 1411 int min_sf_idx_mid = SCALE_MAX_POS; 1412 int min_sf_idx_side = SCALE_MAX_POS; 1413 for (g = 0; g < sce0->ics.num_swb; g++) { 1414 if (!sce0->zeroes[w*16+g]) 1415 min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]); 1416 if (!sce1->zeroes[w*16+g]) 1417 min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]); 1418 } 1419 1065 1420 for (g = 0; g < sce0->ics.num_swb; g++) { 1421 float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f; 1422 cpe->ms_mask[w*16+g] = 0; 1066 1423 if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) { 1067 float dist1 = 0.0f, dist2 = 0.0f; 1424 float Mmax = 0.0f, Smax = 0.0f; 1425 1426 /* Must compute mid/side SF and book for the whole window group */ 1068 1427 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { 1069 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];1070 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];1071 float minthr = FFMIN(band0->threshold, band1->threshold);1072 float maxthr = FFMAX(band0->threshold, band1->threshold);1073 1428 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1074 M[i] = (sce0-> coeffs[start+w2*128+i]1075 + sce1-> coeffs[start+w2*128+i]) * 0.5;1429 M[i] = (sce0->pcoeffs[start+w2*128+i] 1430 + sce1->pcoeffs[start+w2*128+i]) * 0.5f; 1076 1431 S[i] = M[i] 1077 - sce1->coeffs[start+w2*128+i]; 1432 - sce1->pcoeffs[start+w2*128+i]; 1433 } 1434 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1435 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1436 for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) { 1437 Mmax = FFMAX(Mmax, M34[i]); 1438 Smax = FFMAX(Smax, S34[i]); 1439 } 1440 } 1441 1442 for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) { 1443 float dist1 = 0.0f, dist2 = 0.0f; 1444 int B0 = 0, B1 = 0; 1445 int minidx; 1446 int mididx, sididx; 1447 int midcb, sidcb; 1448 1449 minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]); 1450 mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF); 1451 sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF); 1452 midcb = find_min_book(Mmax, mididx); 1453 sidcb = find_min_book(Smax, sididx); 1454 1455 if ((mididx > minidx) || (sididx > minidx)) { 1456 /* scalefactor range violation, bad stuff, will decrease quality unacceptably */ 1457 continue; 1458 } 1459 1460 /* No CB can be zero */ 1461 midcb = FFMAX(1,midcb); 1462 sidcb = FFMAX(1,sidcb); 1463 1464 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { 1465 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g]; 1466 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g]; 1467 float minthr = FFMIN(band0->threshold, band1->threshold); 1468 int b1,b2,b3,b4; 1469 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1470 M[i] = (sce0->coeffs[start+w2*128+i] 1471 + sce1->coeffs[start+w2*128+i]) * 0.5; 1472 S[i] = M[i] 1473 - sce1->coeffs[start+w2*128+i]; 1474 } 1475 abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1476 abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1477 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1478 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1479 dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128, 1480 L34, 1481 sce0->ics.swb_sizes[g], 1482 sce0->sf_idx[(w+w2)*16+g], 1483 sce0->band_type[w*16+g], 1484 lambda / band0->threshold, INFINITY, &b1, 0); 1485 dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128, 1486 R34, 1487 sce1->ics.swb_sizes[g], 1488 sce1->sf_idx[(w+w2)*16+g], 1489 sce1->band_type[w*16+g], 1490 lambda / band1->threshold, INFINITY, &b2, 0); 1491 dist2 += quantize_band_cost(s, M, 1492 M34, 1493 sce0->ics.swb_sizes[g], 1494 mididx, 1495 midcb, 1496 lambda / minthr, INFINITY, &b3, 0); 1497 dist2 += quantize_band_cost(s, S, 1498 S34, 1499 sce1->ics.swb_sizes[g], 1500 sididx, 1501 sidcb, 1502 lambda * mslambda / (minthr * bmax), INFINITY, &b4, 0); 1503 B0 += b1+b2; 1504 B1 += b3+b4; 1505 dist1 -= B0; 1506 dist2 -= B1; 1507 } 1508 cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0; 1509 if (cpe->ms_mask[w*16+g]) { 1510 sce0->sf_idx[w*16+g] = mididx; 1511 sce1->sf_idx[w*16+g] = sididx; 1512 sce0->band_type[w*16+g] = midcb; 1513 sce1->band_type[w*16+g] = sidcb; 1514 break; 1515 } else if (B1 > B0) { 1516 /* More boost won't fix this */ 1517 break; 1078 1518 } 1079 abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);1080 abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);1081 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);1082 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);1083 dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,1084 L34,1085 sce0->ics.swb_sizes[g],1086 sce0->sf_idx[(w+w2)*16+g],1087 sce0->band_type[(w+w2)*16+g],1088 lambda / band0->threshold, INFINITY, NULL);1089 dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,1090 R34,1091 sce1->ics.swb_sizes[g],1092 sce1->sf_idx[(w+w2)*16+g],1093 sce1->band_type[(w+w2)*16+g],1094 lambda / band1->threshold, INFINITY, NULL);1095 dist2 += quantize_band_cost(s, M,1096 M34,1097 sce0->ics.swb_sizes[g],1098 sce0->sf_idx[(w+w2)*16+g],1099 sce0->band_type[(w+w2)*16+g],1100 lambda / maxthr, INFINITY, NULL);1101 dist2 += quantize_band_cost(s, S,1102 S34,1103 sce1->ics.swb_sizes[g],1104 sce1->sf_idx[(w+w2)*16+g],1105 sce1->band_type[(w+w2)*16+g],1106 lambda / minthr, INFINITY, NULL);1107 1519 } 1108 cpe->ms_mask[w*16+g] = dist2 < dist1;1109 1520 } 1110 1521 start += sce0->ics.swb_sizes[g]; 1111 1522 } -
libavcodec/aacenc.c
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c index 5596b4b..c1bf389 100644
a b 46 46 #include "psymodel.h" 47 47 48 48 #define AAC_MAX_CHANNELS 6 49 #define CLIP_AVOIDANCE_FACTOR 0.95f 49 50 50 51 #define ERROR_IF(cond, ...) \ 51 52 if (cond) { \ … … 53 54 return AVERROR(EINVAL); \ 54 55 } 55 56 57 #define WARN_IF(cond, ...) \ 58 if (cond) { \ 59 av_log(avctx, AV_LOG_WARNING, __VA_ARGS__); \ 60 } 61 56 62 float ff_aac_pow34sf_tab[428]; 57 63 58 64 static const uint8_t swb_size_1024_96[] = { … … static const uint8_t *swb_size_1024[] = { 102 108 swb_size_1024_96, swb_size_1024_96, swb_size_1024_64, 103 109 swb_size_1024_48, swb_size_1024_48, swb_size_1024_32, 104 110 swb_size_1024_24, swb_size_1024_24, swb_size_1024_16, 105 swb_size_1024_16, swb_size_1024_16, swb_size_1024_8 111 swb_size_1024_16, swb_size_1024_16, swb_size_1024_8, 112 swb_size_1024_8 106 113 }; 107 114 108 115 static const uint8_t swb_size_128_96[] = { … … static const uint8_t *swb_size_128[] = { 131 138 swb_size_128_96, swb_size_128_96, swb_size_128_96, 132 139 swb_size_128_48, swb_size_128_48, swb_size_128_48, 133 140 swb_size_128_24, swb_size_128_24, swb_size_128_16, 134 swb_size_128_16, swb_size_128_16, swb_size_128_8 141 swb_size_128_16, swb_size_128_16, swb_size_128_8, 142 swb_size_128_8 135 143 }; 136 144 137 145 /** default channel configurations */ … … static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce, 260 268 for (i = 0; i < 1024; i += 128) 261 269 s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2); 262 270 memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024); 271 memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs)); 263 272 } 264 273 265 274 /** … … static void adjust_frame_information(ChannelElement *cpe, int chans) 311 320 start = 0; 312 321 maxsfb = 0; 313 322 cpe->ch[ch].pulse.num_pulse = 0; 314 for (w = 0; w < ics->num_windows*16; w += 16) { 315 for (g = 0; g < ics->num_swb; g++) { 316 //apply M/S 317 if (cpe->common_window && !ch && cpe->ms_mask[w + g]) { 318 for (i = 0; i < ics->swb_sizes[g]; i++) { 319 cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0; 320 cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i]; 323 for (w = 0; w < ics->num_windows; w += ics->group_len[w]) { 324 for (w2 = 0; w2 < ics->group_len[w]; w2++) { 325 start = (w+w2) * 128; 326 for (g = 0; g < ics->num_swb; g++) { 327 //apply M/S 328 if (cpe->common_window && !ch && cpe->ms_mask[w*16 + g]) { 329 for (i = 0; i < ics->swb_sizes[g]; i++) { 330 cpe->ch[0].coeffs[start+i] = (cpe->ch[0].pcoeffs[start+i] + cpe->ch[1].pcoeffs[start+i]) * 0.5f; 331 cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].pcoeffs[start+i]; 332 } 321 333 } 334 start += ics->swb_sizes[g]; 322 335 } 323 start += ics->swb_sizes[g]; 336 for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--) 337 ; 338 maxsfb = FFMAX(maxsfb, cmaxsfb); 324 339 } 325 for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)326 ;327 maxsfb = FFMAX(maxsfb, cmaxsfb);328 340 } 329 341 ics->max_sfb = maxsfb; 330 342 … … static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce) 430 442 sce->ics.swb_sizes[i], 431 443 sce->sf_idx[w*16 + i], 432 444 sce->band_type[w*16 + i], 433 s->lambda); 445 s->lambda, sce->ics.window_clipping[w]); 446 start += sce->ics.swb_sizes[i]; 447 } 448 } 449 } 450 451 /** 452 * Downscale spectral coefficients for near-clipping windows to avoid artifacts 453 */ 454 static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce) 455 { 456 int start, i, j, w, w2; 457 458 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 459 start = 0; 460 for (i = 0; i < sce->ics.max_sfb; i++) { 461 if (sce->ics.window_clipping[w]) { 462 for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++) { 463 float *swb_coeffs = sce->coeffs + start + w2*128; 464 for (j = 0; j < sce->ics.swb_sizes[i]; j++) 465 swb_coeffs[j] *= CLIP_AVOIDANCE_FACTOR; 466 } 467 } 434 468 start += sce->ics.swb_sizes[i]; 435 469 } 436 470 } … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 507 541 AACEncContext *s = avctx->priv_data; 508 542 float **samples = s->planar_samples, *samples2, *la, *overlap; 509 543 ChannelElement *cpe; 510 int i, ch, w, g, chans, tag, start_ch, ret ;544 int i, ch, w, g, chans, tag, start_ch, ret, frame_bits, its, ms_mode = 0; 511 545 int chan_el_counter[4]; 512 546 FFPsyWindowInfo windows[AAC_MAX_CHANNELS]; 513 547 … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 565 599 ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8]; 566 600 for (w = 0; w < ics->num_windows; w++) 567 601 ics->group_len[w] = wi[ch].grouping[w]; 602 for (w = 0; w < ics->num_windows; w++) 603 ics->window_clipping[w] = wi[ch].clipping[w]; 568 604 569 605 apply_window_and_mdct(s, &cpe->ch[ch], overlap); 606 avoid_clipping(s, &cpe->ch[ch]); 570 607 } 571 608 start_ch += chans; 572 609 } 573 610 if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0) 574 611 return ret; 612 613 frame_bits = 0; 614 its = 0; 575 615 do { 576 int frame_bits;577 616 int target_bits, too_many_bits, too_few_bits; 617 578 618 init_put_bits(&s->pb, avpkt->data, avpkt->size); 579 619 580 620 if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) 581 621 put_bitstream_info(s, LIBAVCODEC_IDENT); 582 622 start_ch = 0; 623 target_bits = 0; 583 624 memset(chan_el_counter, 0, sizeof(chan_el_counter)); 584 625 for (i = 0; i < s->chan_map[0]; i++) { 585 626 FFPsyWindowInfo* wi = windows + start_ch; … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 591 632 put_bits(&s->pb, 4, chan_el_counter[tag]++); 592 633 for (ch = 0; ch < chans; ch++) 593 634 coeffs[ch] = cpe->ch[ch].coeffs; 635 s->psy.bitres.alloc = -1; 636 s->psy.bitres.bits = avctx->frame_bits / s->channels; 594 637 s->psy.model->analyze(&s->psy, start_ch, coeffs, wi); 638 if (s->psy.bitres.alloc > 0) { 639 /* Lambda unused here on purpose, we need to take psy's unscaled allocation */ 640 target_bits += s->psy.bitres.alloc; 641 s->psy.bitres.alloc /= chans; 642 } 643 s->cur_type = tag; 595 644 for (ch = 0; ch < chans; ch++) { 596 645 s->cur_channel = start_ch + ch; 597 646 s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda); … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 626 675 if (cpe->common_window) { 627 676 put_ics_info(s, &cpe->ch[0].ics); 628 677 encode_ms_info(&s->pb, cpe); 678 if (cpe->ms_mode) ms_mode = 1; 629 679 } 630 680 } 631 681 for (ch = 0; ch < chans; ch++) { … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 635 685 start_ch += chans; 636 686 } 637 687 688 if (avctx->flags & CODEC_FLAG_QSCALE) { 689 // When using a constant Q-scale, don't mess with lambda 690 break; 691 } 692 693 // rate control stuff 694 // target either the nominal bitrate, or what psy's bit reservoir says to target 695 // whichever is greatest 638 696 frame_bits = put_bits_count(&s->pb); 639 if (frame_bits <= 6144 * s->channels - 3) { 640 s->psy.bitres.bits = frame_bits / s->channels; 697 target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate); 698 target_bits = FFMIN(target_bits, 6144 * s->channels - 3); 699 700 // When using ABR, be strict (but only for increasing) 701 too_many_bits = target_bits + target_bits/2; 702 too_few_bits = target_bits - target_bits/8; 703 //fprintf(stderr, "l:%f\t%d\t%d\t%d\t%d\n", s->lambda, too_few_bits, frame_bits, target_bits, too_many_bits); 704 705 if ( its == 0 /* for steady-state Q-scale tracking */ 706 || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits)) 707 || frame_bits >= 6144 * s->channels - 3 ) 708 { 709 float ratio = ((float)target_bits) / frame_bits; 710 711 if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) { 712 /* 713 This path is for steady-state Q-scale tracking 714 When frame bits fall within the stable range, we still need to adjust 715 lambda to maintain it like so in a stable fashion (large jumps in lambda 716 create artifacts and shoulda be avoided), but slowly 717 */ 718 ratio = sqrtf(sqrtf(ratio)); 719 ratio = av_clipf(ratio, 0.9f, 1.1f); 720 } else { 721 /* Not so fast though */ 722 ratio = sqrtf(ratio); 723 } 724 s->lambda = FFMIN(s->lambda * ratio, 65536.f); 725 726 // Keep iterating if we must reduce and lambda is in the sky 727 // NOT if we did M/S coding, it's undoable 728 if (s->lambda < 300.f || ratio > 0.9f) 729 break; 730 else { 731 if (ms_mode) { 732 for (i = 0; i < s->chan_map[0]; i++) { 733 // Must restore coeffs 734 chans = tag == TYPE_CPE ? 2 : 1; 735 cpe = &s->cpe[i]; 736 for (ch = 0; ch < chans; ch++) 737 memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs)); 738 } 739 } 740 its++; 741 } 742 } else { 641 743 break; 642 744 } 643 644 s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;645 646 745 } while (1); 647 746 648 747 put_bits(&s->pb, 3, TYPE_END); 649 748 flush_put_bits(&s->pb); 650 749 avctx->frame_bits = put_bits_count(&s->pb); 651 750 652 // rate control stuff653 if (!(avctx->flags & CODEC_FLAG_QSCALE)) {654 float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;655 s->lambda *= ratio;656 s->lambda = FFMIN(s->lambda, 65536.f);657 }658 659 751 if (!frame) 660 752 s->last_frame++; 661 753 … … static av_cold int aac_encode_init(AVCodecContext *avctx) 733 825 734 826 s->channels = avctx->channels; 735 827 736 ERROR_IF(i == 16, 828 ERROR_IF(i == 16 829 || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024)) 830 || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)), 737 831 "Unsupported sample rate %d\n", avctx->sample_rate); 738 832 ERROR_IF(s->channels > AAC_MAX_CHANNELS, 739 833 "Unsupported number of channels: %d\n", s->channels); 740 834 ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW, 741 835 "Unsupported profile %d\n", avctx->profile); 742 ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels, 743 "Too many bits per frame requested\n"); 836 WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels, 837 "Too many bits per frame requested, clamping to max\n"); 838 839 avctx->bit_rate = (int)FFMIN( 840 6144 * s->channels / 1024.0 * avctx->sample_rate, 841 avctx->bit_rate); 744 842 745 843 s->samplerate_index = i; 746 844 … … fail: 787 885 788 886 #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM 789 887 static const AVOption aacenc_options[] = { 790 {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},888 {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AACENC_FLAGS, "stereo_mode"}, 791 889 {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 792 890 {"ms_off", "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 793 891 {"ms_force", "Force Mid/Side for the whole frame if possible", 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, -
libavcodec/aacenc.h
diff --git a/libavcodec/aacenc.h b/libavcodec/aacenc.h index ecd6811..4de3531 100644
a b typedef struct AACCoefficientsEncoder { 52 52 void (*encode_window_bands_info)(struct AACEncContext *s, SingleChannelElement *sce, 53 53 int win, int group_len, const float lambda); 54 54 void (*quantize_and_encode_band)(struct AACEncContext *s, PutBitContext *pb, const float *in, int size, 55 int scale_idx, int cb, const float lambda );55 int scale_idx, int cb, const float lambda, int rtz); 56 56 void (*search_for_ms)(struct AACEncContext *s, ChannelElement *cpe, const float lambda); 57 57 } AACCoefficientsEncoder; 58 58 … … typedef struct AACEncContext { 78 78 FFPsyContext psy; 79 79 struct FFPsyPreprocessContext* psypp; 80 80 AACCoefficientsEncoder *coder; 81 int cur_channel; 81 int cur_channel; ///< current channel for coder context 82 82 int last_frame; 83 83 float lambda; 84 enum RawDataBlockType cur_type; ///< channel group type cur_channel belongs to 85 84 86 AudioFrameQueue afq; 85 87 DECLARE_ALIGNED(16, int, qcoefs)[96]; ///< quantized coefficients 86 88 DECLARE_ALIGNED(32, float, scoefs)[1024]; ///< scaled coefficients -
libavcodec/aacpsy.c
diff --git a/libavcodec/aacpsy.c b/libavcodec/aacpsy.c index d2a782e..ddde1da 100644
a b enum { 87 87 }; 88 88 89 89 #define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f) 90 #define PSY_3GPP_PE_TO_BITS(bits) ((bits) / 1.18f) 90 91 91 92 /* LAME psy model constants */ 92 93 #define PSY_LAME_FIR_LEN 21 ///< LAME psy model FIR order … … enum { 95 96 #define AAC_NUM_BLOCKS_SHORT 8 ///< number of blocks in a short sequence 96 97 #define PSY_LAME_NUM_SUBBLOCKS 3 ///< Number of sub-blocks in each short block 97 98 99 #define CLIPPING_THRESHOLD 0.98f 100 98 101 /** 99 102 * @} 100 103 */ … … typedef struct AacPsyContext{ 157 160 } pe; 158 161 AacPsyCoeffs psy_coef[2][64]; 159 162 AacPsyChannel *ch; 163 float global_quality; ///< normalized global quality taken from avctx 160 164 }AacPsyContext; 161 165 162 166 /** … … static float lame_calc_attack_threshold(int bitrate) 255 259 /** 256 260 * LAME psy model specific initialization 257 261 */ 258 static av_cold void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) 259 { 262 static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) { 260 263 int i, j; 261 264 262 265 for (i = 0; i < avctx->channels; i++) { … … static av_cold int psy_3gpp_init(FFPsyContext *ctx) { 299 302 float bark; 300 303 int i, j, g, start; 301 304 float prev, minscale, minath, minsnr, pe_min; 302 const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;305 int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->channels); 303 306 const int bandwidth = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx); 304 307 const float num_bark = calc_bark((float)bandwidth); 305 308 306 309 ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext)); 307 310 pctx = (AacPsyContext*) ctx->model_priv_data; 311 pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f; 308 312 313 if (ctx->avctx->flags & CODEC_FLAG_QSCALE) { 314 /* Use the target average bitrate to compute spread parameters */ 315 chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120)); 316 } 317 309 318 pctx->chan_bitrate = chan_bitrate; 310 pctx->frame_bits = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;319 pctx->frame_bits = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate); 311 320 pctx->pe.min = 8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f); 312 321 pctx->pe.max = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f); 313 322 ctx->bitres.size = 6144 - pctx->frame_bits; 314 323 ctx->bitres.size -= ctx->bitres.size % 8; 315 324 pctx->fill_level = ctx->bitres.size; 316 325 minath = ath(3410, ATH_ADD); 326 317 327 for (j = 0; j < 2; j++) { 318 328 AacPsyCoeffs *coeffs = pctx->psy_coef[j]; 319 329 const uint8_t *band_sizes = ctx->bands[j]; … … static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx, 391 401 int channel, int prev_type) 392 402 { 393 403 int i, j; 394 int br = ctx->avctx->bit_rate / ctx->avctx->channels;404 int br = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate; 395 405 int attack_ratio = br <= 16000 ? 18 : 10; 396 406 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data; 397 407 AacPsyChannel *pch = &pctx->ch[channel]; … … static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size, 501 511 ctx->pe.max = FFMAX(pe, ctx->pe.max); 502 512 ctx->pe.min = FFMIN(pe, ctx->pe.min); 503 513 504 return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits); 514 /* NOTE: allocate a minimum of 1/8th average frame bits, to avoid 515 * reservoir starvation from producing zero-bit frames 516 */ 517 return FFMIN( 518 ctx->frame_bits * bit_factor, 519 FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8)); 505 520 } 506 521 507 522 static float calc_pe_3gpp(AacPsyBand *band) … … static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr, 566 581 return thr; 567 582 } 568 583 584 static av_always_inline float sqrf(float f) 585 { 586 return f*f; 587 } 588 569 589 #ifndef calc_thr_3gpp 570 590 static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch, 571 const uint8_t *band_sizes, const float *coefs )591 const uint8_t *band_sizes, const float *coefs, float q) 572 592 { 573 593 int i, w, g; 574 int start = 0; 594 int start = 0, wstart = 0, end = 1024 / wi->num_windows; 595 float iq2 = sqrf(1.0f / FFMAX(0.125f, q)); 575 596 for (w = 0; w < wi->num_windows*16; w += 16) { 597 wstart = start; 576 598 for (g = 0; g < num_bands; g++) { 577 599 AacPsyBand *band = &pch->band[w+g]; 578 600 579 601 float form_factor = 0.0f; 580 float Temp ;602 float Temp, absthr; 581 603 band->energy = 0.0f; 582 604 for (i = 0; i < band_sizes[g]; i++) { 583 605 band->energy += coefs[start+i] * coefs[start+i]; 584 606 form_factor += sqrtf(fabs(coefs[start+i])); 585 607 } 608 // Absolute threshold of hearing approx taking the low point 609 // to be 16-bit quantization noise, scaled up to improve vbr 610 absthr = sqrf(sqrf(FFMAX(1.0f, (abs(start - wstart - end/16) - end/64) / end * 6.5f)) * end) * 3.0517578125e-5; 611 absthr *= band_sizes[g]; 586 612 Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0; 587 band->thr = band->energy * 0.001258925f;613 band->thr = FFMAX(absthr * iq2, band->energy * 0.001258925f); 588 614 band->nz_lines = form_factor * sqrtf(Temp); 589 615 590 616 start += band_sizes[g]; … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 628 654 const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8]; 629 655 AacPsyCoeffs *coeffs = pctx->psy_coef[wi->num_windows == 8]; 630 656 const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG; 631 657 632 658 //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation" 633 calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs );659 calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, pctx->global_quality); 634 660 635 661 //modify thresholds and energies - spread, threshold in quiet, pre-echo control 636 662 for (w = 0; w < wi->num_windows*16; w += 16) { … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 671 697 672 698 /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */ 673 699 ctx->ch[channel].entropy = pe; 674 desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8); 675 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); 676 /* NOTE: PE correction is kept simple. During initial testing it had very 677 * little effect on the final bitrate. Probably a good idea to come 678 * back and do more testing later. 679 */ 680 if (ctx->bitres.bits > 0) 681 desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits), 682 0.85f, 1.15f); 700 if (ctx->avctx->flags & CODEC_FLAG_QSCALE) { 701 /* (2.5 * 120) achieves almost transparent rate, and we want to give 702 * ample room downwards, so we make that equivalent to QSCALE=2.4 703 */ 704 desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f); 705 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe)); 706 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping 707 708 /* PE slope smoothing */ 709 if (ctx->bitres.bits > 0) { 710 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe)); 711 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping 712 } 713 714 pctx->pe.max = FFMAX(pe, pctx->pe.max); 715 pctx->pe.min = FFMIN(pe, pctx->pe.min); 716 } else { 717 desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8); 718 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); 719 720 /* NOTE: PE correction is kept simple. During initial testing it had very 721 * little effect on the final bitrate. Probably a good idea to come 722 * back and do more testing later. 723 */ 724 if (ctx->bitres.bits > 0) 725 desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits), 726 0.85f, 1.15f); 727 } 683 728 pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits); 684 729 ctx->bitres.alloc = desired_bits; 730 685 731 if (desired_pe < pe) { 686 732 /* 5.6.1.3.4 "First Estimation of the reduction value" */ 687 733 for (w = 0; w < wi->num_windows*16; w += 16) { … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 717 763 } 718 764 desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f); 719 765 if (active_lines > 0.0f) 720 reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);766 reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines); 721 767 722 768 pe = 0.0f; 723 769 for (w = 0; w < wi->num_windows*16; w += 16) { … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 827 873 int grouping = 0; 828 874 int uselongblock = 1; 829 875 int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 }; 876 uint8_t clippings[AAC_NUM_BLOCKS_SHORT]; 830 877 int i; 831 878 FFPsyWindowInfo wi = { { 0 } }; 832 879 … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 841 888 842 889 /* LAME comment: apply high pass filter of fs/4 */ 843 890 psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs); 844 891 845 892 /* Calculate the energies of each sub-shortblock */ 846 893 for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) { 847 894 energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)]; … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 916 963 917 964 lame_apply_block_type(pch, &wi, uselongblock); 918 965 966 /* Calculate input sample maximums and evaluate clipping risk */ 967 if (audio) { 968 for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++) { 969 const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT; 970 float max = 0; 971 int j; 972 for (j = 0; j < AAC_BLOCK_SIZE_SHORT; j++) 973 max = FFMAX(max, fabsf(wbuf[j])); 974 clippings[i] = (max > CLIPPING_THRESHOLD) ? 1 : 0; 975 } 976 } else { 977 for (i = 0; i < 8; i++) 978 clippings[i] = 0; 979 } 980 919 981 wi.window_type[1] = prev_type; 920 982 if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) { 983 int clipping = 0; 984 921 985 wi.num_windows = 1; 922 986 wi.grouping[0] = 1; 923 987 if (wi.window_type[0] == LONG_START_SEQUENCE) 924 988 wi.window_shape = 0; 925 989 else 926 990 wi.window_shape = 1; 991 992 for (i = 0; i < 8 && !clipping; i++) 993 clipping = clippings[i]; 994 wi.clipping[0] = clipping; 927 995 } else { 928 int lastgrp = 0 ;996 int lastgrp = 0, anyclipped = 0; 929 997 930 998 wi.num_windows = 8; 931 999 wi.window_shape = 0; … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 934 1002 lastgrp = i; 935 1003 wi.grouping[lastgrp]++; 936 1004 } 1005 1006 for (i = 0; i < 8; i += wi.grouping[i]) { 1007 int w, clipping = 0; 1008 for (w = 0; w < wi.grouping[i] && !clipping; w++) 1009 clipping = clippings[i+w]; 1010 wi.clipping[i] = clipping; 1011 if (clipping) anyclipped = 1; 1012 } 937 1013 } 938 1014 939 1015 /* Determine grouping, based on the location of the first attack, and save for … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 948 1024 break; 949 1025 } 950 1026 } 1027 951 1028 pch->next_grouping = window_grouping[grouping]; 952 1029 953 1030 pch->prev_attack = attacks[8]; -
libavcodec/psymodel.c
diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c index 22d2497..5e9a6fd 100644
a b FFPsyChannelGroup *ff_psy_find_group(FFPsyContext *ctx, int channel) 75 75 76 76 av_cold void ff_psy_end(FFPsyContext *ctx) 77 77 { 78 if (ctx->model && ctx->model->end)78 if (ctx->model->end) 79 79 ctx->model->end(ctx); 80 80 av_freep(&ctx->bands); 81 81 av_freep(&ctx->num_bands); … … av_cold struct FFPsyPreprocessContext* ff_psy_preprocess_init(AVCodecContext *av 101 101 ctx = av_mallocz(sizeof(FFPsyPreprocessContext)); 102 102 ctx->avctx = avctx; 103 103 104 if (avctx->cutoff > 0)105 cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate;106 107 if (!cutoff_coeff && avctx->codec_id == AV_CODEC_ID_AAC)108 cutoff_coeff = 2.0 * AAC_CUTOFF(avctx) / avctx->sample_rate; 109 110 if (cutoff_coeff && cutoff_coeff < 0.98)111 ctx->fcoeffs = ff_iir_filter_init_coeffs(avctx, FF_FILTER_TYPE_BUTTERWORTH,112 FF_FILTER_MODE_LOWPASS, FILT_ORDER,113 cutoff_coeff, 0.0, 0.0);114 if (ctx->fcoeffs) {115 ctx->fstate = av_mallocz_array(sizeof(ctx->fstate[0]), avctx->channels);116 for (i = 0; i < avctx->channels; i++)117 ctx->fstate[i] = ff_iir_filter_init_state(FILT_ORDER);104 /* AAC has its own LP method */ 105 if (avctx->codec_id != AV_CODEC_ID_AAC) { 106 if (avctx->cutoff > 0) 107 cutoff_coeff = 2.0 * avctx->cutoff / avctx->sample_rate; 108 109 if (cutoff_coeff && cutoff_coeff < 0.98) 110 ctx->fcoeffs = ff_iir_filter_init_coeffs(avctx, FF_FILTER_TYPE_BUTTERWORTH, 111 FF_FILTER_MODE_LOWPASS, FILT_ORDER, 112 cutoff_coeff, 0.0, 0.0); 113 if (ctx->fcoeffs) { 114 ctx->fstate = av_mallocz(sizeof(ctx->fstate[0]) * avctx->channels); 115 for (i = 0; i < avctx->channels; i++) 116 ctx->fstate[i] = ff_iir_filter_init_state(FILT_ORDER); 117 } 118 118 } 119 119 120 120 ff_iir_filter_init(&ctx->fiir); -
libavcodec/psymodel.h
diff --git a/libavcodec/psymodel.h b/libavcodec/psymodel.h index d1a126a..d0e1294 100644
a b 27 27 /** maximum possible number of bands */ 28 28 #define PSY_MAX_BANDS 128 29 29 /** maximum number of channels */ 30 #define PSY_MAX_CHANS 2 030 #define PSY_MAX_CHANS 24 31 31 32 #define AAC_CUTOFF(s) (s->bit_rate ? FFMIN3(4000 + s->bit_rate/8, 12000 + s->bit_rate/32, s->sample_rate / 2) : (s->sample_rate / 2)) 32 /* cutoff for VBR is purposedly increased, since LP filtering actually 33 * hinders VBR performance rather than the opposite 34 */ 35 #define _AAC_CUTOFF(bit_rate,channels,sample_rate) (bit_rate ? FFMIN3(FFMIN3( \ 36 bit_rate/channels/2, \ 37 3000 + bit_rate/channels/4, \ 38 12000 + bit_rate/channels/16), \ 39 20000, \ 40 sample_rate / 2): (sample_rate / 2)) 41 #define AAC_CUTOFF(s) ( \ 42 (s->flags & CODEC_FLAG_QSCALE) \ 43 ? /*_AAC_CUTOFF(((int)(480000.0f*(s->global_quality ? s->global_quality/120.0f : 1.0f))), 1, s->sample_rate)*/s->sample_rate / 2 \ 44 : _AAC_CUTOFF(s->bit_rate, s->channels, s->sample_rate) \ 45 ) 33 46 34 47 /** 35 48 * single band psychoacoustic information … … typedef struct FFPsyWindowInfo { 67 80 int window_shape; ///< window shape (sine/KBD/whatever) 68 81 int num_windows; ///< number of windows in a frame 69 82 int grouping[8]; ///< window grouping (for e.g. AAC) 83 uint8_t clipping[8]; ///< set if a window group's samples are near clipping (for e.g. AAC) 70 84 int *window_sizes; ///< sequence of window sizes inside one frame (for eg. WMA) 71 85 } FFPsyWindowInfo; 72 86 … … typedef struct FFPsyContext { 88 102 struct { 89 103 int size; ///< size of the bitresevoir in bits 90 104 int bits; ///< number of bits used in the bitresevoir 105 int alloc; ///< number of bits allocated by the psy, or -1 if no allocation was done 91 106 } bitres; 92 107 93 108 void* model_priv_data; ///< psychoacoustic model implementation private data
