Ticket #2686: aac-improvements-wip-v8.patch
| File aac-improvements-wip-v8.patch, 71.8 KB (added by , 12 years ago) |
|---|
-
libavcodec/aac.h
diff --git a/libavcodec/aac.h b/libavcodec/aac.h index 89f463e..b880bb3 100644
a b 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 /** -
libavcodec/aaccoder.c
diff --git a/libavcodec/aaccoder.c b/libavcodec/aaccoder.c index 50a246f..92a7a1f 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 : 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; 1066 1422 if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) { 1067 float dist1 = 0.0f, dist2 = 0.0f; 1423 float Mmax = 0.0f, Smax = 0.0f; 1424 1425 /* Must compute mid/side SF and book for the whole window group */ 1068 1426 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 1427 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1074 1428 M[i] = (sce0->coeffs[start+w2*128+i] 1075 1429 + sce1->coeffs[start+w2*128+i]) * 0.5; 1076 1430 S[i] = M[i] 1077 1431 - sce1->coeffs[start+w2*128+i]; 1078 1432 } 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); 1433 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1434 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1435 for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) { 1436 Mmax = FFMAX(Mmax, M34[i]); 1437 Smax = FFMAX(Smax, S34[i]); 1438 } 1107 1439 } 1108 cpe->ms_mask[w*16+g] = dist2 < dist1; 1440 1441 for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) { 1442 float dist1 = 0.0f, dist2 = 0.0f; 1443 int B0 = 0, B1 = 0; 1444 int minidx; 1445 int mididx, sididx; 1446 int midcb, sidcb; 1447 1448 minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]); 1449 mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF); 1450 sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF); 1451 midcb = find_min_book(Mmax, mididx); 1452 sidcb = find_min_book(Smax, sididx); 1453 1454 if ((mididx > minidx) || (sididx > minidx)) { 1455 /* scalefactor range violation, bad stuff, will decrease quality unacceptably */ 1456 continue; 1457 } 1458 1459 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { 1460 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g]; 1461 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g]; 1462 float minthr = FFMIN(band0->threshold, band1->threshold); 1463 int b1,b2,b3,b4; 1464 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1465 M[i] = (sce0->coeffs[start+w2*128+i] 1466 + sce1->coeffs[start+w2*128+i]) * 0.5; 1467 S[i] = M[i] 1468 - sce1->coeffs[start+w2*128+i]; 1469 } 1470 abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1471 abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1472 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1473 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1474 dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128, 1475 L34, 1476 sce0->ics.swb_sizes[g], 1477 sce0->sf_idx[(w+w2)*16+g], 1478 sce0->band_type[(w+w2)*16+g], 1479 lambda / band0->threshold, INFINITY, &b1, 0); 1480 dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128, 1481 R34, 1482 sce1->ics.swb_sizes[g], 1483 sce1->sf_idx[(w+w2)*16+g], 1484 sce1->band_type[(w+w2)*16+g], 1485 lambda / band1->threshold, INFINITY, &b2, 0); 1486 dist2 += quantize_band_cost(s, M, 1487 M34, 1488 sce0->ics.swb_sizes[g], 1489 mididx, 1490 midcb, 1491 lambda / minthr, INFINITY, &b3, 0); 1492 dist2 += quantize_band_cost(s, S, 1493 S34, 1494 sce1->ics.swb_sizes[g], 1495 sididx, 1496 sidcb, 1497 lambda * mslambda / (minthr * bmax), INFINITY, &b4, 0); 1498 B0 += b1+b2; 1499 B1 += b3+b4; 1500 dist1 -= B0; 1501 dist2 -= B1; 1502 } 1503 cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0; 1504 if (cpe->ms_mask[w*16+g]) { 1505 sce0->sf_idx[w*16+g] = mididx; 1506 sce0->band_type[w*16+g] = midcb; 1507 sce1->sf_idx[w*16+g] = sididx; 1508 sce1->band_type[w*16+g] = sidcb; 1509 break; 1510 } else if (B1 > B0) { 1511 /* More boost won't fix this */ 1512 break; 1513 } 1514 } 1515 } else { 1516 cpe->ms_mask[w*16+g] = 0; 1109 1517 } 1110 1518 start += sce0->ics.swb_sizes[g]; 1111 1519 } -
libavcodec/aacenc.c
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c index 5596b4b..646eabe 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 void adjust_frame_information(ChannelElement *cpe, int chans) 311 317 start = 0; 312 318 maxsfb = 0; 313 319 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]; 320 for (w = 0; w < ics->num_windows; w += ics->group_len[w]) { 321 for (w2 = w; w2 < w + ics->group_len[w]; w2++) { 322 for (g = 0; g < ics->num_swb; g++) { 323 //apply M/S 324 if (cpe->common_window && !ch && cpe->ms_mask[w*16 + g]) { 325 for (i = 0; i < ics->swb_sizes[g]; i++) { 326 cpe->ch[0].coeffs[start+i] = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) / 2.0; 327 cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].coeffs[start+i]; 328 } 321 329 } 330 start += ics->swb_sizes[g]; 322 331 } 323 start += ics->swb_sizes[g]; 332 for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--) 333 ; 334 maxsfb = FFMAX(maxsfb, cmaxsfb); 324 335 } 325 for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w+cmaxsfb-1]; cmaxsfb--)326 ;327 maxsfb = FFMAX(maxsfb, cmaxsfb);328 336 } 329 337 ics->max_sfb = maxsfb; 330 338 … … static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce) 430 438 sce->ics.swb_sizes[i], 431 439 sce->sf_idx[w*16 + i], 432 440 sce->band_type[w*16 + i], 433 s->lambda); 441 s->lambda, sce->ics.window_clipping[w]); 442 start += sce->ics.swb_sizes[i]; 443 } 444 } 445 } 446 447 /** 448 * Downscale spectral coefficients for near-clipping windows to avoid artifacts 449 */ 450 static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce) 451 { 452 int start, i, j, w, w2; 453 454 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 455 start = 0; 456 for (i = 0; i < sce->ics.max_sfb; i++) { 457 if (sce->ics.window_clipping[w]) { 458 for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++) { 459 float *swb_coeffs = sce->coeffs + start + w2*128; 460 for (j = 0; j < sce->ics.swb_sizes[i]; j++) 461 swb_coeffs[j] *= CLIP_AVOIDANCE_FACTOR; 462 } 463 } 434 464 start += sce->ics.swb_sizes[i]; 435 465 } 436 466 } … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 507 537 AACEncContext *s = avctx->priv_data; 508 538 float **samples = s->planar_samples, *samples2, *la, *overlap; 509 539 ChannelElement *cpe; 510 int i, ch, w, g, chans, tag, start_ch, ret ;540 int i, ch, w, g, chans, tag, start_ch, ret, frame_bits, its; 511 541 int chan_el_counter[4]; 512 542 FFPsyWindowInfo windows[AAC_MAX_CHANNELS]; 513 543 … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 565 595 ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8]; 566 596 for (w = 0; w < ics->num_windows; w++) 567 597 ics->group_len[w] = wi[ch].grouping[w]; 598 for (w = 0; w < ics->num_windows; w++) 599 ics->window_clipping[w] = wi[ch].clipping[w]; 568 600 569 601 apply_window_and_mdct(s, &cpe->ch[ch], overlap); 602 avoid_clipping(s, &cpe->ch[ch]); 570 603 } 571 604 start_ch += chans; 572 605 } 573 606 if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0) 574 607 return ret; 608 609 frame_bits = 0; 610 its = 0; 575 611 do { 576 int frame_bits;577 612 int target_bits, too_many_bits, too_few_bits; 613 578 614 init_put_bits(&s->pb, avpkt->data, avpkt->size); 579 615 580 616 if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) 581 617 put_bitstream_info(s, LIBAVCODEC_IDENT); 582 618 start_ch = 0; 619 target_bits = 0; 583 620 memset(chan_el_counter, 0, sizeof(chan_el_counter)); 584 621 for (i = 0; i < s->chan_map[0]; i++) { 585 622 FFPsyWindowInfo* wi = windows + start_ch; … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 591 628 put_bits(&s->pb, 4, chan_el_counter[tag]++); 592 629 for (ch = 0; ch < chans; ch++) 593 630 coeffs[ch] = cpe->ch[ch].coeffs; 631 s->psy.bitres.alloc = -1; 632 s->psy.bitres.bits = avctx->frame_bits / s->channels; 594 633 s->psy.model->analyze(&s->psy, start_ch, coeffs, wi); 634 if (s->psy.bitres.alloc > 0) { 635 /* Lambda unused here on purpose, we need to take psy's unscaled allocation */ 636 target_bits += s->psy.bitres.alloc; 637 s->psy.bitres.alloc /= chans; 638 } 639 s->cur_type = tag; 595 640 for (ch = 0; ch < chans; ch++) { 596 641 s->cur_channel = start_ch + ch; 597 642 s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda); … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 635 680 start_ch += chans; 636 681 } 637 682 683 if (avctx->flags & CODEC_FLAG_QSCALE) { 684 // When using a constant Q-scale, don't mess with lambda 685 break; 686 } 687 688 // rate control stuff 689 // target either the nominal bitrate, or what psy's bit reservoir says to target 690 // whichever is greatest 638 691 frame_bits = put_bits_count(&s->pb); 639 if (frame_bits <= 6144 * s->channels - 3) { 640 s->psy.bitres.bits = frame_bits / s->channels; 692 target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate); 693 target_bits = FFMIN(target_bits, 6144 * s->channels - 3); 694 695 // When using ABR, be strict (but only for increasing) 696 too_many_bits = target_bits + target_bits/2; 697 too_few_bits = target_bits - target_bits/8; 698 //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); 699 700 if ( its == 0 /* for steady-state Q-scale tracking */ 701 || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits)) 702 || frame_bits >= 6144 * s->channels - 3 ) 703 { 704 float ratio = ((float)target_bits) / frame_bits; 705 706 if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) { 707 /* 708 This path is for steady-state Q-scale tracking 709 When frame bits fall within the stable range, we still need to adjust 710 lambda to maintain it like so in a stable fashion (large jumps in lambda 711 create artifacts and shoulda be avoided), but slowly 712 */ 713 ratio = sqrtf(sqrtf(ratio)); 714 ratio = av_clipf(ratio, 0.9f, 1.1f); 715 } else { 716 /* Not so fast though */ 717 ratio = sqrtf(ratio); 718 } 719 s->lambda = FFMIN(s->lambda * ratio, 65536.f); 720 721 // Keep iterating if we must reduce and lambda is in the sky 722 if (s->lambda < 300.f || ratio > 0.9f) 723 break; 724 else 725 its++; 726 } else { 641 727 break; 642 728 } 643 644 s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;645 646 729 } while (1); 647 730 648 731 put_bits(&s->pb, 3, TYPE_END); 649 732 flush_put_bits(&s->pb); 650 733 avctx->frame_bits = put_bits_count(&s->pb); 651 734 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 735 if (!frame) 660 736 s->last_frame++; 661 737 … … static av_cold int aac_encode_init(AVCodecContext *avctx) 739 815 "Unsupported number of channels: %d\n", s->channels); 740 816 ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW, 741 817 "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"); 818 WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels, 819 "Too many bits per frame requested, clamping to max\n"); 820 821 avctx->bit_rate = (int)FFMIN( 822 6144 * s->channels / 1024.0 * avctx->sample_rate, 823 avctx->bit_rate); 744 824 745 825 s->samplerate_index = i; 746 826 … … fail: 787 867 788 868 #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM 789 869 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"},870 {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AACENC_FLAGS, "stereo_mode"}, 791 871 {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 792 872 {"ms_off", "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 793 873 {"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..a115c07 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 av_cold int psy_3gpp_init(FFPsyContext *ctx) { 299 303 float bark; 300 304 int i, j, g, start; 301 305 float prev, minscale, minath, minsnr, pe_min; 302 const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;306 int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->channels); 303 307 const int bandwidth = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx); 304 308 const float num_bark = calc_bark((float)bandwidth); 305 309 306 310 ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext)); 307 311 pctx = (AacPsyContext*) ctx->model_priv_data; 312 pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f; 308 313 314 if (ctx->avctx->flags & CODEC_FLAG_QSCALE) { 315 /* Use the target average bitrate to compute spread parameters */ 316 chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120)); 317 } 318 309 319 pctx->chan_bitrate = chan_bitrate; 310 pctx->frame_bits = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;320 pctx->frame_bits = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate); 311 321 pctx->pe.min = 8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f); 312 322 pctx->pe.max = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f); 313 323 ctx->bitres.size = 6144 - pctx->frame_bits; 314 324 ctx->bitres.size -= ctx->bitres.size % 8; 315 325 pctx->fill_level = ctx->bitres.size; 316 326 minath = ath(3410, ATH_ADD); 327 317 328 for (j = 0; j < 2; j++) { 318 329 AacPsyCoeffs *coeffs = pctx->psy_coef[j]; 319 330 const uint8_t *band_sizes = ctx->bands[j]; … … static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx, 391 402 int channel, int prev_type) 392 403 { 393 404 int i, j; 394 int br = ctx->avctx->bit_rate / ctx->avctx->channels;405 int br = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate; 395 406 int attack_ratio = br <= 16000 ? 18 : 10; 396 407 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data; 397 408 AacPsyChannel *pch = &pctx->ch[channel]; … … static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size, 501 512 ctx->pe.max = FFMAX(pe, ctx->pe.max); 502 513 ctx->pe.min = FFMIN(pe, ctx->pe.min); 503 514 504 return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits); 515 /* NOTE: allocate a minimum of 1/8th average frame bits, to avoid 516 * reservoir starvation from producing zero-bit frames 517 */ 518 return FFMIN( 519 ctx->frame_bits * bit_factor, 520 FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8)); 505 521 } 506 522 507 523 static float calc_pe_3gpp(AacPsyBand *band) … … static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr, 566 582 return thr; 567 583 } 568 584 585 static av_always_inline float sqrf(float f) 586 { 587 return f*f; 588 } 589 569 590 #ifndef calc_thr_3gpp 570 591 static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch, 571 const uint8_t *band_sizes, const float *coefs )592 const uint8_t *band_sizes, const float *coefs, float q) 572 593 { 573 594 int i, w, g; 574 int start = 0; 595 int start = 0, wstart = 0, end = 1024 / wi->num_windows; 596 float iq2 = sqrf(1.0f / FFMAX(0.125f, q)); 575 597 for (w = 0; w < wi->num_windows*16; w += 16) { 598 wstart = start; 576 599 for (g = 0; g < num_bands; g++) { 577 600 AacPsyBand *band = &pch->band[w+g]; 578 601 579 602 float form_factor = 0.0f; 580 float Temp ;603 float Temp, absthr; 581 604 band->energy = 0.0f; 582 605 for (i = 0; i < band_sizes[g]; i++) { 583 606 band->energy += coefs[start+i] * coefs[start+i]; 584 607 form_factor += sqrtf(fabs(coefs[start+i])); 585 608 } 609 // Absolute threshold of hearing approx taking the low point 610 // to be 16-bit quantization noise, scaled up to improve vbr 611 absthr = sqrf(sqrf(FFMAX(1.0f, (abs(start - wstart - end/16) - end/64) / end * 6.5f)) * end) * 3.0517578125e-5; 612 absthr *= band_sizes[g]; 586 613 Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0; 587 band->thr = band->energy * 0.001258925f;614 band->thr = FFMAX(absthr * iq2, band->energy * 0.001258925f); 588 615 band->nz_lines = form_factor * sqrtf(Temp); 589 616 590 617 start += band_sizes[g]; … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 628 655 const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8]; 629 656 AacPsyCoeffs *coeffs = pctx->psy_coef[wi->num_windows == 8]; 630 657 const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG; 631 658 632 659 //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation" 633 calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs );660 calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, pctx->global_quality); 634 661 635 662 //modify thresholds and energies - spread, threshold in quiet, pre-echo control 636 663 for (w = 0; w < wi->num_windows*16; w += 16) { … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 671 698 672 699 /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */ 673 700 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); 701 if (ctx->avctx->flags & CODEC_FLAG_QSCALE) { 702 /* (2.5 * 120) achieves almost transparent rate, and we want to give 703 * ample room downwards, so we make that equivalent to QSCALE=2.4 704 */ 705 desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f); 706 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe)); 707 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping 708 709 /* PE slope smoothing */ 710 if (ctx->bitres.bits > 0) { 711 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe)); 712 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping 713 } 714 715 pctx->pe.max = FFMAX(pe, pctx->pe.max); 716 pctx->pe.min = FFMIN(pe, pctx->pe.min); 717 } else { 718 desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8); 719 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); 720 721 /* NOTE: PE correction is kept simple. During initial testing it had very 722 * little effect on the final bitrate. Probably a good idea to come 723 * back and do more testing later. 724 */ 725 if (ctx->bitres.bits > 0) 726 desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits), 727 0.85f, 1.15f); 728 } 683 729 pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits); 684 730 ctx->bitres.alloc = desired_bits; 731 685 732 if (desired_pe < pe) { 686 733 /* 5.6.1.3.4 "First Estimation of the reduction value" */ 687 734 for (w = 0; w < wi->num_windows*16; w += 16) { … … static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 717 764 } 718 765 desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f); 719 766 if (active_lines > 0.0f) 720 reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);767 reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines); 721 768 722 769 pe = 0.0f; 723 770 for (w = 0; w < wi->num_windows*16; w += 16) { … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 827 874 int grouping = 0; 828 875 int uselongblock = 1; 829 876 int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 }; 877 uint8_t clippings[AAC_NUM_BLOCKS_SHORT]; 830 878 int i; 831 879 FFPsyWindowInfo wi = { { 0 } }; 832 880 … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 841 889 842 890 /* LAME comment: apply high pass filter of fs/4 */ 843 891 psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs); 844 892 845 893 /* Calculate the energies of each sub-shortblock */ 846 894 for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) { 847 895 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 964 917 965 lame_apply_block_type(pch, &wi, uselongblock); 918 966 967 /* Calculate input sample maximums and evaluate clipping risk */ 968 if (audio) { 969 for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++) { 970 const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT; 971 float max = 0; 972 int j; 973 for (j = 0; j < AAC_BLOCK_SIZE_SHORT; j++) 974 max = FFMAX(max, fabsf(wbuf[j])); 975 clippings[i] = (max > CLIPPING_THRESHOLD) ? 1 : 0; 976 } 977 } else { 978 for (i = 0; i < 8; i++) 979 clippings[i] = 0; 980 } 981 919 982 wi.window_type[1] = prev_type; 920 983 if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) { 984 int clipping = 0; 985 921 986 wi.num_windows = 1; 922 987 wi.grouping[0] = 1; 923 988 if (wi.window_type[0] == LONG_START_SEQUENCE) 924 989 wi.window_shape = 0; 925 990 else 926 991 wi.window_shape = 1; 992 993 for (i = 0; i < 8 && !clipping; i++) 994 clipping = clippings[i]; 995 wi.clipping[0] = clipping; 927 996 } else { 928 int lastgrp = 0 ;997 int lastgrp = 0, anyclipped = 0; 929 998 930 999 wi.num_windows = 8; 931 1000 wi.window_shape = 0; … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 934 1003 lastgrp = i; 935 1004 wi.grouping[lastgrp]++; 936 1005 } 1006 1007 for (i = 0; i < 8; i += wi.grouping[i]) { 1008 int w, clipping = 0; 1009 for (w = 0; w < wi.grouping[i] && !clipping; w++) 1010 clipping = clippings[i+w]; 1011 wi.clipping[i] = clipping; 1012 if (clipping) anyclipped = 1; 1013 } 937 1014 } 938 1015 939 1016 /* Determine grouping, based on the location of the first attack, and save for … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 948 1025 break; 949 1026 } 950 1027 } 1028 951 1029 pch->next_grouping = window_grouping[grouping]; 952 1030 953 1031 pch->prev_attack = attacks[8]; -
libavcodec/psymodel.c
diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c index bfc85b3..cc25fca 100644
a b 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(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
