BD-PSNR gate against x264, the encoder's first reference
Browse files at this commit5e93348a957b701c48e63fb64c4b637d0acbfdc9Parent: f8a771e- test
- BD-PSNR gate against x264, the encoder's first reference
1 changed file +204 -19
- crates/ec-h264/tests/encode.rs +204 -19
crates/ec-h264/tests/encode.rsmodified+204 -19
| @@ -700,25 +700,13 @@ fn real_library_frames_encode_and_decode_exactly() { | |||
| 700 | assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); | 700 | assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); |
| 701 | } | 701 | } |
| 702 | 702 | ||
| 703 | -/// BD-PSNR of the opt-in `transform_8x8` flag against flag-off on one real | 703 | +/// The first `want` pictures a second apart from one of the user's media |
| 704 | -/// clip from the library, full size, over a QP sweep: the number the synthetic | 704 | +/// files: demuxed by ec-mp4, decoded by this crate, every Nth frame with N the |
| 705 | -/// gate above cannot give, because the synthetic clip is content the flag wins | 705 | +/// source frame rate. Returns the luma/chroma size and the pictures. |
| 706 | -/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; | 706 | +fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { |
| 707 | -/// asserts nothing, so a regressing clip fails a gate, not the test run. | ||
| 708 | -/// | ||
| 709 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | ||
| 710 | -/// real_clip_t8x8_bd_psnr -- --ignored --nocapture | ||
| 711 | -#[test] | ||
| 712 | -#[ignore = "set EC_H264_CLIP to a media file of yours"] | ||
| 713 | -fn real_clip_t8x8_bd_psnr() { | ||
| 714 | use ec_core::registry::{Decoder as _, Demuxer as _}; | 707 | use ec_core::registry::{Decoder as _, Demuxer as _}; |
| 715 | 708 | ||
| 716 | - let Some(path) = std::env::var_os("EC_H264_CLIP") else { | 709 | + let file = std::fs::File::open(path).expect("source opens"); |
| 717 | - panic!("EC_H264_CLIP must name a media file"); | ||
| 718 | - }; | ||
| 719 | - // The first 30 pictures a second apart, demuxed by ec-mp4 and decoded by | ||
| 720 | - // this crate: every Nth frame, N the source frame rate. | ||
| 721 | - let file = std::fs::File::open(&path).expect("source opens"); | ||
| 722 | let mut demux = | 710 | let mut demux = |
| 723 | ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); | 711 | ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); |
| 724 | let (index, params) = demux | 712 | let (index, params) = demux |
| @@ -738,7 +726,7 @@ fn real_clip_t8x8_bd_psnr() { | |||
| 738 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); | 726 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); |
| 739 | let mut sources: Vec<Planes> = Vec::new(); | 727 | let mut sources: Vec<Planes> = Vec::new(); |
| 740 | let mut seen = 0usize; | 728 | let mut seen = 0usize; |
| 741 | - while sources.len() < 30 { | 729 | + while sources.len() < want { |
| 742 | let Ok(packet) = demux.next_packet() else { | 730 | let Ok(packet) = demux.next_packet() else { |
| 743 | break; | 731 | break; |
| 744 | }; | 732 | }; |
| @@ -747,7 +735,7 @@ fn real_clip_t8x8_bd_psnr() { | |||
| 747 | } | 735 | } |
| 748 | dec.send_packet(&packet).expect("decode"); | 736 | dec.send_packet(&packet).expect("decode"); |
| 749 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { | 737 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 750 | - if sources.len() < 30 && seen % stride == 0 { | 738 | + if sources.len() < want && seen % stride == 0 { |
| 751 | sources.push(planes_of(&f)); | 739 | sources.push(planes_of(&f)); |
| 752 | } | 740 | } |
| 753 | seen += 1; | 741 | seen += 1; |
| @@ -766,6 +754,24 @@ fn real_clip_t8x8_bd_psnr() { | |||
| 766 | h, | 754 | h, |
| 767 | sources.len() | 755 | sources.len() |
| 768 | ); | 756 | ); |
| 757 | + (w, h, sources) | ||
| 758 | +} | ||
| 759 | + | ||
| 760 | +/// BD-PSNR of the opt-in `transform_8x8` flag against flag-off on one real | ||
| 761 | +/// clip from the library, full size, over a QP sweep: the number the synthetic | ||
| 762 | +/// gate above cannot give, because the synthetic clip is content the flag wins | ||
| 763 | +/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; | ||
| 764 | +/// asserts nothing, so a regressing clip fails a gate, not the test run. | ||
| 765 | +/// | ||
| 766 | +/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | ||
| 767 | +/// real_clip_t8x8_bd_psnr -- --ignored --nocapture | ||
| 768 | +#[test] | ||
| 769 | +#[ignore = "set EC_H264_CLIP to a media file of yours"] | ||
| 770 | +fn real_clip_t8x8_bd_psnr() { | ||
| 771 | + let Some(path) = std::env::var_os("EC_H264_CLIP") else { | ||
| 772 | + panic!("EC_H264_CLIP must name a media file"); | ||
| 773 | + }; | ||
| 774 | + let (w, h, sources) = clip_sources(&path, 30); | ||
| 769 | 775 | ||
| 770 | let run = |t8x8: bool, qp: i32| { | 776 | let run = |t8x8: bool, qp: i32| { |
| 771 | let mut cfg = EncoderConfig::new(w as u32, h as u32); | 777 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| @@ -807,3 +813,182 @@ fn real_clip_t8x8_bd_psnr() { | |||
| 807 | share * 100.0 | 813 | share * 100.0 |
| 808 | ); | 814 | ); |
| 809 | } | 815 | } |
| 816 | + | ||
| 817 | +// --------------------------------------------------------------------------- | ||
| 818 | +// The encoder's rate-quality distance from x264: the survey's rank-1 gap, | ||
| 819 | +// because until this test existed the repo could measure our decoder against | ||
| 820 | +// every reference and our encoder against nothing but itself. | ||
| 821 | +// --------------------------------------------------------------------------- | ||
| 822 | + | ||
| 823 | +/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measured | ||
| 824 | +/// -2.442 dB against x264 there on 2026-08-23 (352x288, 24 pictures, both at | ||
| 825 | +/// their own default effort: our `Preset::Fast`, x264's `-preset medium`). | ||
| 826 | +/// The floor is that number with room for platform noise, so the distance can | ||
| 827 | +/// shrink but not grow unnoticed; it is not a claim that -2.4 dB is fine. | ||
| 828 | +const BD_PSNR_VS_X264_FLOOR: f64 = -2.60; | ||
| 829 | + | ||
| 830 | +fn have_x264() -> bool { | ||
| 831 | + std::process::Command::new("ffmpeg") | ||
| 832 | + .args(["-v", "error", "-hide_banner", "-encoders"]) | ||
| 833 | + .output() | ||
| 834 | + .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) | ||
| 835 | +} | ||
| 836 | + | ||
| 837 | +/// Encode raw I420 pictures with x264 at constant QP, matched to what our | ||
| 838 | +/// encoder actually does: Main profile (CABAC, no 8x8 transform), one | ||
| 839 | +/// reference, no B pictures, the same GOP, and adaptive quantisation and psy | ||
| 840 | +/// off so both encoders spend bits by the same rule. Returns the Annex B | ||
| 841 | +/// stream. | ||
| 842 | +fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> { | ||
| 843 | + let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); | ||
| 844 | + std::fs::create_dir_all(&dir).ok()?; | ||
| 845 | + let raw = dir.join(format!("in-q{qp}.yuv")); | ||
| 846 | + let out = dir.join(format!("out-q{qp}.264")); | ||
| 847 | + let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); | ||
| 848 | + for (y, u, v) in sources { | ||
| 849 | + buf.extend_from_slice(y); | ||
| 850 | + buf.extend_from_slice(u); | ||
| 851 | + buf.extend_from_slice(v); | ||
| 852 | + } | ||
| 853 | + std::fs::write(&raw, &buf).ok()?; | ||
| 854 | + let status = std::process::Command::new("ffmpeg") | ||
| 855 | + .args(["-v", "error", "-y"]) | ||
| 856 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 857 | + .args(["-s", &format!("{w}x{h}"), "-r", "1"]) | ||
| 858 | + .arg("-i") | ||
| 859 | + .arg(&raw) | ||
| 860 | + .args(["-c:v", "libx264", "-preset", "medium"]) | ||
| 861 | + .args(["-profile:v", "main", "-qp", &qp.to_string()]) | ||
| 862 | + .args(["-g", "10", "-bf", "0", "-refs", "1"]) | ||
| 863 | + .args(["-x264-params", "scenecut=0:aq-mode=0:psy=0:8x8dct=0"]) | ||
| 864 | + .args(["-f", "h264"]) | ||
| 865 | + .arg(&out) | ||
| 866 | + .output() | ||
| 867 | + .ok()?; | ||
| 868 | + let _ = std::fs::remove_file(&raw); | ||
| 869 | + if !status.status.success() { | ||
| 870 | + eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); | ||
| 871 | + return None; | ||
| 872 | + } | ||
| 873 | + let stream = std::fs::read(&out).ok()?; | ||
| 874 | + let _ = std::fs::remove_file(&out); | ||
| 875 | + Some(stream) | ||
| 876 | +} | ||
| 877 | + | ||
| 878 | +/// BD-PSNR of our encoder against x264 at matched features over QP | ||
| 879 | +/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot | ||
| 880 | +/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure | ||
| 881 | +/// the same thing on real content. | ||
| 882 | +/// | ||
| 883 | +/// Both curves are (bits, luma PSNR against the same source pictures). Ours | ||
| 884 | +/// uses the encoder's own reconstruction; x264's stream is decoded back with | ||
| 885 | +/// ffmpeg, so its PSNR is measured on what a decoder would actually show. | ||
| 886 | +/// | ||
| 887 | +/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture | ||
| 888 | +/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | ||
| 889 | +/// bd_psnr_vs_x264 -- --nocapture | ||
| 890 | +#[test] | ||
| 891 | +fn bd_psnr_vs_x264() { | ||
| 892 | + if !have_ffmpeg() || !have_x264() { | ||
| 893 | + eprintln!( | ||
| 894 | + "SKIP bd_psnr_vs_x264: no ffmpeg with libx264 on PATH. \ | ||
| 895 | + Install one, then: cargo test --release -p ec-h264 --test encode \ | ||
| 896 | + bd_psnr_vs_x264 -- --nocapture" | ||
| 897 | + ); | ||
| 898 | + return; | ||
| 899 | + } | ||
| 900 | + let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { | ||
| 901 | + Some(path) => clip_sources(&path, 24), | ||
| 902 | + None => { | ||
| 903 | + let (w, h, frames) = (352, 288, 24); | ||
| 904 | + let mut clip = Clip::new(w, h); | ||
| 905 | + let mut sources = Vec::with_capacity(frames); | ||
| 906 | + for t in 0..frames { | ||
| 907 | + clip.render(t); | ||
| 908 | + sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); | ||
| 909 | + } | ||
| 910 | + eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); | ||
| 911 | + (w, h, sources) | ||
| 912 | + } | ||
| 913 | + }; | ||
| 914 | + | ||
| 915 | + let ours = |qp: i32| { | ||
| 916 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 917 | + cfg.qp = qp; | ||
| 918 | + cfg.gop_size = 10; | ||
| 919 | + cfg.cabac = true; | ||
| 920 | + cfg.framerate = 1.0; | ||
| 921 | + cfg.threads = 0; | ||
| 922 | + let mut enc = Encoder::new(cfg).expect("encoder"); | ||
| 923 | + let (mut stream, mut sum_recon) = (Vec::new(), 0.0); | ||
| 924 | + for (y, u, v) in &sources { | ||
| 925 | + let view = PictureView::i420(w as u32, h as u32, y, u, v); | ||
| 926 | + stream.extend_from_slice(&enc.encode(&view).expect("encode").au); | ||
| 927 | + sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); | ||
| 928 | + } | ||
| 929 | + // Measured the same way x264 is: on what a decoder shows, not on the | ||
| 930 | + // encoder's own reconstruction. The two are printed together because a | ||
| 931 | + // gap between them is a bug in one of the halves, not a rate-quality | ||
| 932 | + // result. | ||
| 933 | + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); | ||
| 934 | + assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); | ||
| 935 | + let sum: f64 = sources | ||
| 936 | + .iter() | ||
| 937 | + .zip(&decoded) | ||
| 938 | + .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 939 | + .sum(); | ||
| 940 | + let (decoded_psnr, recon_psnr) = ( | ||
| 941 | + sum / sources.len() as f64, | ||
| 942 | + sum_recon / sources.len() as f64, | ||
| 943 | + ); | ||
| 944 | + assert!( | ||
| 945 | + (decoded_psnr - recon_psnr).abs() < 0.05, | ||
| 946 | + "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ | ||
| 947 | + stream decodes to {decoded_psnr:.2} dB" | ||
| 948 | + ); | ||
| 949 | + ((stream.len() * 8) as f64, decoded_psnr) | ||
| 950 | + }; | ||
| 951 | + let x264 = |qp: i32| { | ||
| 952 | + let stream = x264_encode_qp(&sources, w, h, qp).expect("x264 encodes"); | ||
| 953 | + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); | ||
| 954 | + assert_eq!( | ||
| 955 | + decoded.len(), | ||
| 956 | + sources.len(), | ||
| 957 | + "x264 returned {} pictures for {} sources", | ||
| 958 | + decoded.len(), | ||
| 959 | + sources.len() | ||
| 960 | + ); | ||
| 961 | + let sum: f64 = sources | ||
| 962 | + .iter() | ||
| 963 | + .zip(&decoded) | ||
| 964 | + .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 965 | + .sum(); | ||
| 966 | + ((stream.len() * 8) as f64, sum / sources.len() as f64) | ||
| 967 | + }; | ||
| 968 | + | ||
| 969 | + let qps = [22, 26, 30, 34]; | ||
| 970 | + let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); | ||
| 971 | + let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); | ||
| 972 | + for (i, &qp) in qps.iter().enumerate() { | ||
| 973 | + let (ob, op) = mine[i]; | ||
| 974 | + let (xb, xp) = theirs[i]; | ||
| 975 | + eprintln!( | ||
| 976 | + "qp {qp}: ours {ob:.0} bits {op:.2} dB | x264 {xb:.0} bits {xp:.2} dB \ | ||
| 977 | + ({:+.1}% bits, {:+.2} dB)", | ||
| 978 | + (ob / xb - 1.0) * 100.0, | ||
| 979 | + op - xp | ||
| 980 | + ); | ||
| 981 | + } | ||
| 982 | + let bd = bd_psnr_delta(&mine, &theirs); | ||
| 983 | + eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); | ||
| 984 | + | ||
| 985 | + // The floor is calibrated on the synthetic clip; a clip of the user's is a | ||
| 986 | + // measurement, not a gate, because its content is not pinned. | ||
| 987 | + if std::env::var_os("EC_H264_CLIP").is_none() { | ||
| 988 | + assert!( | ||
| 989 | + bd > BD_PSNR_VS_X264_FLOOR, | ||
| 990 | + "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ | ||
| 991 | + {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" | ||
| 992 | + ); | ||
| 993 | + } | ||
| 994 | +} | ||