+ /* rate control stuff
+ * target either the nominal bitrate, or what psy's bit reservoir says to target
+ * whichever is greatest
+ */
+
+ frame_bits = put_bits_count(&s->pb);
+ target_bits = FFMAX(target_bits, avctx->bit_rate * 1024 / avctx->sample_rate);
+ target_bits = FFMIN(target_bits, 6144 * s->channels - 3);
+
+ /* When using ABR, be strict (but only for increasing) */
+ too_many_bits = target_bits + target_bits/2;
+ too_few_bits = target_bits - target_bits/8;
+
+ if ( its == 0 /* for steady-state Q-scale tracking */
+ || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
+ || frame_bits >= 6144 * s->channels - 3 )
+ {
+ float ratio = ((float)target_bits) / frame_bits;
+
+ if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
+ /*
+ * This path is for steady-state Q-scale tracking
+ * When frame bits fall within the stable range, we still need to adjust
+ * lambda to maintain it like so in a stable fashion (large jumps in lambda
+ * create artifacts and should be avoided), but slowly
+ */
+ ratio = sqrtf(sqrtf(ratio));
+ ratio = av_clipf(ratio, 0.9f, 1.1f);
+ } else {
+ /* Not so fast though */
+ ratio = sqrtf(ratio);
+ }
+ s->lambda = FFMIN(s->lambda * ratio, 65536.f);