Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

h264enc: 1-pass bitrate modes no longer starve the opening second (#74)

EthanSuquet68173aa82ab7
diff --git a/crates/h264enc/src/ratecontrol.rs b/crates/h264enc/src/ratecontrol.rs
index 35f4780f8..9f77a6813 100644
--- a/crates/h264enc/src/ratecontrol.rs
+++ b/crates/h264enc/src/ratecontrol.rs
@@ -101,7 +101,11 @@ pub struct RateControl {
model_done: f64,
inflight: std::collections::VecDeque<f64>,
last_q: f64,
+ /// Virtual history for 1-pass ABR: (frame count, complexity of one virtual frame), fixed at the first frame.
prior: Option<(f64, f64)>,
+ /// Sum and count of the rate-model terms (`coef · cplx^QCOMP / type_factor`) of the coded P and B frames.
+ inter_s: f64,
+ inter_n: u64,
}
impl RateControl {
@@ -124,6 +128,8 @@ impl RateControl {
inflight: std::collections::VecDeque::new(),
last_q: 0.0,
prior: None,
+ inter_s: 0.0,
+ inter_n: 0,
}
}
@@ -173,16 +179,16 @@ impl RateControl {
let bpf = *kbps as f64 * 1000.0 / self.fps;
// rate factor so that past frames at this rf would have hit the target
let s_here = self.coef[ti] * cplx.powf(QCOMP) / type_factor(t);
- // Virtual history of one second of P frames (inter cost ~ 40% of the first frame's) so the first
- // I frame gets a realistic share of the budget instead of a single frame's worth.
- let (fps, coef1) = (self.fps, self.coef[1]);
- let (pn0, ps0) = *self.prior.get_or_insert_with(|| {
- let n = fps.max(1.0);
- let c0 = if t == SliceType::I { 0.4 * cplx } else { cplx };
- (n, n * coef1 * c0.powf(QCOMP))
- });
+ // Virtual history of one second of inter frames so the first I frame gets a realistic share of the
+ // budget instead of a single frame's worth. A virtual frame costs what the P and B frames coded so far
+ // cost on average; before the first of them, a P frame of 40% of the first frame's complexity under
+ // the current model. Re-estimated every frame: the initial guess of `coef` can be several times off,
+ // and a history frozen at that guess starves the opening second of bits.
+ let fps = self.fps;
+ let (pn0, c0) = *self.prior.get_or_insert_with(|| (fps.max(1.0), if t == SliceType::I { 0.4 * cplx } else { cplx }));
+ let per_frame = if self.inter_n > 0 { self.inter_s / self.inter_n as f64 } else { self.coef[1] * c0.powf(QCOMP) };
let fade = (1.0 - self.frames as f64 / pn0).max(0.0);
- let (pn, ps) = (pn0 * fade, ps0 * fade);
+ let (pn, ps) = (pn0 * fade, pn0 * fade * per_frame);
let s = self.sum_s + s_here + ps;
let wanted = bpf * (self.frames as f64 + 1.0 + pn);
let mut rf = s / wanted;
@@ -242,7 +248,12 @@ impl RateControl {
self.coef[k] = self.coef[ti] * [1.2, 1.0, 0.85][k] / [1.2, 1.0, 0.85][ti];
}
}
- self.sum_s += self.coef[ti] * cplx.powf(QCOMP) / type_factor(t);
+ let s_frame = self.coef[ti] * cplx.powf(QCOMP) / type_factor(t);
+ self.sum_s += s_frame;
+ if t != SliceType::I {
+ self.inter_s += s_frame;
+ self.inter_n += 1;
+ }
self.total_bits += bits as f64;
if let Some(p) = self.inflight.pop_front() {
self.model_done += p;
diff --git a/crates/h264enc/tests/ffmpeg_oracle.rs b/crates/h264enc/tests/ffmpeg_oracle.rs
index 86446535c..e19cfc49b 100644
--- a/crates/h264enc/tests/ffmpeg_oracle.rs
+++ b/crates/h264enc/tests/ffmpeg_oracle.rs
@@ -187,6 +187,32 @@ fn abr_hits_target() {
}
}
+/// 1-pass VBR must not starve the opening second of a 60 fps export (#74): the rate model's initial guess
+/// is several times too pessimistic, and a virtual history frozen at that guess kept the pictures after the
+/// first one 6–9 dB below the rest until it faded out after one second.
+#[test]
+fn vbr_opening_second_is_not_starved() {
+ if ffmpeg().is_none() {
+ return;
+ }
+ let (w, h, n, fps) = (640, 360, 120, 60);
+ let frames: Vec<Yuv> = (0..n).map(|t| synth(w, h, t)).collect();
+ let mut c = cfg(w, h, Profile::High, Preset::Balanced, 2, RateControl::Vbr { target_kbps: 2000, max_kbps: 3000 }, 0);
+ c.fps_num = fps;
+ c.keyint = 2 * fps;
+ let run = encode(c, &frames);
+ let dec = verify("vbr_opening", &run, w, h, n);
+ let fs = w * h * 3 / 2;
+ let ps: Vec<f64> = frames.iter().enumerate().map(|(i, f)| psnr(&dec[i * fs..i * fs + w * h], &f.y)).collect();
+ let mean = |r: std::ops::Range<usize>| ps[r.clone()].iter().sum::<f64>() / r.len() as f64;
+ // 0.1–0.5 s against everything after the first second (the same GOP, so no new I frame in between).
+ let (opening, settled) = (mean(6..30), mean(60..n));
+ let kbps = run.stream.len() as f64 * 8.0 / (n as f64 / fps as f64) / 1000.0;
+ eprintln!("opening {opening:.2} dB, after 1 s {settled:.2} dB, {kbps:.1} kbps");
+ assert!(settled - opening <= 3.0, "opening second starved: {opening:.2} dB vs {settled:.2} dB after 1 s");
+ assert!((kbps - 2000.0).abs() / 2000.0 <= 0.10, "{kbps:.1} kbps vs target 2000");
+}
+
#[test]
fn two_pass_vbr_hits_target() {
if ffmpeg().is_none() {