Ticket #2686: aac-improvements-wip-v9b.patch
| File aac-improvements-wip-v9b.patch, 98.6 KB (added by , 12 years ago) |
|---|
-
libavcodec/aac.h
diff --git a/libavcodec/aac.h b/libavcodec/aac.h index a151737..32f5ad3 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 5bf6a9c..9768f18 100644
a b static const uint8_t * const 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 62 63 /** 64 * approximates exp10f(-3.0f*(0.5f + 0.5f * cosf(FFMIN(b,15.5f) / 15.5f))) 65 */ 66 static av_always_inline float bval2bmax(float b) 67 { 68 return 0.001f + 0.0035f * (b*b*b) / (15.5f*15.5f*15.5f); 69 } 60 70 61 71 /** 62 72 * Quantize one coefficient. 63 73 * @return absolute value of the quantized coefficient 64 74 * @see 3GPP TS26.403 5.6.2 "Scalefactor determination" 65 75 */ 66 static av_always_inline int quant(float coef, const float Q )76 static av_always_inline int quant(float coef, const float Q, const float rounding) 67 77 { 68 78 float a = coef * Q; 69 return sqrtf(a * sqrtf(a)) + 0.4054;79 return sqrtf(a * sqrtf(a)) + rounding; 70 80 } 71 81 72 82 static void quantize_bands(int *out, const float *in, const float *scaled, 73 int size, float Q34, int is_signed, int maxval )83 int size, float Q34, int is_signed, int maxval, const float rounding) 74 84 { 75 85 int i; 76 86 double qc; 77 87 for (i = 0; i < size; i++) { 78 88 qc = scaled[i] * Q34; 79 out[i] = (int)FFMIN(qc + 0.4054, (double)maxval);89 out[i] = (int)FFMIN(qc + rounding, (double)maxval); 80 90 if (is_signed && in[i] < 0.0f) { 81 91 out[i] = -out[i]; 82 92 } … … static av_always_inline float quantize_and_encode_band_cost_template( 108 118 const float *scaled, int size, int scale_idx, 109 119 int cb, const float lambda, const float uplim, 110 120 int *bits, int BT_ZERO, int BT_UNSIGNED, 111 int BT_PAIR, int BT_ESC )121 int BT_PAIR, int BT_ESC, const float ROUNDING) 112 122 { 113 123 const int q_idx = POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512; 114 124 const float Q = ff_aac_pow2sf_tab [q_idx]; … … static av_always_inline float quantize_and_encode_band_cost_template( 134 144 abs_pow34_v(s->scoefs, in, size); 135 145 scaled = s->scoefs; 136 146 } 137 quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval );147 quantize_bands(s->qcoefs, in, scaled, size, Q34, !BT_UNSIGNED, maxval, ROUNDING); 138 148 if (BT_UNSIGNED) { 139 149 off = 0; 140 150 } else { … … static av_always_inline float quantize_and_encode_band_cost_template( 161 171 di = t - CLIPPED_ESCAPE; 162 172 curbits += 21; 163 173 } else { 164 int c = av_clip(quant(t, Q ), 0, 8191);174 int c = av_clip(quant(t, Q, ROUNDING), 0, 8191); 165 175 di = t - c*cbrtf(c)*IQ; 166 176 curbits += av_log2(c)*2 - 4 + 1; 167 177 } … … static av_always_inline float quantize_and_encode_band_cost_template( 191 201 if (BT_ESC) { 192 202 for (j = 0; j < 2; j++) { 193 203 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);204 int coef = av_clip(quant(fabsf(in[i+j]), Q, ROUNDING), 0, 8191); 195 205 int len = av_log2(coef); 196 206 197 207 put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2); … … static av_always_inline float quantize_and_encode_band_cost_template( 207 217 return cost; 208 218 } 209 219 210 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC ) \220 #define QUANTIZE_AND_ENCODE_BAND_COST_FUNC(NAME, BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING) \ 211 221 static float quantize_and_encode_band_cost_ ## NAME( \ 212 222 struct AACEncContext *s, \ 213 223 PutBitContext *pb, const float *in, \ … … static float quantize_and_encode_band_cost_ ## NAME( 217 227 return quantize_and_encode_band_cost_template( \ 218 228 s, pb, in, scaled, size, scale_idx, \ 219 229 BT_ESC ? ESC_BT : cb, lambda, uplim, bits, \ 220 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC );\230 BT_ZERO, BT_UNSIGNED, BT_PAIR, BT_ESC, ROUNDING); \ 221 231 } 222 232 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) 233 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO, 1, 0, 0, 0, ROUND_STANDARD) 234 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD, 0, 0, 0, 0, ROUND_STANDARD) 235 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD, 0, 1, 0, 0, ROUND_STANDARD) 236 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR, 0, 0, 1, 0, ROUND_STANDARD) 237 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR, 0, 1, 1, 0, ROUND_STANDARD) 238 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC, 0, 1, 1, 1, ROUND_STANDARD) 239 240 /*QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ZERO_RTZ, 1, 0, 0, 0, ROUND_TO_ZERO) 241 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SQUAD_RTZ, 0, 0, 0, 0, ROUND_TO_ZERO) 242 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UQUAD_RTZ, 0, 1, 0, 0, ROUND_TO_ZERO) 243 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(SPAIR_RTZ, 0, 0, 1, 0, ROUND_TO_ZERO) 244 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(UPAIR_RTZ, 0, 1, 1, 0, ROUND_TO_ZERO)*/ 245 QUANTIZE_AND_ENCODE_BAND_COST_FUNC(ESC_RTZ, 0, 1, 1, 1, ROUND_TO_ZERO) 229 246 230 247 static float (*const quantize_and_encode_band_cost_arr[])( 231 248 struct AACEncContext *s, … … static float (*const quantize_and_encode_band_cost_arr[])( 247 264 quantize_and_encode_band_cost_ESC, 248 265 }; 249 266 267 static float (*const quantize_and_encode_band_cost_rtz_arr[])( 268 struct AACEncContext *s, 269 PutBitContext *pb, const float *in, 270 const float *scaled, int size, int scale_idx, 271 int cb, const float lambda, const float uplim, 272 int *bits) = { 273 quantize_and_encode_band_cost_ZERO, 274 quantize_and_encode_band_cost_SQUAD, 275 quantize_and_encode_band_cost_SQUAD, 276 quantize_and_encode_band_cost_UQUAD, 277 quantize_and_encode_band_cost_UQUAD, 278 quantize_and_encode_band_cost_SPAIR, 279 quantize_and_encode_band_cost_SPAIR, 280 quantize_and_encode_band_cost_UPAIR, 281 quantize_and_encode_band_cost_UPAIR, 282 quantize_and_encode_band_cost_UPAIR, 283 quantize_and_encode_band_cost_UPAIR, 284 quantize_and_encode_band_cost_ESC_RTZ, 285 }; 286 250 287 #define quantize_and_encode_band_cost( \ 251 288 s, pb, in, scaled, size, scale_idx, cb, \ 252 lambda, uplim, bits )\253 quantize_and_encode_band_cost_arr[cb](\289 lambda, uplim, bits, rtz) \ 290 ((rtz) ? quantize_and_encode_band_cost_rtz_arr : quantize_and_encode_band_cost_arr)[cb]( \ 254 291 s, pb, in, scaled, size, scale_idx, cb, \ 255 292 lambda, uplim, bits) 256 293 257 294 static float quantize_band_cost(struct AACEncContext *s, const float *in, 258 295 const float *scaled, int size, int scale_idx, 259 296 int cb, const float lambda, const float uplim, 260 int *bits )297 int *bits, int rtz) 261 298 { 262 299 return quantize_and_encode_band_cost(s, NULL, in, scaled, size, scale_idx, 263 cb, lambda, uplim, bits );300 cb, lambda, uplim, bits, rtz); 264 301 } 265 302 266 303 static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb, 267 304 const float *in, int size, int scale_idx, 268 int cb, const float lambda )305 int cb, const float lambda, int rtz) 269 306 { 270 307 quantize_and_encode_band_cost(s, pb, in, NULL, size, scale_idx, cb, lambda, 271 INFINITY, NULL );308 INFINITY, NULL, rtz); 272 309 } 273 310 274 311 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 319 return maxval; 283 320 } 284 321 322 static av_const float sqrf(float f) { 323 return f*f; 324 } 325 326 static float find_form_factor(int group_len, int swb_size, float thresh, const float *scaled, float cleanup_factor) { 327 const float iswb_size = 1.0f / swb_size; 328 const float iswb_sizem1 = 1.0f / (swb_size - 1); 329 const float ethresh = thresh; 330 float form = 0.0f, weight = 0.0f; 331 int w2, i; 332 for (w2 = 0; w2 < group_len; w2++) { 333 float e = 0.0f, e2 = 0.0f, var = 0.0f, maxval = 0.0f; 334 float nzl = 0; 335 for (i = 0; i < swb_size; i++) { 336 float s = fabsf(scaled[w2*128+i]); 337 maxval = FFMAX(maxval, s); 338 e += s; 339 e2 += s *= s; 340 /* We really don't want a hard non-zero-line count, since 341 * even below-threshold lines do add up towards band spectral power. 342 * So, fall steeply towards zero, but smoothly 343 */ 344 if (s >= ethresh) 345 nzl += 1.0f; 346 else if (cleanup_factor > 1.0f) 347 nzl += powf(sqrf(s / ethresh), sqrf(FFMIN(4.0f,cleanup_factor))); 348 else 349 nzl += sqrf(s / ethresh); 350 } 351 if (e2 > thresh) { 352 float frm; 353 e *= iswb_size; 354 355 // compute variance 356 for (i = 0; i < swb_size; i++) { 357 float d = fabsf(scaled[w2*128+i]) - e; 358 var += d*d; 359 } 360 var = sqrtf(var * iswb_sizem1); 361 362 e2 *= iswb_size; 363 frm = e / FFMIN(e+4*var,maxval); 364 form += e2 * sqrtf(frm) / FFMAX(0.5f,nzl); 365 weight += e2; 366 } 367 } 368 if (weight > 0) 369 return form / weight; 370 else 371 return 1.0f; 372 } 373 374 static float find_max_absval(int group_len, int swb_size, const float *scaled) { 375 float maxval = 0.0f; 376 int w2, i; 377 for (w2 = 0; w2 < group_len; w2++) { 378 for (i = 0; i < swb_size; i++) { 379 maxval = FFMAX(maxval, fabs(scaled[w2*128+i])); 380 } 381 } 382 return maxval; 383 } 384 385 static unsigned char aac_maxval_cb[] = { 386 0, 1, 3, 5, 5, 7, 7, 7, 9, 9, 9, 9, 9, 11 387 }; 388 285 389 static int find_min_book(float maxval, int sf) { 286 390 float Q = ff_aac_pow2sf_tab[POW_SF2_ZERO - sf + SCALE_ONE_POS - SCALE_DIV_512]; 287 391 float Q34 = sqrtf(Q * sqrtf(Q)); 288 392 int qmaxval, cb; 289 393 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; 394 if (qmaxval >= (sizeof(aac_maxval_cb) / sizeof(aac_maxval_cb[0]))) 395 cb = 11; 396 else 397 cb = aac_maxval_cb[qmaxval]; 297 398 return cb; 298 399 } 299 400 … … static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce 341 442 } else { 342 443 float minrd = next_minrd; 343 444 int mincb = next_mincb; 445 float maxval = find_max_val(group_len, size, s->scoefs + start + w*128); 446 int startcb = find_min_book(maxval, sce->sf_idx[win*16+swb]); 344 447 next_minrd = INFINITY; 345 448 next_mincb = 0; 346 for (cb = 0; cb < 12; cb++) { 449 for (cb = 0; cb < startcb; cb++) { 450 path[swb+1][cb].cost = INFINITY; 451 path[swb+1][cb].prev_idx = -1; 452 path[swb+1][cb].run = 0; 453 } 454 for (cb = startcb; cb < 12; cb++) { 347 455 float cost_stay_here, cost_get_here; 348 456 float rd = 0.0f; 349 457 for (w = 0; w < group_len; w++) { 350 458 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb]; 351 459 rd += quantize_band_cost(s, sce->coeffs + start + w*128, 352 460 s->scoefs + start + w*128, size, 353 sce->sf_idx[ (win+w)*16+swb], cb,354 lambda / band->threshold, INFINITY, NULL );461 sce->sf_idx[win*16+swb], cb, 462 lambda / band->threshold, INFINITY, NULL, 0); 355 463 } 356 464 cost_stay_here = path[swb][cb].cost + rd; 357 465 cost_get_here = minrd + rd + run_bits + 4; … … static void codebook_trellis_rate(AACEncContext *s, SingleChannelElement *sce, 472 580 for (w = 0; w < group_len; w++) { 473 581 bits += quantize_band_cost(s, sce->coeffs + start + w*128, 474 582 s->scoefs + start + w*128, size, 475 sce->sf_idx[ (win+w)*16+swb], cb,476 0, INFINITY, NULL );583 sce->sf_idx[win*16+swb], cb, 584 0, INFINITY, NULL, 0); 477 585 } 478 586 cost_stay_here = path[swb][cb].cost + bits; 479 587 cost_get_here = minbits + bits + run_bits + 4; … … static av_always_inline uint8_t coef2maxsf(float coef) { 545 653 546 654 typedef struct TrellisPath { 547 655 float cost; 656 int bits; 548 657 int prev; 658 int cb; 549 659 } TrellisPath; 550 660 551 661 #define TRELLIS_STAGES 121 552 #define TRELLIS_STATES (SCALE_MAX_DIFF+1)662 #define TRELLIS_STATES 255 553 663 554 664 static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 555 665 SingleChannelElement *sce, 556 666 const float lambda) 557 667 { 558 int q, w, w2, g, start = 0 ;668 int q, w, w2, g, start = 0, wstart = 0; 559 669 int i, j; 560 670 int idx; 561 671 TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES]; 562 672 int bandaddr[TRELLIS_STAGES]; 563 673 int minq; 564 674 float mincost; 675 const float sqlambda = (float)sqrtf(lambda / 100.f) * 100.f; 676 const float rdlambda = sqrtf(av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f)); 677 const float rdmin = 0.03125f; 678 const float rdmax = 1.0f; 565 679 float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f; 566 680 int q0, q1, qcnt = 0; 681 int toomanybits; 682 int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate 683 / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels) 684 * (lambda / 120.f); 685 int refbits = destbits; 686 int cutoff = 1024; 687 int psy_bits_max; 688 int g_to_toomanybits[TRELLIS_STAGES]; 689 690 if (s->psy.bitres.alloc >= 0) { 691 // Psy granted us extra bits to use, from the reservoire 692 // adjust for lambda except what psy already did 693 destbits = s->psy.bitres.alloc 694 * (lambda / (avctx->global_quality ? avctx->global_quality : 120)); 695 } 696 697 // Compute band-to-bit-allocation table to properly cost by cumulative bit expenditure 698 699 if (avctx->flags & CODEC_FLAG_QSCALE) { 700 // Constant Q-scale doesn't compensate MS coding on its own 701 // No need to be overly precise, this only controls cutoff frequency 702 if (s->options.stereo_mode && s->cur_type == TYPE_CPE) 703 destbits *= 2; 704 705 toomanybits = 5800; 706 } else { 707 toomanybits = FFMIN(destbits + destbits/8, 5800); 708 } 709 710 // and zero out above cutoff frequency 711 { 712 int wlen = 1024 / sce->ics.num_windows; 713 int bandwidth; 714 715 /* Scale, psy gives us constant quality, this LP only scales 716 * bitrate by lambda, so we save bits on subjectively unimportant HF 717 * rather than increase quantization noise. Adjust nominal bitrate 718 * to effective bitrate according to encoding parameters, _AAC_CUTOFF 719 * is calibrated for effective bitrate. 720 */ 721 float rate_bandwidth_multiplier = 1.3f; 722 int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE) 723 ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024) 724 : (avctx->bit_rate / avctx->channels); 725 726 if (avctx->cutoff > 0) 727 bandwidth = avctx->cutoff; 728 else 729 bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate)); 567 730 731 cutoff = bandwidth * 2 * wlen / avctx->sample_rate; 732 } 733 734 for (w = 0, idx = 1; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 735 for (g = wstart = 0; g < sce->ics.num_swb; g++, wstart += sce->ics.swb_sizes[g]) { 736 int nz = 0, bits = 0, curbits; 737 738 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 739 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 740 bits += band->bits; 741 if (!(wstart >= cutoff || band->energy <= band->threshold || band->threshold == 0.0f)) 742 nz = 1; 743 } 744 745 curbits = g_to_toomanybits[idx-1]; 746 if (nz) { 747 curbits += 3+bits; 748 } else { 749 curbits += 1; 750 } 751 if (g == 0) 752 curbits += destbits / (8 * sce->ics.num_windows); 753 g_to_toomanybits[idx] = curbits; 754 idx++; 755 } 756 } 757 j = idx; 758 psy_bits_max = g_to_toomanybits[idx-1]; 759 if (psy_bits_max) { 760 for (idx = 0; idx < j; idx++) { 761 g_to_toomanybits[idx] = g_to_toomanybits[idx] * toomanybits / psy_bits_max; 762 } 763 } 764 765 // Initialize trellis state 766 568 767 for (i = 0; i < 1024; i++) { 569 768 float t = fabsf(sce->coeffs[i]); 570 769 if (t > 0.0f) { … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 585 784 q0 = coef2minsf(q0f); 586 785 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero 587 786 q1 = coef2maxsf(q1f); 588 if (q1 - q0 > 60) {787 if (q1 - q0 > TRELLIS_STATES) { 589 788 int q0low = q0; 590 789 int q1high = q1; 591 790 //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped 592 791 int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512); 593 q1 = qnrg + 30;594 q0 = qnrg - 30;792 q1 = qnrg + TRELLIS_STATES/2; 793 q0 = qnrg - TRELLIS_STATES/2; 595 794 if (q0 < q0low) { 596 795 q1 += q0low - q0; 597 796 q0 = q0low; … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 603 802 604 803 for (i = 0; i < TRELLIS_STATES; i++) { 605 804 paths[0][i].cost = 0.0f; 805 paths[0][i].bits = 0; 606 806 paths[0][i].prev = -1; 807 paths[0][i].cb = 0; 607 808 } 608 809 for (j = 1; j < TRELLIS_STAGES; j++) { 609 810 for (i = 0; i < TRELLIS_STATES; i++) { 610 811 paths[j][i].cost = INFINITY; 812 paths[j][i].bits = 0; 611 813 paths[j][i].prev = -2; 814 paths[j][i].cb = 0; 612 815 } 613 816 } 614 817 idx = 1; 615 818 abs_pow34_v(s->scoefs, sce->coeffs, 1024); 616 819 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 820 const float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f; 617 821 start = w*128; 618 for (g = 0; g < sce->ics.num_swb; g++) {822 for (g = wstart = 0; g < sce->ics.num_swb; g++, wstart += sce->ics.swb_sizes[g]) { 619 823 const float *coefs = sce->coeffs + start; 824 const float *scoefs = s->scoefs + start; 620 825 float qmin, qmax; 621 826 int nz = 0; 622 827 623 828 bandaddr[idx] = w * 16 + g; 624 qmin = INT_MAX;829 qmin = FLT_MAX; 625 830 qmax = 0.0f; 626 831 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 627 832 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 628 if (band->energy <= band->threshold || band->threshold == 0.0f) { 629 sce->zeroes[(w+w2)*16+g] = 1; 833 if (wstart >= cutoff || band->energy <= band->threshold || band->threshold == 0.0f) { 630 834 continue; 631 835 } 632 sce->zeroes[(w+w2)*16+g] = 0;633 836 nz = 1; 634 837 for (i = 0; i < sce->ics.swb_sizes[g]; i++) { 635 838 float t = fabsf(coefs[w2*128+i]); … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 639 842 } 640 843 } 641 844 if (nz) { 642 int minscale, maxscale ;845 int minscale, maxscale, qstep; 643 846 float minrd = INFINITY; 644 847 float maxval; 848 float bmax = bval2bmax(g * 17.0f / sce->ics.num_swb) / 0.0045f; 849 int btoomanybits = FFMIN(5800, toomanybits * (0.25f + 0.75f * bmax)); 645 850 //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped 646 851 minscale = coef2minsf(qmin); 647 852 //maximum scalefactor index is when maximum coefficient after quantizing is still not zero … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 649 854 minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1); 650 855 maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES); 651 856 maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start); 652 for (q = minscale; q < maxscale; q++) { 653 float dist = 0; 654 int cb = find_min_book(maxval, sce->sf_idx[w*16+g]); 655 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 656 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 657 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); 659 } 660 minrd = FFMIN(minrd, dist); 661 662 for (i = 0; i < q1 - q0; i++) { 663 float cost; 664 cost = paths[idx - 1][i].cost + dist 665 + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO]; 666 if (cost < paths[idx][q].cost) { 667 paths[idx][q].cost = cost; 668 paths[idx][q].prev = i; 857 qstep = av_clip((maxscale - minscale + SCALE_MAX_DIFF/2) / SCALE_MAX_DIFF, 1, 3); 858 859 for (q = minscale; q < maxscale; q += qstep) { 860 // we don't want holes - ie: codebook 0 861 int cb = find_min_book(maxval, q + q0); 862 if (cb > 0) { 863 // Check viability (ie: that there is a path starting at this q that respects SCALE_MAX_DIFF) 864 int viable = 0, qdiff = FFMIN(q + SCALE_MAX_DIFF, q1 - q0); 865 for (i = FFMAX(0, q - SCALE_MAX_DIFF); !viable && i < qdiff; i++) { 866 viable = paths[idx - 1][i].prev != -2; 867 } 868 if (viable) { 869 float dist = 0; 870 int bits = 0; 871 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 872 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 873 int b; 874 float formfactor = find_form_factor( 875 1, sce->ics.swb_sizes[g], 876 band->threshold / sce->ics.swb_sizes[w], 877 coefs + w2*128, 878 start / (cutoff * 1.25f)); 879 formfactor *= de_psy_factor; 880 formfactor = av_clipf(sqrtf(formfactor), 0.015625f, 1.0f); 881 formfactor = av_clipf(rdlambda * formfactor, rdmin, rdmax); 882 dist += quantize_band_cost(s, coefs + w2*128, scoefs + w2*128, sce->ics.swb_sizes[g], 883 q + q0, cb, sqlambda / (band->threshold * formfactor), INFINITY, &b, 0); 884 bits += b; 885 } 886 minrd = FFMIN(minrd, dist); 887 888 for (i = FFMAX(0, q - SCALE_MAX_DIFF); i < qdiff; i++) { 889 if (paths[idx - 1][i].prev != -2) { 890 int tbits = paths[idx - 1][i].bits + bits 891 + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO]; 892 float cost = paths[idx - 1][i].cost + dist 893 + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO] 894 + sqrf(FFMAX(0, tbits - g_to_toomanybits[idx])); 895 if (cost < paths[idx][q].cost) { 896 paths[idx][q].cost = cost; 897 paths[idx][q].bits = tbits; 898 paths[idx][q].prev = i; 899 paths[idx][q].cb = cb; 900 } 901 } 902 } 669 903 } 670 904 } 671 905 } 672 906 } else { 673 907 for (q = 0; q < q1 - q0; q++) { 674 paths[idx][q].cost = paths[idx - 1][q].cost + 1; 675 paths[idx][q].prev = q; 908 if (paths[idx-1][q].prev != -2) { 909 paths[idx][q].cost = paths[idx - 1][q].cost + 1; 910 paths[idx][q].bits = paths[idx - 1][q].bits + 1; 911 paths[idx][q].prev = q; 912 paths[idx][q].cb = 0; 913 } 676 914 } 677 915 } 678 916 sce->zeroes[w*16+g] = !nz; … … static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s, 691 929 } 692 930 while (idx) { 693 931 sce->sf_idx[bandaddr[idx]] = minq + q0; 932 sce->band_type[bandaddr[idx]] = paths[idx][minq].cb; 694 933 minq = paths[idx][minq].prev; 695 934 idx--; 696 935 } 697 936 //set the same quantizers inside window groups 698 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 699 for (g = 0; g < sce->ics.num_swb; g++) 700 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) 937 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 938 for (g = 0; g < sce->ics.num_swb; g++) { 939 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) { 701 940 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g]; 941 sce->zeroes[(w+w2)*16+g] = sce->zeroes[w*16+g]; 942 sce->band_type[(w+w2)*16+g] = sce->band_type[w*16+g]; 943 } 944 } 945 } 702 946 } 703 947 948 #define sclip(x) av_clip(x,60,218) 949 704 950 /** 705 951 * two-loop quantizers search taken from ISO 13818-7 Appendix C 706 952 */ 707 953 static void search_for_quantizers_twoloop(AVCodecContext *avctx, 708 954 AACEncContext *s, 709 955 SingleChannelElement *sce, 710 constfloat lambda)956 float lambda) 711 957 { 712 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]; 958 int start = 0, i, w, w2, g, recomprd; 959 int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate 960 / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels) 961 * (lambda / 120.f); 962 int refbits = destbits; 963 int toomanybits, toofewbits; 964 char nzs[128]; 965 int maxsf[128]; 966 float dists[128] = { 0 }, uplims[128], euplims[128]; 715 967 float maxvals[128]; 716 int fflag, minscaler; 968 969 /* rdlambda controls the maximum tolerated distortion. Twoloop 970 * will keep iterating until it fails to lower it or it reaches 971 * ulimit * rdlambda. Keeping it low increases quality on difficult 972 * signals, but lower it too much, and bits will be taken from weak 973 * signals, creating "holes". A balance is necesary. 974 * rdmax and rdmin specify the relative deviation from rdlambda 975 * allowed for tonality compensation 976 */ 977 float rdlambda = av_clipf(2.0f * 120.f / lambda, 0.0625f, 16.0f); 978 float rdmin = 0.03125f; 979 float rdmax = 1.0f; 980 981 /* sfoffs controls an offset of optmium allocation that will be 982 * applied based on lambda. Keep it real and modest, the loop 983 * will take care of the rest, this just accelerates convergence 984 */ 985 float sfoffs = av_clipf(log2f(120.0f / lambda) * 4.0f, -5, 10); 986 987 int fflag, minscaler, maxscaler, nminscaler, minrdsf; 717 988 int its = 0; 989 int maxits = 30; 718 990 int allz = 0; 719 float minthr = INFINITY; 991 int tbits; 992 int cutoff = 1024; 993 int cleanoff = 1024; 994 995 /* zeroscale controls a multiplier of the threshold, if band energy 996 * is below this, a zero is forced. Keep it lower than 1, unless 997 * low lambda is used, because energy < threshold doesn't mean there's 998 * no audible signal outright, it's just energy. Also make it rise 999 * slower than rdlambda, as rdscale has due compensation with 1000 * noisy band depriorization below, whereas zeroing logic is rather dumb 1001 */ 1002 float zeroscale; 1003 if (lambda > 120.f) 1004 zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f); 1005 else 1006 zeroscale = 1.f; 1007 1008 if (s->psy.bitres.alloc >= 0) { 1009 // Psy granted us extra bits to use, from the reservoire 1010 // adjust for lambda except what psy already did 1011 destbits = s->psy.bitres.alloc 1012 * (lambda / (avctx->global_quality ? avctx->global_quality : 120)); 1013 } 1014 1015 if (avctx->flags & CODEC_FLAG_QSCALE) { 1016 // Constant Q-scale doesn't compensate MS coding on its own 1017 // No need to be overly precise, this only controls RD 1018 // adjustment CB limits when going overboard 1019 if (s->options.stereo_mode && s->cur_type == TYPE_CPE) 1020 destbits *= 2; 1021 1022 // When using a constant Q-scale, don't adjust bits, just use RD 1023 // Don't let it go overboard, though... 8x psy target is enough 1024 toomanybits = 5800; //av_clip(FFMAX(refbits*3, destbits * 8), 768, 5800); 1025 toofewbits = destbits / 16; 1026 1027 // Don't offset scalers, just RD 1028 sfoffs = sce->ics.num_windows - 1; 1029 rdlambda = sqrtf(rdlambda); 1030 1031 // search further 1032 maxits *= 2; 1033 } else { 1034 // When using ABR, be strict 1035 toomanybits = destbits + destbits/16; 1036 toofewbits = destbits - destbits/4; 1037 1038 sfoffs = 0; 1039 rdlambda = sqrtf(rdlambda); 1040 } 1041 1042 // and zero out above cutoff frequency 1043 { 1044 int wlen = 1024 / sce->ics.num_windows; 1045 int bandwidth; 1046 int cleanwidth; 1047 1048 /* Scale, psy gives us constant quality, this LP only scales 1049 * bitrate by lambda, so we save bits on subjectively unimportant HF 1050 * rather than increase quantization noise. Adjust nominal bitrate 1051 * to effective bitrate according to encoding parameters, _AAC_CUTOFF 1052 * is calibrated for effective bitrate. 1053 */ 1054 float rate_bandwidth_multiplier = 1.3f; 1055 int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE) 1056 ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024) 1057 : (avctx->bit_rate / avctx->channels); 1058 1059 if (avctx->cutoff > 0) 1060 bandwidth = avctx->cutoff; 1061 else 1062 bandwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate, 1, avctx->sample_rate)); 1063 cleanwidth = FFMAX(3000, _AAC_CUTOFF(frame_bit_rate * 0.8f, 1, avctx->sample_rate)); 1064 1065 cutoff = bandwidth * 2 * wlen / avctx->sample_rate; 1066 cleanoff = cleanwidth * 2 * wlen / avctx->sample_rate; 1067 } 720 1068 721 1069 // for values above this the decoder might end up in an endless loop 722 1070 // due to always having more bits than what can be encoded. 723 1071 destbits = FFMIN(destbits, 5800); 1072 toomanybits = FFMIN(toomanybits, 5800); 1073 toofewbits = FFMIN(toofewbits, 5800); 724 1074 //XXX: some heuristic to determine initial quantizers will reduce search time 725 1075 //determine zero bands and upper limits 726 1076 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 727 for (g = 0; g < sce->ics.num_swb; g++) {1077 for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) { 728 1078 int nz = 0; 729 1079 float uplim = 0.0f; 1080 float energy = 0.0f; 1081 730 1082 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 731 1083 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) { 1084 if (start >= cutoff || band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0) { 734 1085 sce->zeroes[(w+w2)*16+g] = 1; 735 1086 continue; 736 1087 } 737 1088 nz = 1; 738 1089 } 739 uplims[w*16+g] = uplim *512; 1090 if (!nz) { 1091 uplim = 0.0f; 1092 } else { 1093 nz = 0; 1094 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1095 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 1096 if (band->energy <= (band->threshold * zeroscale) || band->threshold == 0.0f) 1097 continue; 1098 uplim += band->threshold; 1099 energy += band->energy; 1100 nz++; 1101 } 1102 } 1103 uplims[w*16+g] = uplim; 1104 nzs[w*16+g] = nz; 740 1105 sce->zeroes[w*16+g] = !nz; 741 if (nz)742 minthr = FFMIN(minthr, uplim);743 1106 allz |= nz; 744 1107 } 745 1108 } 1109 1110 /* Compute initial scalers */ 1111 minscaler = 65535; 746 1112 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 747 1113 for (g = 0; g < sce->ics.num_swb; g++) { 748 1114 if (sce->zeroes[w*16+g]) { 749 1115 sce->sf_idx[w*16+g] = SCALE_ONE_POS; 750 1116 continue; 751 1117 } 752 sce->sf_idx[w*16+g] = SCALE_ONE_POS + FFMIN(log2f(uplims[w*16+g]/minthr)*4,59); 1118 /* log2f-to-distortion ratio is, technically, 2 (1.5db = 4, but it's power vs level so it's 2). 1119 * But, as offsets are applied, low-frequency signals are too sensitive to the induced distortion, 1120 * so we make scaling more conservative by choosing a lower log2f-to-distortion ratio, and thus 1121 * more robust. 1122 */ 1123 sce->sf_idx[w*16+g] = av_clip( 1124 SCALE_ONE_POS 1125 + 1.75*log2f(FFMAX(0.00125f,uplims[w*16+g]) / sce->ics.swb_sizes[g]) 1126 + sfoffs, 1127 60, SCALE_MAX_POS); 1128 //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]); 1129 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]); 753 1130 } 1131 //fprintf(stderr, "|\n"); 754 1132 } 755 1133 //fprintf(stderr, "\n"); 1134 1135 /* Clip */ 1136 minscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512); 1137 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 1138 for (g = 0; g < sce->ics.num_swb; g++) 1139 if (!sce->zeroes[w*16+g]) 1140 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF - 1); 1141 756 1142 if (!allz) 757 1143 return; 758 1144 abs_pow34_v(s->scoefs, sce->coeffs, 1024); … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 766 1152 } 767 1153 } 768 1154 1155 /* Scale uplims to match rate distortion to quality 1156 * and apply noisy band depriorization and tonal band priorization. 1157 * Maxval-energy ratio gives us an idea of how noisy/tonal the band is. 1158 * If maxval^2 ~ energy, then that band is mostly noise, and we can relax 1159 * rate distortion requirements. 1160 */ 1161 memcpy(euplims, uplims, sizeof(euplims)); 1162 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1163 /* psy already priorizes transients to some extent */ 1164 float de_psy_factor = (sce->ics.num_windows > 1) ? 8.0f / sce->ics.group_len[w] : 1.0f; 1165 start = w*128; 1166 for (g = 0; g < sce->ics.num_swb; g++) { 1167 if (nzs[g] > 0) { 1168 float energy2uplim = find_form_factor( 1169 sce->ics.group_len[w], sce->ics.swb_sizes[g], 1170 uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]), 1171 sce->coeffs + start, 1172 start / (float)cleanoff); 1173 energy2uplim *= de_psy_factor; 1174 if (!(avctx->flags & CODEC_FLAG_QSCALE)) { 1175 // In ABR, we need to priorize less and let rate control do its thing 1176 energy2uplim = sqrtf(energy2uplim); 1177 } 1178 energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim)); 1179 //fprintf(stderr, "%.3f ", energy2uplim); 1180 uplims[w*16+g] *= av_clipf(rdlambda * energy2uplim, rdmin, rdmax) 1181 * sce->ics.group_len[w]; 1182 1183 // For energy uplims, don't cleanoff 1184 energy2uplim = find_form_factor( 1185 sce->ics.group_len[w], sce->ics.swb_sizes[g], 1186 uplims[w*16+g] / (nzs[g] * sce->ics.swb_sizes[w]), 1187 sce->coeffs + start, 0); 1188 energy2uplim *= de_psy_factor; 1189 if (!(avctx->flags & CODEC_FLAG_QSCALE)) { 1190 // In ABR, we need to priorize less and let rate control do its thing 1191 energy2uplim = sqrtf(energy2uplim); 1192 } 1193 energy2uplim = FFMAX(0.015625f, FFMIN(1.0f, energy2uplim)); 1194 euplims[w*16+g] *= av_clipf(rdlambda * energy2uplim * sce->ics.group_len[w], 1195 0.5f, 1.0f); 1196 } 1197 start += sce->ics.swb_sizes[g]; 1198 } 1199 //fprintf(stderr, "|"); 1200 } 1201 //fprintf(stderr, "\n"); 1202 1203 for (i = 0; i < sizeof(maxsf) / sizeof(maxsf[0]); ++i) 1204 maxsf[i] = SCALE_MAX_POS; 1205 769 1206 //perform two-loop search 770 1207 //outer loop - improve quality 771 1208 do { 772 int tbits, qstep; 773 minscaler = sce->sf_idx[0]; 1209 int qstep; 774 1210 //inner loop - quantize spectrum to fit into given number of bits 775 1211 qstep = its ? 1 : 32; 776 1212 do { 777 1213 int prev = -1; 1214 int changed = 0; 778 1215 tbits = 0; 1216 recomprd = 0; 779 1217 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 780 1218 start = w*128; 781 1219 for (g = 0; g < sce->ics.num_swb; g++) { … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 789 1227 start += sce->ics.swb_sizes[g]; 790 1228 continue; 791 1229 } 792 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);793 1230 cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 794 1231 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 795 1232 int b; … … static void search_for_quantizers_twoloop(AVCodecContext *avctx, 800 1237 cb, 801 1238 1.0f, 802 1239 INFINITY, 803 &b); 1240 &b, 1241 0); 804 1242 bits += b; 805 1243 } 806 1244 dists[w*16+g] = dist - bits; 807 1245 if (prev != -1) { 808 bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO]; 1246 int sfdiff = sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO; 1247 av_assert1(sfdiff >= 0 && sfdiff <= 2*SCALE_MAX_DIFF); 1248 bits += ff_aac_scalefactor_bits[sfdiff]; 809 1249 } 810 1250 tbits += bits; 811 1251 start += sce->ics.swb_sizes[g]; 812 1252 prev = sce->sf_idx[w*16+g]; 813 1253 } 814 1254 } 815 if (tbits > destbits) { 816 for (i = 0; i < 128; i++) 817 if (sce->sf_idx[i] < 218 - qstep) 818 sce->sf_idx[i] += qstep; 819 } else { 820 for (i = 0; i < 128; i++) 821 if (sce->sf_idx[i] > 60 - qstep) 822 sce->sf_idx[i] -= qstep; 1255 if (tbits > toomanybits) { 1256 recomprd = 1; 1257 for (i = 0; i < 128; i++) { 1258 if (sce->sf_idx[i] < (SCALE_MAX_POS - SCALE_DIV_512)) { 1259 int maxsf_i = (tbits > 5800) ? SCALE_MAX_POS : maxsf[i]; 1260 int new_sf = FFMIN(maxsf_i, sce->sf_idx[i] + qstep); 1261 if (new_sf != sce->sf_idx[i]) { 1262 sce->sf_idx[i] = new_sf; 1263 changed = 1; 1264 } 1265 } 1266 } 1267 } else if (tbits < toofewbits) { 1268 recomprd = 1; 1269 for (i = 0; i < 128; i++) { 1270 if (sce->sf_idx[i] > SCALE_ONE_POS) { 1271 int new_sf = FFMAX(SCALE_ONE_POS, sce->sf_idx[i] - qstep); 1272 if (new_sf != sce->sf_idx[i]) { 1273 sce->sf_idx[i] = new_sf; 1274 changed = 1; 1275 } 1276 } 1277 } 823 1278 } 824 1279 qstep >>= 1; 825 if (!qstep && tbits > destbits*1.02 && sce->sf_idx[0] < 217)1280 if (!qstep && tbits > toomanybits && sce->sf_idx[0] < 217 && changed) 826 1281 qstep = 1; 827 1282 } while (qstep); 1283 if (recomprd) { 1284 // Must recompute distortion 1285 int prev = -1; 1286 tbits = 0; 1287 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1288 start = w*128; 1289 for (g = 0; g < sce->ics.num_swb; g++) { 1290 const float *coefs = sce->coeffs + start; 1291 const float *scaled = s->scoefs + start; 1292 int bits = 0; 1293 int cb; 1294 float dist = 0.0f; 1295 1296 if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218) { 1297 start += sce->ics.swb_sizes[g]; 1298 continue; 1299 } 1300 cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1301 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1302 int b; 1303 dist += quantize_band_cost(s, coefs + w2*128, 1304 scaled + w2*128, 1305 sce->ics.swb_sizes[g], 1306 sce->sf_idx[w*16+g], 1307 cb, 1308 1.0f, 1309 INFINITY, 1310 &b, 1311 0); 1312 bits += b; 1313 } 1314 dists[w*16+g] = dist - bits; 1315 if (prev != -1) { 1316 int sfdiff = sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO; 1317 av_assert1(sfdiff >= 0 && sfdiff <= 2*SCALE_MAX_DIFF); 1318 bits += ff_aac_scalefactor_bits[sfdiff]; 1319 } 1320 tbits += bits; 1321 start += sce->ics.swb_sizes[g]; 1322 prev = sce->sf_idx[w*16+g]; 1323 } 1324 } 1325 } 1326 1327 minscaler = SCALE_MAX_POS; 1328 maxscaler = 0; 1329 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1330 for (g = 0; g < sce->ics.num_swb; g++) { 1331 if (!sce->zeroes[w*16+g]) { 1332 minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]); 1333 maxscaler = FFMAX(maxscaler, sce->sf_idx[w*16+g]); 1334 } 1335 } 1336 } 828 1337 829 1338 fflag = 0; 830 minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF); 1339 minscaler = nminscaler = av_clip(minscaler, SCALE_ONE_POS - SCALE_DIV_512, SCALE_MAX_POS - SCALE_DIV_512); 1340 minrdsf = FFMAX3(60, minscaler - 1, maxscaler - SCALE_MAX_DIFF - 1); 831 1341 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1342 // Start with big steps, end up fine-tunning 1343 int depth = (its > maxits/2) ? ((its > maxits*2/3) ? 1 : 3) : 10; 1344 int edepth = depth+2; 1345 float uplmax = its / (maxits*0.25f) + 1.0f; 1346 uplmax *= (tbits > destbits) ? FFMIN(2.0f, tbits / (float)FFMAX(1,destbits)) : 1.0f; 1347 start = w * 128; 832 1348 for (g = 0; g < sce->ics.num_swb; g++) { 833 1349 int prevsc = sce->sf_idx[w*16+g]; 834 if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60) { 835 if (find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1)) 836 sce->sf_idx[w*16+g]--; 837 else //Try to make sure there is some energy in every band 838 sce->sf_idx[w*16+g]-=2; 1350 if (!sce->zeroes[w*16+g]) { 1351 const float *coefs = sce->coeffs + start; 1352 const float *scaled = s->scoefs + start; 1353 int cmb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1354 if ((!cmb || dists[w*16+g] > uplims[w*16+g]) && sce->sf_idx[w*16+g] > minrdsf) { 1355 //Try to make sure there is some energy in every nonzero band 1356 //NOTE: This algorithm must be forcibly imbalanced, pushing harder 1357 // on holes or more distorted bands at first, otherwise there's 1358 // no net gain (since the next iteration will offset all bands 1359 // on the opposite direction to compensate for extra bits) 1360 for (i = 0; i < edepth; ++i) { 1361 int cb, bits; 1362 float dist; 1363 int mb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]-1); 1364 cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1365 dist = 0.f; 1366 bits = 0; 1367 if (!cb) { 1368 maxsf[w*16+g] = FFMIN(sce->sf_idx[w*16+g], maxsf[w*16+g]); 1369 } else if (i >= depth && dists[w*16+g] < euplims[w*16+g]) { 1370 break; 1371 } 1372 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1373 int b; 1374 dist += quantize_band_cost(s, coefs + w2*128, 1375 scaled + w2*128, 1376 sce->ics.swb_sizes[g], 1377 sce->sf_idx[w*16+g]-1, 1378 cb, 1379 1.0f, 1380 INFINITY, 1381 &b, 1382 0); 1383 bits += b; 1384 } 1385 sce->sf_idx[w*16+g]--; 1386 dists[w*16+g] = dist - bits; 1387 if (mb && (sce->sf_idx[w*16+g] < minrdsf || dists[w*16+g] < FFMIN(uplmax*uplims[w*16+g], euplims[w*16+g]))) 1388 break; 1389 } 1390 } else if (tbits > toofewbits && dists[w*16+g] < uplims[w*16+g] && sce->sf_idx[w*16+g] < maxscaler) { 1391 // Um... over target 1392 for (i = 0; i < depth; ++i) { 1393 int cb, bits; 1394 float dist; 1395 cb = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]+1); 1396 if (cb > 0) { 1397 dist = 0.f; 1398 bits = 0; 1399 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1400 int b; 1401 dist += quantize_band_cost(s, coefs + w2*128, 1402 scaled + w2*128, 1403 sce->ics.swb_sizes[g], 1404 sce->sf_idx[w*16+g]+1, 1405 cb, 1406 1.0f, 1407 INFINITY, 1408 &b, 1409 0); 1410 bits += b; 1411 } 1412 dist -= bits; 1413 if (dist < uplims[w*16+g]) { 1414 sce->sf_idx[w*16+g]++; 1415 dists[w*16+g] = dist; 1416 } else { 1417 break; 1418 } 1419 } 1420 } 1421 } 839 1422 } 840 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], min scaler, minscaler + SCALE_MAX_DIFF);841 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);1423 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minrdsf, minscaler + SCALE_MAX_DIFF); 1424 sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], SCALE_MAX_POS - SCALE_DIV_512); 842 1425 if (sce->sf_idx[w*16+g] != prevsc) 843 1426 fflag = 1; 1427 nminscaler = FFMIN(nminscaler, sce->sf_idx[w*16+g]); 844 1428 sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1429 start += sce->ics.swb_sizes[g]; 1430 } 1431 } 1432 if (nminscaler < minscaler) { 1433 // Drecreased some scalers below minscaler. Must re-clamp. 1434 minscaler = nminscaler; 1435 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1436 for (g = 0; g < sce->ics.num_swb; g++) { 1437 sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF); 1438 sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]); 1439 } 845 1440 } 846 1441 } 847 1442 its++; 848 } while (fflag && its < 10); 1443 } while (fflag && its < maxits); 1444 1445 /* Fill implicit zeroes */ 1446 //fprintf(stderr, "its:%d %d/%d: ", its, tbits, destbits); 1447 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1448 /* No lowly codebooks beyond cutoff zone, to clean up noisy coefs */ 1449 int scutoff = cutoff + cutoff/5; 1450 for (g = start = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) { 1451 int minbt = (start < scutoff) ? 0 : 3; 1452 //fprintf(stderr, "%02x ", sce->sf_idx[w*16+g]); 1453 if (sce->band_type[w*16+g] <= minbt) { 1454 sce->zeroes[w*16+g] = 1; 1455 sce->band_type[w*16+g] = 0; 1456 } 1457 } 1458 //fprintf(stderr, "|"); 1459 } 1460 //fprintf(stderr, "\n"); 1461 //fprintf(stderr, "ba:%d br:%d (%d-%d) %.2f \t\r\n", s->psy.bitres.alloc, tbits, toofewbits, toomanybits); 849 1462 } 850 1463 851 1464 static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s, … … static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s, 965 1578 ESC_BT, 966 1579 lambda, 967 1580 INFINITY, 968 &b); 1581 &b, 1582 0); 969 1583 dist -= b; 970 1584 } 971 1585 dist *= 1.0f / 512.0f / lambda; 972 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512] );1586 quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD); 973 1587 if (quant_max >= 8191) { // too much, return to the previous quantizer 974 1588 sce->sf_idx[w*16+g] = prev_scf; 975 1589 break; … … static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s, 1019 1633 SingleChannelElement *sce, 1020 1634 const float lambda) 1021 1635 { 1022 int i, w, w2, g; 1023 int minq = 255; 1636 int w, w2, g; 1637 float lowlambda = av_clipf(120.f / lambda, 0.85f, 1.f); 1638 float rlambda = av_clipf(120.f / lambda, 0.75f, 10.f); 1639 const int minq = av_clip(2 * log2f(120.f / lambda) + 150, 100, 218 - SCALE_MAX_DIFF); 1640 const int maxq = minq + SCALE_MAX_DIFF - 1; 1024 1641 1025 1642 memset(sce->sf_idx, 0, sizeof(sce->sf_idx)); 1026 1643 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1027 1644 for (g = 0; g < sce->ics.num_swb; g++) { 1028 1645 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) { 1029 1646 FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; 1030 if (band->energy <= band->threshold) {1031 sce->sf_idx[(w+w2)*16+g] = 218;1647 if (band->energy <= 0.05 * lowlambda * band->threshold) { 1648 sce->sf_idx[(w+w2)*16+g] = maxq; 1032 1649 sce->zeroes[(w+w2)*16+g] = 1; 1033 1650 } else { 1034 sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);1651 sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + 1.414*log2f(band->threshold * rlambda), minq, maxq); 1035 1652 sce->zeroes[(w+w2)*16+g] = 0; 1036 1653 } 1037 minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);1038 1654 } 1039 1655 } 1040 1656 } 1041 for (i = 0; i < 128; i++) {1042 sce->sf_idx[i] = 140;1043 //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);1044 }1045 1657 //set the same quantizers inside window groups 1046 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) 1047 for (g = 0; g < sce->ics.num_swb; g++) 1048 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) 1049 sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g]; 1658 if (sce->ics.num_windows > 1) { 1659 for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { 1660 for (g = 0; g < sce->ics.num_swb; g++) { 1661 if (sce->ics.group_len[w] > 1) { 1662 int avg_sf_idx = 0; 1663 for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) 1664 avg_sf_idx += sce->sf_idx[w*16+g]; 1665 avg_sf_idx /= sce->ics.group_len[w]; 1666 for (w2 = 1; w2 < sce->ics.group_len[w]; w2++) 1667 sce->sf_idx[(w+w2)*16+g] = avg_sf_idx; 1668 } 1669 } 1670 } 1671 } 1050 1672 } 1051 1673 1052 1674 static void search_for_ms(AACEncContext *s, ChannelElement *cpe, 1053 1675 const float lambda) 1054 1676 { 1055 int start = 0, i, w, w2, g ;1677 int start = 0, i, w, w2, g, sid_sf_boost; 1056 1678 float M[128], S[128]; 1057 1679 float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3; 1680 float mslambda = FFMIN(1.0f, lambda / 120.0f); 1058 1681 SingleChannelElement *sce0 = &cpe->ch[0]; 1059 1682 SingleChannelElement *sce1 = &cpe->ch[1]; 1683 1060 1684 if (!cpe->common_window) 1061 1685 return; 1686 1062 1687 for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) { 1688 int min_sf_idx_mid = SCALE_MAX_POS; 1689 int min_sf_idx_side = SCALE_MAX_POS; 1690 for (g = 0; g < sce0->ics.num_swb; g++) { 1691 if (!sce0->zeroes[w*16+g]) 1692 min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]); 1693 if (!sce1->zeroes[w*16+g]) 1694 min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]); 1695 } 1696 1063 1697 for (g = 0; g < sce0->ics.num_swb; g++) { 1698 float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f; 1699 cpe->ms_mask[w*16+g] = 0; 1064 1700 if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) { 1065 float dist1 = 0.0f, dist2 = 0.0f; 1701 float Mmax = 0.0f, Smax = 0.0f; 1702 1703 /* Must compute mid/side SF and book for the whole window group */ 1066 1704 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { 1067 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];1068 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];1069 float minthr = FFMIN(band0->threshold, band1->threshold);1070 float maxthr = FFMAX(band0->threshold, band1->threshold);1071 1705 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1072 M[i] = (sce0-> coeffs[start+w2*128+i]1073 + sce1-> coeffs[start+w2*128+i]) * 0.5;1706 M[i] = (sce0->pcoeffs[start+w2*128+i] 1707 + sce1->pcoeffs[start+w2*128+i]) * 0.5f; 1074 1708 S[i] = M[i] 1075 - sce1->coeffs[start+w2*128+i]; 1709 - sce1->pcoeffs[start+w2*128+i]; 1710 } 1711 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1712 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1713 for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) { 1714 Mmax = FFMAX(Mmax, M34[i]); 1715 Smax = FFMAX(Smax, S34[i]); 1716 } 1717 } 1718 1719 for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) { 1720 float dist1 = 0.0f, dist2 = 0.0f; 1721 int B0 = 0, B1 = 0; 1722 int minidx; 1723 int mididx, sididx; 1724 int midcb, sidcb; 1725 1726 minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]); 1727 mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF); 1728 sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF); 1729 midcb = find_min_book(Mmax, mididx); 1730 sidcb = find_min_book(Smax, sididx); 1731 1732 if ((mididx > minidx) || (sididx > minidx)) { 1733 /* scalefactor range violation, bad stuff, will decrease quality unacceptably */ 1734 continue; 1735 } 1736 1737 /* No CB can be zero */ 1738 midcb = FFMAX(1,midcb); 1739 sidcb = FFMAX(1,sidcb); 1740 1741 for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) { 1742 FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g]; 1743 FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g]; 1744 float minthr = FFMIN(band0->threshold, band1->threshold); 1745 int b1,b2,b3,b4; 1746 for (i = 0; i < sce0->ics.swb_sizes[g]; i++) { 1747 M[i] = (sce0->coeffs[start+w2*128+i] 1748 + sce1->coeffs[start+w2*128+i]) * 0.5; 1749 S[i] = M[i] 1750 - sce1->coeffs[start+w2*128+i]; 1751 } 1752 abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1753 abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]); 1754 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]); 1755 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]); 1756 dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128, 1757 L34, 1758 sce0->ics.swb_sizes[g], 1759 sce0->sf_idx[(w+w2)*16+g], 1760 sce0->band_type[w*16+g], 1761 lambda / band0->threshold, INFINITY, &b1, 0); 1762 dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128, 1763 R34, 1764 sce1->ics.swb_sizes[g], 1765 sce1->sf_idx[(w+w2)*16+g], 1766 sce1->band_type[w*16+g], 1767 lambda / band1->threshold, INFINITY, &b2, 0); 1768 dist2 += quantize_band_cost(s, M, 1769 M34, 1770 sce0->ics.swb_sizes[g], 1771 mididx, 1772 midcb, 1773 lambda / minthr, INFINITY, &b3, 0); 1774 dist2 += quantize_band_cost(s, S, 1775 S34, 1776 sce1->ics.swb_sizes[g], 1777 sididx, 1778 sidcb, 1779 lambda * mslambda / (minthr * bmax), INFINITY, &b4, 0); 1780 B0 += b1+b2; 1781 B1 += b3+b4; 1782 dist1 -= B0; 1783 dist2 -= B1; 1784 } 1785 cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0; 1786 if (cpe->ms_mask[w*16+g]) { 1787 sce0->sf_idx[w*16+g] = mididx; 1788 sce1->sf_idx[w*16+g] = sididx; 1789 sce0->band_type[w*16+g] = midcb; 1790 sce1->band_type[w*16+g] = sidcb; 1791 break; 1792 } else if (B1 > B0) { 1793 /* More boost won't fix this */ 1794 break; 1076 1795 } 1077 abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);1078 abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);1079 abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);1080 abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);1081 dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,1082 L34,1083 sce0->ics.swb_sizes[g],1084 sce0->sf_idx[(w+w2)*16+g],1085 sce0->band_type[(w+w2)*16+g],1086 lambda / band0->threshold, INFINITY, NULL);1087 dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,1088 R34,1089 sce1->ics.swb_sizes[g],1090 sce1->sf_idx[(w+w2)*16+g],1091 sce1->band_type[(w+w2)*16+g],1092 lambda / band1->threshold, INFINITY, NULL);1093 dist2 += quantize_band_cost(s, M,1094 M34,1095 sce0->ics.swb_sizes[g],1096 sce0->sf_idx[(w+w2)*16+g],1097 sce0->band_type[(w+w2)*16+g],1098 lambda / maxthr, INFINITY, NULL);1099 dist2 += quantize_band_cost(s, S,1100 S34,1101 sce1->ics.swb_sizes[g],1102 sce1->sf_idx[(w+w2)*16+g],1103 sce1->band_type[(w+w2)*16+g],1104 lambda / minthr, INFINITY, NULL);1105 1796 } 1106 cpe->ms_mask[w*16+g] = dist2 < dist1;1107 1797 } 1108 1798 start += sce0->ics.swb_sizes[g]; 1109 1799 } … … AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = { 1119 1809 }, 1120 1810 [AAC_CODER_ANMR] = { 1121 1811 search_for_quantizers_anmr, 1122 encode_window_bands_info,1812 codebook_trellis_rate, 1123 1813 quantize_and_encode_band, 1124 1814 search_for_ms, 1125 1815 }, -
libavcodec/aacenc.c
diff --git a/libavcodec/aacenc.c b/libavcodec/aacenc.c index d9c7215..dc3bab6 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 if (isnan(cpe->ch->coeffs[0])) { 571 608 av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n"); 572 609 return AVERROR(EINVAL); … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 576 613 } 577 614 if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels)) < 0) 578 615 return ret; 616 617 frame_bits = 0; 618 its = 0; 579 619 do { 580 int frame_bits;581 620 int target_bits, too_many_bits, too_few_bits; 621 582 622 init_put_bits(&s->pb, avpkt->data, avpkt->size); 583 623 584 624 if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT)) 585 625 put_bitstream_info(s, LIBAVCODEC_IDENT); 586 626 start_ch = 0; 627 target_bits = 0; 587 628 memset(chan_el_counter, 0, sizeof(chan_el_counter)); 588 629 for (i = 0; i < s->chan_map[0]; i++) { 589 630 FFPsyWindowInfo* wi = windows + start_ch; … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 595 636 put_bits(&s->pb, 4, chan_el_counter[tag]++); 596 637 for (ch = 0; ch < chans; ch++) 597 638 coeffs[ch] = cpe->ch[ch].coeffs; 639 s->psy.bitres.alloc = -1; 640 s->psy.bitres.bits = avctx->frame_bits / s->channels; 598 641 s->psy.model->analyze(&s->psy, start_ch, coeffs, wi); 642 if (s->psy.bitres.alloc > 0) { 643 /* Lambda unused here on purpose, we need to take psy's unscaled allocation */ 644 target_bits += s->psy.bitres.alloc; 645 s->psy.bitres.alloc /= chans; 646 } 647 s->cur_type = tag; 599 648 for (ch = 0; ch < chans; ch++) { 600 649 s->cur_channel = start_ch + ch; 601 650 s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda); … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 630 679 if (cpe->common_window) { 631 680 put_ics_info(s, &cpe->ch[0].ics); 632 681 encode_ms_info(&s->pb, cpe); 682 if (cpe->ms_mode) ms_mode = 1; 633 683 } 634 684 } 635 685 for (ch = 0; ch < chans; ch++) { … … static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, 639 689 start_ch += chans; 640 690 } 641 691 692 if (avctx->flags & CODEC_FLAG_QSCALE) { 693 // When using a constant Q-scale, don't mess with lambda 694 break; 695 } 696 697 // rate control stuff 698 // target either the nominal bitrate, or what psy's bit reservoir says to target 699 // whichever is greatest 642 700 frame_bits = put_bits_count(&s->pb); 643 if (frame_bits <= 6144 * s->channels - 3) { 644 s->psy.bitres.bits = frame_bits / s->channels; 701 target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate); 702 target_bits = FFMIN(target_bits, 6144 * s->channels - 3); 703 704 // When using ABR, be strict (but only for increasing) 705 too_many_bits = target_bits + target_bits/2; 706 too_few_bits = target_bits - target_bits/8; 707 //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); 708 709 if ( its == 0 /* for steady-state Q-scale tracking */ 710 || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits)) 711 || frame_bits >= 6144 * s->channels - 3 ) 712 { 713 float ratio = ((float)target_bits) / frame_bits; 714 715 if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) { 716 /* 717 This path is for steady-state Q-scale tracking 718 When frame bits fall within the stable range, we still need to adjust 719 lambda to maintain it like so in a stable fashion (large jumps in lambda 720 create artifacts and shoulda be avoided), but slowly 721 */ 722 ratio = sqrtf(sqrtf(ratio)); 723 ratio = av_clipf(ratio, 0.9f, 1.1f); 724 } else { 725 /* Not so fast though */ 726 ratio = sqrtf(ratio); 727 } 728 s->lambda = FFMIN(s->lambda * ratio, 65536.f); 729 730 // Keep iterating if we must reduce and lambda is in the sky 731 if (s->lambda < 300.f || ratio > 0.9f) { 732 break; 733 } else { 734 if (ms_mode) { 735 for (i = 0; i < s->chan_map[0]; i++) { 736 // Must restore coeffs 737 chans = tag == TYPE_CPE ? 2 : 1; 738 cpe = &s->cpe[i]; 739 for (ch = 0; ch < chans; ch++) 740 memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs)); 741 } 742 } 743 its++; 744 } 745 } else { 645 746 break; 646 747 } 647 648 s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;649 650 748 } while (1); 651 749 652 750 put_bits(&s->pb, 3, TYPE_END); 653 751 flush_put_bits(&s->pb); 654 752 avctx->frame_bits = put_bits_count(&s->pb); 655 753 656 // rate control stuff657 if (!(avctx->flags & CODEC_FLAG_QSCALE)) {658 float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;659 s->lambda *= ratio;660 s->lambda = FFMIN(s->lambda, 65536.f);661 }662 663 754 if (!frame) 664 755 s->last_frame++; 665 756 … … static av_cold int aac_encode_init(AVCodecContext *avctx) 740 831 741 832 s->channels = avctx->channels; 742 833 743 ERROR_IF(i == 16, 834 ERROR_IF(i == 16 835 || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024)) 836 || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)), 744 837 "Unsupported sample rate %d\n", avctx->sample_rate); 745 838 ERROR_IF(s->channels > AAC_MAX_CHANNELS, 746 839 "Unsupported number of channels: %d\n", s->channels); 747 840 ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW, 748 841 "Unsupported profile %d\n", avctx->profile); 749 ERROR_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels, 750 "Too many bits per frame requested\n"); 842 WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels, 843 "Too many bits per frame requested, clamping to max\n"); 844 845 avctx->bit_rate = (int)FFMIN( 846 6144 * s->channels / 1024.0 * avctx->sample_rate, 847 avctx->bit_rate); 751 848 752 849 s->samplerate_index = i; 753 850 … … fail: 794 891 795 892 #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM 796 893 static const AVOption aacenc_options[] = { 797 {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},894 {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, AACENC_FLAGS, "stereo_mode"}, 798 895 {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 799 896 {"ms_off", "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"}, 800 897 {"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 0decb1d..3e040ed 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 9eeb836..c3e72a0 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 void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, 778 824 779 825 psy_band->threshold = band->thr; 780 826 psy_band->energy = band->energy; 827 psy_band->perceptual_weight = band->pe; 828 psy_band->bits = PSY_3GPP_PE_TO_BITS(band->pe); 781 829 } 782 830 } 783 831 … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 827 875 int grouping = 0; 828 876 int uselongblock = 1; 829 877 int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 }; 878 uint8_t clippings[AAC_NUM_BLOCKS_SHORT]; 830 879 int i; 831 880 FFPsyWindowInfo wi = { { 0 } }; 832 881 … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 841 890 842 891 /* LAME comment: apply high pass filter of fs/4 */ 843 892 psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs); 844 893 845 894 /* Calculate the energies of each sub-shortblock */ 846 895 for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) { 847 896 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 965 917 966 lame_apply_block_type(pch, &wi, uselongblock); 918 967 968 /* Calculate input sample maximums and evaluate clipping risk */ 969 if (audio) { 970 for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++) { 971 const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT; 972 float max = 0; 973 int j; 974 for (j = 0; j < AAC_BLOCK_SIZE_SHORT; j++) 975 max = FFMAX(max, fabsf(wbuf[j])); 976 clippings[i] = (max > CLIPPING_THRESHOLD) ? 1 : 0; 977 } 978 } else { 979 for (i = 0; i < 8; i++) 980 clippings[i] = 0; 981 } 982 919 983 wi.window_type[1] = prev_type; 920 984 if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) { 985 int clipping = 0; 986 921 987 wi.num_windows = 1; 922 988 wi.grouping[0] = 1; 923 989 if (wi.window_type[0] == LONG_START_SEQUENCE) 924 990 wi.window_shape = 0; 925 991 else 926 992 wi.window_shape = 1; 993 994 for (i = 0; i < 8 && !clipping; i++) 995 clipping = clippings[i]; 996 wi.clipping[0] = clipping; 927 997 } else { 928 int lastgrp = 0 ;998 int lastgrp = 0, anyclipped = 0; 929 999 930 1000 wi.num_windows = 8; 931 1001 wi.window_shape = 0; … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 934 1004 lastgrp = i; 935 1005 wi.grouping[lastgrp]++; 936 1006 } 1007 1008 for (i = 0; i < 8; i += wi.grouping[i]) { 1009 int w, clipping = 0; 1010 for (w = 0; w < wi.grouping[i] && !clipping; w++) 1011 clipping = clippings[i+w]; 1012 wi.clipping[i] = clipping; 1013 if (clipping) anyclipped = 1; 1014 } 937 1015 } 938 1016 939 1017 /* Determine grouping, based on the location of the first attack, and save for … … static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, 948 1026 break; 949 1027 } 950 1028 } 1029 951 1030 pch->next_grouping = window_grouping[grouping]; 952 1031 953 1032 pch->prev_attack = attacks[8]; -
libavcodec/psymodel.c
diff --git a/libavcodec/psymodel.c b/libavcodec/psymodel.c index 059cbef..7f92b9d 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 75261ba..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
