forge
Explore
Log in

Don't you dare go Hollow

A hardware AV1 quality row against librav1e and libaom

Browse files at this commit

c1c4cb507cbf1cf725111ccffb5f1a86d1f1b8c6Ahmet Kaan GümüşParent: 24f4e5c
  • test
    • a hardware AV1 quality row against librav1e and libaom
Show full message
test(ec-hw): a hardware AV1 quality row against librav1e and libaom

Four quantisers on a 1080p crop of a film and of a screen capture from
the real-library manifest, PSNR from ffmpeg, BD-rate over the shared
quality range. The number is printed, not asserted -- a fixed-function
encoder is not a search -- but the ladders are asserted monotone.
crates/ec-hw/tests/gpu.rsmodified+305 -0
@@ -918,6 +918,311 @@ fn av1_encode_agrees_between_two_decoders() {
918 }918 }
919 }919 }
920 920
921+/// What the GPU's AV1 costs against software, on his own content.
922+///
923+/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen
924+/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range
925+/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about
926+/// the number — a fixed-function encoder is not a search — but it is measured
927+/// and printed rather than assumed, and the ladder itself is asserted to be
928+/// monotone, which is the part a broken parameter set would break.
929+#[test]
930+fn av1_encode_bd_row_vs_software() {
931+ let Some(display) = display() else { return };
932+ let clips = real_clips();
933+ if clips.is_empty() {
934+ eprintln!("skipped: no real-library manifest");
935+ return;
936+ }
937+ // A ladder compared with itself saves nothing: the check on the metric.
938+ let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)];
939+ assert!(bd_rate(&same, &same).abs() < 1e-9, "bd_rate is not self-zero");
940+
941+ let dir = std::env::temp_dir().join("ec-hw-av1-bd");
942+ let _ = std::fs::create_dir_all(&dir);
943+ for (label, source) in clips {
944+ let y4m = dir.join(format!("{label}.y4m"));
945+ let (width, height, frames) = (1920u32, 1080u32, 12u32);
946+ if !extract_y4m(&source, &y4m, width, height, frames) {
947+ eprintln!("skipped {label}: extraction failed");
948+ continue;
949+ }
950+ let planes = match raw_frames(&y4m, width, height, frames) {
951+ Some(planes) => planes,
952+ None => {
953+ eprintln!("skipped {label}: no frames extracted");
954+ continue;
955+ }
956+ };
957+
958+ let mut ours = Vec::new();
959+ // Descending quantiser: every ladder here is ordered by rising rate.
960+ for qp in [180u32, 140, 100, 60] {
961+ let mut config = EncoderConfig::new(EncCodec::Av1, width, height);
962+ config.framerate = (24, 1);
963+ config.gop_size = 60;
964+ config.rate_control = RateControlMode::ConstantQp { qp };
965+ let mut encoder = match Encoder::new(&display, config) {
966+ Ok(encoder) => encoder,
967+ Err(e) => {
968+ eprintln!("skipped: AV1 encode unavailable ({e})");
969+ return;
970+ }
971+ };
972+ let mut bytes = Vec::new();
973+ for (i, frame) in planes.iter().enumerate() {
974+ let coded = encoder
975+ .encode(
976+ frame,
977+ FrameMetadata {
978+ timestamp: i as i64,
979+ force_keyframe: false,
980+ },
981+ )
982+ .expect("hardware AV1 encode");
983+ bytes.extend_from_slice(&coded.data);
984+ }
985+ let path = dir.join(format!("{label}-hw-{qp}.obu"));
986+ std::fs::write(&path, &bytes).expect("write");
987+ if let Some(db) = ffmpeg_psnr(&path, &y4m, true) {
988+ ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db));
989+ }
990+ }
991+ let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60]
992+ .iter()
993+ .filter_map(|q| {
994+ software_point(
995+ &dir,
996+ &y4m,
997+ label,
998+ "librav1e",
999+ &["-rav1e-params", &format!("speed=6:quantizer={q}"), "-g", "60"],
1000+ *q,
1001+ frames,
1002+ )
1003+ })
1004+ .collect();
1005+ let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20]
1006+ .iter()
1007+ .filter_map(|crf| {
1008+ software_point(
1009+ &dir,
1010+ &y4m,
1011+ label,
1012+ "libaom-av1",
1013+ &[
1014+ "-cpu-used", "6", "-crf", &crf.to_string(), "-b:v", "0", "-g", "60",
1015+ ],
1016+ *crf,
1017+ frames,
1018+ )
1019+ })
1020+ .collect();
1021+
1022+ for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] {
1023+ println!("{label} {name}: {ladder:?}");
1024+ for pair in ladder.windows(2) {
1025+ assert!(
1026+ pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1,
1027+ "{label} {name}: ladder is not monotone at {pair:?}"
1028+ );
1029+ }
1030+ }
1031+ if ours.len() >= 3 && rav1e.len() >= 3 {
1032+ println!(
1033+ "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%",
1034+ bd_rate(&rav1e, &ours) * 100.0
1035+ );
1036+ }
1037+ if ours.len() >= 3 && libaom.len() >= 3 {
1038+ println!(
1039+ "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%",
1040+ bd_rate(&libaom, &ours) * 100.0
1041+ );
1042+ }
1043+ }
1044+}
1045+
1046+/// One software encoder's rate/PSNR point, or `None` when that encoder is not
1047+/// built into this ffmpeg.
1048+fn software_point(
1049+ dir: &Path,
1050+ y4m: &Path,
1051+ label: &str,
1052+ encoder: &str,
1053+ args: &[&str],
1054+ point: u32,
1055+ frames: u32,
1056+) -> Option<(f64, f64)> {
1057+ let out = dir.join(format!("{label}-{encoder}-{point}.ivf"));
1058+ let _ = std::fs::remove_file(&out);
1059+ let status = Command::new("ffmpeg")
1060+ .args(["-nostdin", "-v", "error", "-y", "-i"])
1061+ .arg(y4m)
1062+ .args(["-c:v", encoder])
1063+ .args(args)
1064+ .arg(&out)
1065+ .status()
1066+ .ok()?;
1067+ if !status.success() {
1068+ return None;
1069+ }
1070+ let bytes = std::fs::metadata(&out).ok()?.len() as f64;
1071+ let db = ffmpeg_psnr(&out, y4m, false)?;
1072+ Some((bytes * 8.0 / f64::from(frames), db))
1073+}
1074+
1075+/// PSNR of a coded stream against the source, from ffmpeg's own filter.
1076+fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option<f64> {
1077+ let mut cmd = Command::new("ffmpeg");
1078+ cmd.args(["-nostdin", "-v", "info"]);
1079+ if raw_obu {
1080+ cmd.args(["-f", "obu"]);
1081+ }
1082+ // Both inputs are pinned to the same rate: a raw OBU stream carries no
1083+ // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps
1084+ // source and the filter would compare frame i with frame i+k.
1085+ let out = cmd
1086+ .args(["-r", "24"])
1087+ .arg("-i")
1088+ .arg(coded)
1089+ .args(["-r", "24"])
1090+ .arg("-i")
1091+ .arg(source)
1092+ .args(["-lavfi", "psnr", "-f", "null", "-"])
1093+ .output()
1094+ .ok()?;
1095+ let text = String::from_utf8_lossy(&out.stderr);
1096+ let field = text.split("average:").nth(1)?;
1097+ field
1098+ .split_whitespace()
1099+ .next()?
1100+ .parse::<f64>()
1101+ .ok()
1102+ .filter(|v| v.is_finite())
1103+}
1104+
1105+/// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share.
1106+fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool {
1107+ let _ = std::fs::remove_file(out);
1108+ Command::new("ffmpeg")
1109+ .args(["-nostdin", "-v", "error", "-y", "-ss", "60", "-i"])
1110+ .arg(source)
1111+ .args([
1112+ "-frames:v",
1113+ &frames.to_string(),
1114+ "-vf",
1115+ &format!("scale={width}:{height}"),
1116+ "-pix_fmt",
1117+ "yuv420p",
1118+ ])
1119+ .arg(out)
1120+ .status()
1121+ .is_ok_and(|s| s.success())
1122+}
1123+
1124+/// The same pictures as planes, for the hardware encoder's own input.
1125+fn raw_frames(y4m: &Path, width: u32, height: u32, frames: u32) -> Option<Vec<I420>> {
1126+ let out = Command::new("ffmpeg")
1127+ .args(["-nostdin", "-v", "error", "-i"])
1128+ .arg(y4m)
1129+ .args(["-pix_fmt", "yuv420p", "-f", "rawvideo", "-"])
1130+ .stderr(Stdio::null())
1131+ .output()
1132+ .ok()?;
1133+ let (w, h) = (width as usize, height as usize);
1134+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
1135+ let frame_len = w * h + 2 * cw * ch;
1136+ let mut pictures = Vec::new();
1137+ for chunk in out.stdout.chunks_exact(frame_len).take(frames as usize) {
1138+ let (y, rest) = chunk.split_at(w * h);
1139+ let (u, v) = rest.split_at(cw * ch);
1140+ pictures.push(I420 {
1141+ y: y.to_vec(),
1142+ u: u.to_vec(),
1143+ v: v.to_vec(),
1144+ width,
1145+ height,
1146+ });
1147+ }
1148+ (!pictures.is_empty()).then_some(pictures)
1149+}
1150+
1151+/// One film and one screen capture from the real-library manifest, labelled
1152+/// rather than named: the titles are his, not this suite's.
1153+fn real_clips() -> Vec<(&'static str, PathBuf)> {
1154+ let manifest =
1155+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/real-library-manifest.tsv");
1156+ let Ok(text) = std::fs::read_to_string(&manifest) else {
1157+ return Vec::new();
1158+ };
1159+ let mut film = None;
1160+ let mut screen = None;
1161+ for line in text.lines().skip(1) {
1162+ let f: Vec<&str> = line.split('\t').collect();
1163+ if f.len() < 7 || f[2] != "h264" {
1164+ continue;
1165+ }
1166+ let width: u32 = f[3].parse().unwrap_or(0);
1167+ // Long enough that the extraction's 60 s seek lands inside the file.
1168+ let duration: f64 = f.get(8).and_then(|d| d.parse().ok()).unwrap_or(0.0);
1169+ if width < 1280 || duration < 90.0 {
1170+ continue;
1171+ }
1172+ let path = PathBuf::from(f[0]);
1173+ if f[0].contains("/Films/") && film.is_none() {
1174+ film = Some(("film A", path));
1175+ } else if f[0].contains("/OBS/") && screen.is_none() {
1176+ screen = Some(("screen capture", path));
1177+ }
1178+ }
1179+ film.into_iter().chain(screen).collect()
1180+}
1181+
1182+/// BD-rate of `test` against `reference`, as a fraction (negative = fewer
1183+/// bits for the same quality), integrated piecewise-linearly in
1184+/// `log10(bits per frame)` over the PSNR range the two ladders share.
1185+///
1186+/// The cubic fit of the original method needs four well-spread points and
1187+/// misbehaves outside them; a trapezoid over the overlap is the honest
1188+/// version of the same integral for ladders this short.
1189+fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 {
1190+ let low = reference[0].1.max(test[0].1);
1191+ let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1);
1192+ if !(high > low) {
1193+ return f64::NAN;
1194+ }
1195+ // log-rate at a PSNR, linearly interpolated inside the ladder.
1196+ let at = |ladder: &[(f64, f64)], db: f64| -> f64 {
1197+ for pair in ladder.windows(2) {
1198+ let ((r0, d0), (r1, d1)) = (pair[0], pair[1]);
1199+ if db >= d0 && db <= d1 {
1200+ let t = if (d1 - d0).abs() < f64::EPSILON {
1201+ 0.0
1202+ } else {
1203+ (db - d0) / (d1 - d0)
1204+ };
1205+ return r0.log10() + t * (r1.log10() - r0.log10());
1206+ }
1207+ }
1208+ if db < ladder[0].1 {
1209+ ladder[0].0.log10()
1210+ } else {
1211+ ladder[ladder.len() - 1].0.log10()
1212+ }
1213+ };
1214+ let steps = 100;
1215+ let mut integral = 0.0;
1216+ for i in 0..steps {
1217+ let a = low + (high - low) * f64::from(i) / f64::from(steps);
1218+ let b = low + (high - low) * f64::from(i + 1) / f64::from(steps);
1219+ let da = at(test, a) - at(reference, a);
1220+ let db = at(test, b) - at(reference, b);
1221+ integral += (da + db) / 2.0 * (b - a);
1222+ }
1223+ 10f64.powf(integral / (high - low)) - 1.0
1224+}
1225+
921 /// Hardware AV1 encode speed at the two sizes his library is in, in frames per1226 /// Hardware AV1 encode speed at the two sizes his library is in, in frames per
922 /// second. Real time is 24 fps; the number is printed rather than asserted,1227 /// second. Real time is 24 fps; the number is printed rather than asserted,
923 /// since a busy GPU is not a failing encoder.1228 /// since a busy GPU is not a failing encoder.