forge
Explore
Log in

Don't you dare go Hollow

A quality/size targeting surface over base_q_idx

Browse files at this commit

a55d2efb8af2a6da61d2f5c0dc8713fcf9c14fe8Ahmet Kaan GümüşParent: f44b458
  • feat
    • a quality/size targeting surface over base_q_idx
Show full message
feat(av1): a quality/size targeting surface over base_q_idx

RateTarget::{QIndex,Quality,BytesPerFrame} on Av1Encoder::with_rate_target,
additive alongside the existing EncoderConfig::base_q_idx path. Quality
maps to base_q_idx via the calibration sweep's linear fit; BytesPerFrame
steers it with a clamped proportional controller (no accumulated debt, so
no windup class to bound). Calibration sweep test records the curve.
crates/ec-av1/src/encode.rsmodified+43 -0
@@ -4505,4 +4505,47 @@ mod tests {
45054505 elapsed / 24
45064506 );
45074507 }
4508+
4509+ /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
4510+ /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
4511+ /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
4512+ /// -- --ignored --nocapture`.
4513+ #[test]
4514+ #[ignore = "a calibration probe, not a gate"]
4515+ fn calibration_sweep_base_q_idx() {
4516+ if !have_ffmpeg() {
4517+ eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
4518+ return;
4519+ }
4520+ let (width, height, frames) = (640usize, 384usize, 12usize);
4521+ for clip in [
4522+ "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
4523+ "h264-1080p-60-8bit.mp4", // higher motion, 60fps
4524+ ] {
4525+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4526+ .join("../../fixtures/video")
4527+ .join(clip);
4528+ if !path.exists() {
4529+ eprintln!("SKIP {clip}: fixture missing");
4530+ continue;
4531+ }
4532+ let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
4533+ eprintln!("--- {clip} ---");
4534+ for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
4535+ let encoded = encode_sequence(&source, q, 0.5).unwrap();
4536+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
4537+ let mean_psnr: f64 = decoded
4538+ .iter()
4539+ .zip(&source)
4540+ .map(|(d, s)| psnr(&d.y, &s.y))
4541+ .sum::<f64>()
4542+ / frames as f64;
4543+ let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
4544+ eprintln!(
4545+ "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
4546+ encoded.stream.len()
4547+ );
4548+ }
4549+ }
4550+ }
45084551 }
crates/ec-av1/src/encoder.rsmodified+353 -3
@@ -76,11 +76,99 @@ impl Colour {
7676 }
7777 }
7878
79+/// A quality/size targeting surface for callers who would rather not pick a
80+/// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality"
81+/// dial that holds a stable perceptual level across content, `ffmpeg -crf`)
82+/// since a from-scratch scheme is not this lane's charter to invent.
83+/// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`]
84+/// keeps working exactly as before for every existing caller, this is a
85+/// second, opt-in constructor.
86+#[derive(Debug, Clone, Copy, PartialEq)]
87+pub enum RateTarget {
88+ /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own
89+ /// value, for a caller that already has one.
90+ QIndex(u8),
91+ /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best),
92+ /// mapped to a fixed `base_q_idx` by the calibration in
93+ /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx`
94+ /// across the sweep's own 40..=240 span, since the measured bytes/PSNR
95+ /// curve is close enough to log-linear there that a straight line is
96+ /// the "simplest correct" fit this lane's charter asks for). No
97+ /// per-frame feedback: one value, picked once at construction.
98+ Quality(u8),
99+ /// A closed loop that steers `base_q_idx` frame by frame to land each
100+ /// coded frame near this many bytes, via [`RateLoop`] — see there for
101+ /// the controller and its windup bound.
102+ BytesPerFrame(u32),
103+}
104+
105+/// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
106+/// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0);
107+/// `quality` above 100 clamps to the best point measured, matching a CRF
108+/// dial's own saturating ends rather than extrapolating past calibrated
109+/// data.
110+fn quality_to_q_idx(quality: u8) -> u8 {
111+ let quality = f64::from(quality.min(100));
112+ (240.0 - quality * 2.0).round() as u8
113+}
114+
115+/// The closed-loop controller behind [`RateTarget::BytesPerFrame`]: a
116+/// proportional step on `base_q_idx`, sized from the calibration sweep's own
117+/// log-linear slope (bytes roughly halve every ~45 `q_idx` steps there, i.e.
118+/// `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped per frame. Pure proportional —
119+/// no accumulated error term — is the windup bound itself
120+/// ([[vorbis-rate-loop-windup]]'s class): the only state carried between
121+/// frames is `q`, already clamped to `0..=255`, so a quiet lead-in cannot
122+/// build a debt a later transient has to repay; each frame's step is bounded
123+/// by `STEP_CLAMP` regardless of history.
124+#[derive(Debug, Clone, Copy)]
125+struct RateLoop {
126+ target_bytes: u32,
127+ q: f64,
128+}
129+
130+impl RateLoop {
131+ /// The steepest a single frame is allowed to move `base_q_idx`, in
132+ /// either direction — chosen so one wildly over/under-sized frame
133+ /// (a scene cut, a black lead-in) nudges the next frame's quantizer
134+ /// rather than slamming it to an extreme.
135+ const STEP_CLAMP: f64 = 12.0;
136+ /// The calibration sweep's own slope (see the struct doc), inverted to
137+ /// convert a bytes ratio into a `q_idx` step.
138+ const GAIN: f64 = 1.0 / 0.0154;
139+
140+ fn new(target_bytes: u32, start_q: f64) -> Self {
141+ Self {
142+ target_bytes,
143+ q: start_q,
144+ }
145+ }
146+
147+ fn q_idx(&self) -> u8 {
148+ self.q.round().clamp(0.0, 255.0) as u8
149+ }
150+
151+ /// Steers `q` toward `target_bytes` from this frame's actual coded size.
152+ fn update(&mut self, actual_bytes: usize) {
153+ if self.target_bytes == 0 || actual_bytes == 0 {
154+ return;
155+ }
156+ let ratio = actual_bytes as f64 / f64::from(self.target_bytes);
157+ let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);
158+ self.q = (self.q + step).clamp(0.0, 255.0);
159+ }
160+}
161+
79162 /// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
80163 /// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
81164 /// unit) rather than a bitrate — a bitrate control loop is not part of this
82165 /// lane's charter, and a caller that wants one can still derive a
83-/// `base_q_idx` from its own target and set that field.
166+/// `base_q_idx` from its own target and set that field. A caller who wants
167+/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
168+/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
169+/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
170+/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
171+/// two variants).
84172 #[derive(Debug, Clone, Copy)]
85173 pub struct EncoderConfig {
86174 /// The picture's width in luma samples; must be even and nonzero.
@@ -128,6 +216,11 @@ pub struct Av1Encoder {
128216 /// than read.
129217 reference: Option<Picture>,
130218 next_index: u64,
219+ /// `Some` only when constructed via
220+ /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
221+ /// otherwise every picture is coded at `config.base_q_idx`, unchanged
222+ /// from before this field existed.
223+ rate_loop: Option<RateLoop>,
131224 }
132225
133226 impl Av1Encoder {
@@ -149,9 +242,35 @@ impl Av1Encoder {
149242 config,
150243 reference: None,
151244 next_index: 0,
245+ rate_loop: None,
152246 })
153247 }
154248
249+ /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
250+ /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
251+ /// `config.base_q_idx` being used as-is.
252+ ///
253+ /// # Errors
254+ /// Same as [`Av1Encoder::new`].
255+ pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
256+ let rate_loop = match rate {
257+ RateTarget::QIndex(q) => {
258+ config.base_q_idx = q;
259+ None
260+ }
261+ RateTarget::Quality(quality) => {
262+ config.base_q_idx = quality_to_q_idx(quality);
263+ None
264+ }
265+ RateTarget::BytesPerFrame(target_bytes) => {
266+ Some(RateLoop::new(target_bytes, f64::from(config.base_q_idx)))
267+ }
268+ };
269+ let mut encoder = Self::new(config)?;
270+ encoder.rate_loop = rate_loop;
271+ Ok(encoder)
272+ }
273+
155274 /// The coded (padded-to-64) frame size every picture in this stream is
156275 /// coded at — what a decoder allocates and what `ffprobe` reports.
157276 #[must_use]
@@ -192,11 +311,15 @@ impl Av1Encoder {
192311 let padded = picture.padded_to(SUPERBLOCK);
193312 let is_key = self.next_index % self.config.gop as u64 == 0;
194313 let order = self.next_index;
314+ let base_q_idx = self
315+ .rate_loop
316+ .as_ref()
317+ .map_or(self.config.base_q_idx, RateLoop::q_idx);
195318
196319 let encoded: Encoded = if is_key {
197320 encode_key_frame_inner(
198321 &padded,
199- self.config.base_q_idx,
322+ base_q_idx,
200323 DEADZONE,
201324 &KEY_FRAME_MODES,
202325 split_blocks(),
@@ -213,7 +336,7 @@ impl Av1Encoder {
213336 encode_inter_frame(
214337 &padded,
215338 reference,
216- self.config.base_q_idx,
339+ base_q_idx,
217340 DEADZONE,
218341 order as u32,
219342 render,
@@ -223,6 +346,9 @@ impl Av1Encoder {
223346 self.reference = Some(encoded.reconstruction.clone());
224347 self.next_index += 1;
225348 let cropped = crop_encoded(&encoded, render.0, render.1);
349+ if let Some(rate_loop) = self.rate_loop.as_mut() {
350+ rate_loop.update(cropped.stream.len());
351+ }
226352 Ok(Packet {
227353 data: cropped.stream,
228354 key: is_key,
@@ -512,4 +638,228 @@ mod tests {
512638 let err = Av1Encoder::new(config).unwrap_err();
513639 assert!(err.to_string().contains("gop"), "{err}");
514640 }
641+
642+ /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
643+ /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
644+ /// to this facade's own input size, and re-coded through the facade so the
645+ /// rate-target surface is exercised at the entry point a caller actually
646+ /// drives.
647+ fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
648+ if !have_ffmpeg() {
649+ return None;
650+ }
651+ let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
652+ .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
653+ if !clip.exists() {
654+ return None;
655+ }
656+ let out = Command::new("ffmpeg")
657+ .args(["-v", "error", "-i", clip.to_str().unwrap()])
658+ .args(["-frames:v", &frames.to_string()])
659+ .args(["-vf", &format!("scale={width}:{height}")])
660+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
661+ .output()
662+ .expect("ffmpeg failed to run");
663+ assert!(
664+ out.status.success(),
665+ "{}",
666+ String::from_utf8_lossy(&out.stderr)
667+ );
668+ let (luma, chroma) = (width * height, width * height / 4);
669+ let frame_len = luma + 2 * chroma;
670+ assert_eq!(
671+ out.stdout.len(),
672+ frame_len * frames,
673+ "expected {frames} 4:2:0 frames"
674+ );
675+ Some(
676+ (0..frames)
677+ .map(|i| {
678+ let bytes = &out.stdout[i * frame_len..][..frame_len];
679+ Picture {
680+ width,
681+ height,
682+ y: bytes[..luma].to_vec(),
683+ u: bytes[luma..luma + chroma].to_vec(),
684+ v: bytes[luma + chroma..].to_vec(),
685+ }
686+ })
687+ .collect(),
688+ )
689+ }
690+
691+ /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
692+ /// coded size within ±20% of `frames * target` once the first few
693+ /// frames' settling has been discarded (the key frame's own reference
694+ /// state and the controller's first couple of steps).
695+ #[test]
696+ fn bytes_per_frame_target_settles_within_20_percent() {
697+ let Some(pictures) = h264_clip_frames(640, 384, 24) else {
698+ eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
699+ return;
700+ };
701+ let target_bytes = 4_000u32;
702+ let config = EncoderConfig {
703+ width: 640,
704+ height: 384,
705+ base_q_idx: 100,
706+ gop: 24,
707+ colour: Colour::Bt709Limited,
708+ };
709+ let mut enc =
710+ Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
711+ let sizes: Vec<usize> = pictures
712+ .iter()
713+ .map(|p| enc.encode(p).unwrap().data.len())
714+ .collect();
715+ // Discard the key frame (always far larger than an inter target) and
716+ // the next 4 inter frames the loop needs to step toward it.
717+ let settled = &sizes[5..];
718+ let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
719+ let low = f64::from(target_bytes) * 0.8;
720+ let high = f64::from(target_bytes) * 1.2;
721+ assert!(
722+ mean >= low && mean <= high,
723+ "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
724+ );
725+ }
726+
727+ /// The `BytesPerFrame` controller's own windup bound: no frame's coded
728+ /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
729+ /// clip's full range of content (so a scene cut can't be the one frame
730+ /// that breaks the bound).
731+ #[test]
732+ fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
733+ let Some(pictures) = h264_clip_frames(640, 384, 24) else {
734+ eprintln!(
735+ "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
736+ );
737+ return;
738+ };
739+ let config = EncoderConfig {
740+ width: 640,
741+ height: 384,
742+ base_q_idx: 100,
743+ gop: 24,
744+ colour: Colour::Bt709Limited,
745+ };
746+ let mut enc =
747+ Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
748+ let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();
749+ for picture in &pictures {
750+ enc.encode(picture).unwrap();
751+ let q = enc.rate_loop.as_ref().unwrap().q_idx();
752+ let step = (i32::from(q) - i32::from(prev_q)).abs();
753+ assert!(
754+ f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
755+ "q stepped from {prev_q} to {q}, past the {} clamp",
756+ RateLoop::STEP_CLAMP
757+ );
758+ prev_q = q;
759+ }
760+ }
761+
762+ fn psnr(a: &[u8], b: &[u8]) -> f64 {
763+ let squared: f64 = a
764+ .iter()
765+ .zip(b)
766+ .map(|(&x, &y)| {
767+ let d = f64::from(x) - f64::from(y);
768+ d * d
769+ })
770+ .sum();
771+ if squared == 0.0 {
772+ return f64::INFINITY;
773+ }
774+ 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
775+ }
776+
777+ /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
778+ /// entry per coded frame, in order — this facade's own equivalent of
779+ /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
780+ /// PSNR check needs the decoded pixels, not just the coded byte count.
781+ fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
782+ let path = std::env::temp_dir().join(format!(
783+ "ec-av1-facade-rate-decode-{}-{}.obu",
784+ std::process::id(),
785+ std::ptr::addr_of!(stream) as usize
786+ ));
787+ std::fs::write(&path, stream).expect("writing the decode probe stream");
788+ let out = Command::new("ffmpeg")
789+ .args(["-v", "error", "-f", "obu", "-i"])
790+ .arg(&path)
791+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
792+ .output()
793+ .expect("ffmpeg failed to run");
794+ let _ = std::fs::remove_file(&path);
795+ assert!(
796+ out.status.success(),
797+ "{}",
798+ String::from_utf8_lossy(&out.stderr)
799+ );
800+ let (luma, chroma) = (width * height, width * height / 4);
801+ let frame_len = luma + 2 * chroma;
802+ out.stdout
803+ .chunks_exact(frame_len)
804+ .map(|f| f[..luma].to_vec())
805+ .collect()
806+ }
807+
808+ /// [`RateTarget::Quality`] is monotone: a higher quality dial never
809+ /// produces a smaller stream or a worse mean PSNR than a lower one, on
810+ /// the same real clip.
811+ #[test]
812+ fn quality_target_is_monotone_in_bytes_and_psnr() {
813+ if !have_ffmpeg() {
814+ eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
815+ return;
816+ }
817+ let (width, height) = (640, 384);
818+ let Some(pictures) = h264_clip_frames(width, height, 8) else {
819+ eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
820+ return;
821+ };
822+ let mut prev_bytes = 0usize;
823+ let mut prev_psnr = 0.0f64;
824+ for quality in [20u8, 50, 80] {
825+ let config = EncoderConfig {
826+ width,
827+ height,
828+ base_q_idx: 100,
829+ gop: 8,
830+ colour: Colour::Bt709Limited,
831+ };
832+ let mut enc =
833+ Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
834+ let mut stream = Vec::new();
835+ let mut total_bytes = 0usize;
836+ for picture in &pictures {
837+ let packet = enc.encode(picture).unwrap();
838+ total_bytes += packet.data.len();
839+ stream.extend_from_slice(&packet.data);
840+ }
841+ let decoded = ffmpeg_decode_luma(&stream, width, height);
842+ assert_eq!(
843+ decoded.len(),
844+ pictures.len(),
845+ "quality {quality}: dav1d frame count"
846+ );
847+ let mean_psnr: f64 = decoded
848+ .iter()
849+ .zip(&pictures)
850+ .map(|(d, p)| psnr(d, &p.y))
851+ .sum::<f64>()
852+ / decoded.len() as f64;
853+ assert!(
854+ total_bytes >= prev_bytes,
855+ "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
856+ );
857+ assert!(
858+ mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
859+ "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
860+ );
861+ prev_bytes = total_bytes;
862+ prev_psnr = mean_psnr;
863+ }
864+ }
515865 }