M13.4: av1enc key and inter frames, bit-exact with libdav1d
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
7f97c25c3e
commit
4130172bbe
@@ -0,0 +1,114 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use effectcraft_av1enc::{Encoder, EncoderConfig, Frame, Packet};
|
||||
|
||||
/// A synthetic 4:2:0 picture.
|
||||
pub struct Pic {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub y: Vec<u16>,
|
||||
pub u: Vec<u16>,
|
||||
pub v: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Pic {
|
||||
pub fn frame(&self) -> Frame<'_> {
|
||||
Frame { y: &self.y, u: &self.u, v: &self.v, y_stride: self.w, uv_stride: self.w.div_ceil(2) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth gradients with a soft blob, moved by (dx, dy) samples per frame index `t`, plus a
|
||||
/// textured rectangle that moves differently.
|
||||
pub fn synth(w: usize, h: usize, bd: u32, t: usize) -> Pic {
|
||||
let max = ((1u32 << bd) - 1) as f64;
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
let sample = |x: f64, y: f64| -> f64 {
|
||||
let fx = x - 2.0 * t as f64;
|
||||
let fy = y - 1.0 * t as f64;
|
||||
let base = 0.25 + 0.5 * (fx / 97.0).sin() * (fy / 61.0).cos() * 0.5 + 0.2 * ((fx + fy) / (w + h) as f64);
|
||||
let d = ((fx - w as f64 / 2.0).powi(2) + (fy - h as f64 / 2.0).powi(2)).sqrt();
|
||||
let blob = 0.3 * (-d * d / (2.0 * (w.min(h) as f64 / 5.0).powi(2))).exp();
|
||||
// a checkered patch moving right by 4 per frame
|
||||
let px = x - 4.0 * t as f64 - w as f64 / 4.0;
|
||||
let py = y - h as f64 / 3.0;
|
||||
let patch =
|
||||
if (0.0..24.0).contains(&px) && (0.0..16.0).contains(&py) { if ((px as i32 / 4) + (py as i32 / 4)) % 2 == 0 { 0.25 } else { -0.25 } } else { 0.0 };
|
||||
(base + blob + patch).clamp(0.0, 1.0)
|
||||
};
|
||||
let mut y = vec![0u16; w * h];
|
||||
for j in 0..h {
|
||||
for i in 0..w {
|
||||
y[j * w + i] = (sample(i as f64, j as f64) * max).round() as u16;
|
||||
}
|
||||
}
|
||||
let mut u = vec![0u16; cw * ch];
|
||||
let mut v = vec![0u16; cw * ch];
|
||||
for j in 0..ch {
|
||||
for i in 0..cw {
|
||||
let s = sample(2.0 * i as f64, 2.0 * j as f64);
|
||||
u[j * cw + i] = ((0.5 + 0.3 * (s - 0.5) + 0.1 * (i as f64 / 13.0).sin()) * max).round() as u16;
|
||||
v[j * cw + i] = ((0.5 - 0.25 * (s - 0.5) + 0.1 * (j as f64 / 7.0).cos()) * max).round() as u16;
|
||||
}
|
||||
}
|
||||
Pic { w, h, y, u, v }
|
||||
}
|
||||
|
||||
/// Deterministic noise picture (hard case for prediction).
|
||||
pub fn noise(w: usize, h: usize, bd: u32, seed: u32) -> Pic {
|
||||
let mut s = seed.wrapping_mul(2_654_435_761).max(1);
|
||||
let mut rnd = || {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
s
|
||||
};
|
||||
let mask = (1u32 << bd) - 1;
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
Pic {
|
||||
w,
|
||||
h,
|
||||
y: (0..w * h).map(|_| (rnd() & mask) as u16).collect(),
|
||||
u: (0..cw * ch).map(|_| (rnd() & mask) as u16).collect(),
|
||||
v: (0..cw * ch).map(|_| (rnd() & mask) as u16).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn psnr(a: &[u16], b: &[u16], bd: u32) -> f64 {
|
||||
let max = ((1u32 << bd) - 1) as f64;
|
||||
let mse = a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).powi(2)).sum::<f64>() / a.len() as f64;
|
||||
if mse == 0.0 { 99.0 } else { 10.0 * (max * max / mse).log10() }
|
||||
}
|
||||
|
||||
pub struct Run {
|
||||
pub packets: Vec<Packet>,
|
||||
pub recons: Vec<[Vec<u16>; 3]>,
|
||||
pub psnr_y: Vec<f64>,
|
||||
}
|
||||
|
||||
/// Encodes `pics`, checks every packet decodes (filmcraft-av1) to exactly the encoder's
|
||||
/// reconstruction and returns packets, reconstructions and luma PSNRs.
|
||||
pub fn encode_and_check(cfg: EncoderConfig, pics: &[Pic]) -> Run {
|
||||
let bd = cfg.bit_depth as u32;
|
||||
let mut enc = Encoder::new(cfg).expect("config");
|
||||
let mut dec = filmcraft_av1::Decoder::new();
|
||||
let mut run = Run { packets: Vec::new(), recons: Vec::new(), psnr_y: Vec::new() };
|
||||
for (i, p) in pics.iter().enumerate() {
|
||||
let pkt = enc.encode(&p.frame());
|
||||
let rec = enc.last_reconstruction().expect("reconstruction");
|
||||
let out = dec.decode(&pkt.data).unwrap_or_else(|e| panic!("frame {i}: decode error {e:?}"));
|
||||
assert_eq!(out.len(), 1, "frame {i}: one picture per packet");
|
||||
let d = &out[0];
|
||||
assert_eq!((d.width as usize, d.height as usize), (p.w, p.h));
|
||||
for pl in 0..3 {
|
||||
if d.planes[pl] != rec[pl] {
|
||||
let first = d.planes[pl].iter().zip(&rec[pl]).position(|(a, b)| a != b).unwrap_or(usize::MAX);
|
||||
let pw = if pl == 0 { p.w } else { p.w.div_ceil(2) };
|
||||
panic!("frame {i} plane {pl}: decoder output differs from the reconstruction (first at x {} y {})", first % pw, first / pw);
|
||||
}
|
||||
}
|
||||
run.psnr_y.push(psnr(&p.y, &rec[0], bd));
|
||||
run.recons.push(rec);
|
||||
run.packets.push(pkt);
|
||||
}
|
||||
run
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! External oracle: streams decoded by ffmpeg's libdav1d must equal the encoder's reconstruction
|
||||
//! bit for bit. Skipped when `ffmpeg` (with libdav1d) is not installed. ffmpeg's native `av1`
|
||||
//! decoder only drives hardware decoders, so it is not used.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use common::*;
|
||||
use effectcraft_av1enc::{Encoder, EncoderConfig, Packet, RateControl};
|
||||
|
||||
fn have_libdav1d() -> bool {
|
||||
let Ok(out) = Command::new("ffmpeg").args(["-hide_banner", "-decoders"]).output() else {
|
||||
eprintln!("ffmpeg not found: skipping the external oracle");
|
||||
return false;
|
||||
};
|
||||
let ok = out.status.success() && String::from_utf8_lossy(&out.stdout).contains("libdav1d");
|
||||
if !ok {
|
||||
eprintln!("ffmpeg without libdav1d: skipping the external oracle");
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// IVF container with one temporal unit (temporal delimiter + packet) per frame.
|
||||
fn ivf(w: usize, h: usize, packets: &[Packet]) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(b"DKIF");
|
||||
v.extend_from_slice(&0u16.to_le_bytes());
|
||||
v.extend_from_slice(&32u16.to_le_bytes());
|
||||
v.extend_from_slice(b"AV01");
|
||||
v.extend_from_slice(&(w as u16).to_le_bytes());
|
||||
v.extend_from_slice(&(h as u16).to_le_bytes());
|
||||
v.extend_from_slice(&30u32.to_le_bytes());
|
||||
v.extend_from_slice(&1u32.to_le_bytes());
|
||||
v.extend_from_slice(&(packets.len() as u32).to_le_bytes());
|
||||
v.extend_from_slice(&0u32.to_le_bytes());
|
||||
for (i, p) in packets.iter().enumerate() {
|
||||
v.extend_from_slice(&((p.data.len() + 2) as u32).to_le_bytes());
|
||||
v.extend_from_slice(&(i as u64).to_le_bytes());
|
||||
v.extend_from_slice(&[0x12, 0x00]); // OBU_TEMPORAL_DELIMITER
|
||||
v.extend_from_slice(&p.data);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Encodes `pics`, decodes the IVF stream with `ffmpeg -c:v libdav1d` and compares every
|
||||
/// decoded frame with the encoder's reconstruction.
|
||||
fn check(name: &str, cfg: EncoderConfig, pics: &[Pic]) {
|
||||
let (w, h, bd) = (cfg.width as usize, cfg.height as usize, cfg.bit_depth);
|
||||
let mut enc = Encoder::new(cfg).expect("config");
|
||||
let mut packets = Vec::new();
|
||||
let mut recons = Vec::new();
|
||||
for p in pics {
|
||||
packets.push(enc.encode(&p.frame()));
|
||||
recons.push(enc.last_reconstruction().expect("reconstruction"));
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("effectcraft-av1enc-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let input = dir.join("in.ivf");
|
||||
let output = dir.join("out.yuv");
|
||||
std::fs::write(&input, ivf(w, h, &packets)).expect("write ivf");
|
||||
let pix_fmt = if bd == 8 { "yuv420p" } else { "yuv420p10le" };
|
||||
let res = Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-y", "-c:v", "libdav1d", "-i"])
|
||||
.arg(&input)
|
||||
.args(["-f", "rawvideo", "-pix_fmt", pix_fmt])
|
||||
.arg(&output)
|
||||
.output()
|
||||
.expect("run ffmpeg");
|
||||
let stderr = String::from_utf8_lossy(&res.stderr);
|
||||
assert!(res.status.success() && stderr.trim().is_empty(), "{name}: ffmpeg -c:v libdav1d failed: {stderr}");
|
||||
let raw = std::fs::read(&output).expect("decoded yuv");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let samples: Vec<u16> =
|
||||
if bd == 8 { raw.iter().map(|&b| b as u16).collect() } else { raw.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect() };
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
let fsize = w * h + 2 * cw * ch;
|
||||
assert_eq!(samples.len(), fsize * pics.len(), "{name}: decoded frame count");
|
||||
for (i, rec) in recons.iter().enumerate() {
|
||||
let f = &samples[i * fsize..(i + 1) * fsize];
|
||||
let planes = [&f[..w * h], &f[w * h..w * h + cw * ch], &f[w * h + cw * ch..]];
|
||||
for p in 0..3 {
|
||||
if planes[p] != &rec[p][..] {
|
||||
let pw = if p == 0 { w } else { cw };
|
||||
let k = planes[p].iter().zip(&rec[p]).position(|(a, b)| a != b).unwrap_or(0);
|
||||
panic!("{name}: frame {i} plane {p} differs from the reconstruction at ({}, {})", k % pw, k / pw);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("{name}: libdav1d bit-exact over {} frames ({} bytes)", pics.len(), packets.iter().map(|p| p.data.len()).sum::<usize>());
|
||||
}
|
||||
|
||||
fn cfg(w: usize, h: usize, bd: u8, rate: RateControl, keyint: u32) -> EncoderConfig {
|
||||
let mut c = EncoderConfig::new(w as u32, h as u32, 30, 1);
|
||||
c.bit_depth = bd;
|
||||
c.rate = rate;
|
||||
c.keyint = keyint;
|
||||
c
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libdav1d_decodes_bit_exact() {
|
||||
if !have_libdav1d() {
|
||||
return;
|
||||
}
|
||||
// a moving pattern with inter frames
|
||||
let pics: Vec<Pic> = (0..8).map(|t| synth(176, 144, 8, t)).collect();
|
||||
check("inter8", cfg(176, 144, 8, RateControl::ConstantQ(90), 5), &pics);
|
||||
// all-intra at a fine quantizer (large coefficients, Golomb codes)
|
||||
let pics: Vec<Pic> = (0..2).map(|t| noise(64, 48, 8, t as u32 + 3)).collect();
|
||||
check("noise-intra", cfg(64, 48, 8, RateControl::ConstantQ(4), 1), &pics);
|
||||
// odd sizes, 8 and 10 bit
|
||||
let pics: Vec<Pic> = (0..4).map(|t| synth(33, 17, 8, t)).collect();
|
||||
check("odd8", cfg(33, 17, 8, RateControl::ConstantQ(60), 3), &pics);
|
||||
let pics: Vec<Pic> = (0..5).map(|t| synth(101, 75, 10, t)).collect();
|
||||
check("odd10", cfg(101, 75, 10, RateControl::ConstantQ(110), 4), &pics);
|
||||
// a noisy moving picture, bitrate mode
|
||||
let pics: Vec<Pic> = (0..6).map(|t| noisy(128, 80, t)).collect();
|
||||
check("bitrate", cfg(128, 80, 8, RateControl::Bitrate { kbps: 300 }, 10), &pics);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libdav1d_decodes_1080p() {
|
||||
if !have_libdav1d() {
|
||||
return;
|
||||
}
|
||||
let pics: Vec<Pic> = (0..3).map(|t| noisy(1920, 1080, t)).collect();
|
||||
check("1080p", cfg(1920, 1080, 8, RateControl::ConstantQ(120), 30), &pics);
|
||||
}
|
||||
|
||||
fn noisy(w: usize, h: usize, t: usize) -> Pic {
|
||||
let mut p = synth(w, h, 8, t);
|
||||
let n = noise(w, h, 8, 7 + t as u32);
|
||||
for (a, b) in p.y.iter_mut().zip(&n.y) {
|
||||
*a = (*a as i32 + (*b as i32 - 128) / 16).clamp(0, 255) as u16;
|
||||
}
|
||||
p
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Round trips through FilmCraft's spec-derived AV1 decoder: decoded frames must equal the
|
||||
//! encoder's own reconstruction bit for bit.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::*;
|
||||
use effectcraft_av1enc::{EncoderConfig, RateControl};
|
||||
|
||||
fn cfg(w: u32, h: u32, bd: u8, q: u8, keyint: u32) -> EncoderConfig {
|
||||
let mut c = EncoderConfig::new(w, h, 30, 1);
|
||||
c.bit_depth = bd;
|
||||
c.rate = RateControl::ConstantQ(q);
|
||||
c.keyint = keyint;
|
||||
c
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intra_8bit_smooth_high_quality() {
|
||||
let pics = vec![synth(128, 96, 8, 0)];
|
||||
let run = encode_and_check(cfg(128, 96, 8, 40, 1), &pics);
|
||||
eprintln!("intra 8-bit q40: {} bytes, PSNR-Y {:.2} dB", run.packets[0].data.len(), run.psnr_y[0]);
|
||||
assert!(run.packets[0].keyframe);
|
||||
assert!(run.psnr_y[0] > 35.0, "PSNR {:.2}", run.psnr_y[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_sizes_all_intra() {
|
||||
for (w, h) in [(33, 17), (1, 1), (7, 9), (65, 63), (100, 30)] {
|
||||
let pics: Vec<Pic> = (0..2).map(|t| synth(w, h, 8, t)).collect();
|
||||
let run = encode_and_check(cfg(w as u32, h as u32, 8, 90, 1), &pics);
|
||||
assert!(run.packets.iter().all(|p| p.keyframe));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_low_q_exact() {
|
||||
let pics = vec![noise(72, 40, 8, 1)];
|
||||
let run = encode_and_check(cfg(72, 40, 8, 1, 1), &pics);
|
||||
assert!(run.psnr_y[0] > 40.0, "PSNR {:.2}", run.psnr_y[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inter_moving_pattern() {
|
||||
let pics: Vec<Pic> = (0..6).map(|t| synth(160, 112, 8, t)).collect();
|
||||
let run = encode_and_check(cfg(160, 112, 8, 80, 30), &pics);
|
||||
let sizes: Vec<usize> = run.packets.iter().map(|p| p.data.len()).collect();
|
||||
eprintln!("inter sizes {sizes:?} psnr {:?}", run.psnr_y);
|
||||
assert!(run.packets[0].keyframe && run.packets[1..].iter().all(|p| !p.keyframe));
|
||||
let inter_avg = sizes[1..].iter().sum::<usize>() as f64 / (sizes.len() - 1) as f64;
|
||||
assert!(inter_avg < sizes[0] as f64 * 0.5, "inter frames {inter_avg} vs key {}", sizes[0]);
|
||||
assert!(run.psnr_y.iter().all(|&p| p > 33.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_bit_inter() {
|
||||
let pics: Vec<Pic> = (0..4).map(|t| synth(96, 72, 10, t)).collect();
|
||||
let run = encode_and_check(cfg(96, 72, 10, 60, 3), &pics);
|
||||
eprintln!("10-bit psnr {:?}", run.psnr_y);
|
||||
assert!(run.psnr_y.iter().all(|&p| p > 35.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_size_inter() {
|
||||
let pics: Vec<Pic> = (0..5).map(|t| synth(57, 43, 8, t)).collect();
|
||||
encode_and_check(cfg(57, 43, 8, 120, 10), &pics);
|
||||
let pics: Vec<Pic> = (0..3).map(|t| synth(33, 17, 10, t)).collect();
|
||||
encode_and_check(cfg(33, 17, 10, 120, 10), &pics);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrate_mode_tracks_target() {
|
||||
let n = 12;
|
||||
let pics: Vec<Pic> = (0..n).map(|t| synth(192, 128, 8, t)).collect();
|
||||
let mut c = cfg(192, 128, 8, 0, 12);
|
||||
c.rate = RateControl::Bitrate { kbps: 400 };
|
||||
let run = encode_and_check(c, &pics);
|
||||
let bits: usize = run.packets.iter().map(|p| p.data.len() * 8).sum();
|
||||
let kbps = bits as f64 / (n as f64 / 30.0) / 1000.0;
|
||||
eprintln!("bitrate mode: {kbps:.1} kbit/s for a 400 kbit/s target, psnr {:?}", run.psnr_y);
|
||||
assert!(kbps > 400.0 / 2.0 && kbps < 400.0 * 2.0, "{kbps} kbit/s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers() {
|
||||
let enc = effectcraft_av1enc::Encoder::new(cfg(1920, 1080, 10, 100, 60)).unwrap();
|
||||
let c = enc.av1c();
|
||||
assert_eq!(c[0], 0x81);
|
||||
assert_eq!(c[1] & 0x1f, 8, "1080p30 is level 4.0");
|
||||
assert_eq!(c[2], 0b0100_1100);
|
||||
assert_eq!(&c[4..], &enc.sequence_header_obu()[..]);
|
||||
assert_eq!(enc.sequence_header_obu()[0], 0x0A);
|
||||
}
|
||||
Reference in New Issue
Block a user