+ int tbits;
+ int cutoff = 1024;
+ int pns_start_pos;
+
+ /**
+ * zeroscale controls a multiplier of the threshold, if band energy
+ * is below this, a zero is forced. Keep it lower than 1, unless
+ * low lambda is used, because energy < threshold doesn't mean there's
+ * no audible signal outright, it's just energy. Also make it rise
+ * slower than rdlambda, as rdscale has due compensation with
+ * noisy band depriorization below, whereas zeroing logic is rather dumb
+ */
+ float zeroscale;
+ if (lambda > 120.f) {
+ zeroscale = av_clipf(powf(120.f / lambda, 0.25f), 0.0625f, 1.0f);
+ } else {
+ zeroscale = 1.f;
+ }
+
+ if (s->psy.bitres.alloc >= 0) {
+ /**
+ * Psy granted us extra bits to use, from the reservoire
+ * adjust for lambda except what psy already did
+ */
+ destbits = s->psy.bitres.alloc
+ * (lambda / (avctx->global_quality ? avctx->global_quality : 120));
+ }
+
+ if (avctx->flags & CODEC_FLAG_QSCALE) {
+ /**
+ * Constant Q-scale doesn't compensate MS coding on its own
+ * No need to be overly precise, this only controls RD
+ * adjustment CB limits when going overboard
+ */
+ if (s->options.stereo_mode && s->cur_type == TYPE_CPE)
+ destbits *= 2;
+
+ /**
+ * When using a constant Q-scale, don't adjust bits, just use RD
+ * Don't let it go overboard, though... 8x psy target is enough
+ */
+ toomanybits = 5800;
+ toofewbits = destbits / 16;
+
+ /** Don't offset scalers, just RD */
+ sfoffs = sce->ics.num_windows - 1;
+ rdlambda = sqrtf(rdlambda);
+
+ /** search further */
+ maxits *= 2;
+ } else {
+ /** When using ABR, be strict */
+ toomanybits = destbits + destbits/16;
+ toofewbits = destbits - destbits/4;
+
+ sfoffs = 0;
+ rdlambda = sqrtf(rdlambda);
+ }
+
+ /** and zero out above cutoff frequency */
+ {
+ int wlen = 1024 / sce->ics.num_windows;
+ int bandwidth;
+
+ /**
+ * Scale, psy gives us constant quality, this LP only scales
+ * bitrate by lambda, so we save bits on subjectively unimportant HF
+ * rather than increase quantization noise. Adjust nominal bitrate
+ * to effective bitrate according to encoding parameters,
+ * AAC_CUTOFF_FROM_BITRATE is calibrated for effective bitrate.
+ */
+ float rate_bandwidth_multiplier = 1.5f;
+ int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
+ ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
+ : (avctx->bit_rate / avctx->channels);
+
+ /** Compensate for extensions that increase efficiency */
+ if (s->options.pns || s->options.intensity_stereo)
+ frame_bit_rate *= 1.15f;