Encoder conformance against both decoders and the library
Browse files at this commit2fb37fbc8cb6dd3f86c03b4bf8b7cc361a746167Parent: 6d22228- test
- encoder conformance against both decoders and the library
1 changed file +528 -0
- crates/ec-h264/tests/encode.rs +528 -0
crates/ec-h264/tests/encode.rsadded+528 -0
| @@ -0,0 +1,528 @@ | ||
| 1 | +//! Encoder conformance: what this encoder writes is what this decoder — and, | |
| 2 | +//! in the ffmpeg-driven half of the suite, what ffmpeg — reconstructs. | |
| 3 | +//! | |
| 4 | +//! The load-bearing property is that the encoder's own reconstruction is | |
| 5 | +//! *bit-identical* to a decode of its bitstream. Both sides share the | |
| 6 | +//! prediction, transform and deblocking code, so a mismatch means the syntax | |
| 7 | +//! written does not describe the picture reconstructed, which is the one class | |
| 8 | +//! of encoder bug that quality metrics cannot see. | |
| 9 | + | |
| 10 | +use ec_h264::{Decoder, Encoder, EncoderConfig, NalOutcome, OutputOrder, PictureView, Preset}; | |
| 11 | + | |
| 12 | +/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. | |
| 13 | +type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); | |
| 14 | + | |
| 15 | +/// A synthetic source with real structure: moving edges, a gradient and a | |
| 16 | +/// noisy patch, so intra, inter and skip all get exercised. | |
| 17 | +struct Clip { | |
| 18 | + w: usize, | |
| 19 | + h: usize, | |
| 20 | + y: Vec<u8>, | |
| 21 | + u: Vec<u8>, | |
| 22 | + v: Vec<u8>, | |
| 23 | +} | |
| 24 | + | |
| 25 | +impl Clip { | |
| 26 | + fn new(w: usize, h: usize) -> Clip { | |
| 27 | + Clip { | |
| 28 | + w, | |
| 29 | + h, | |
| 30 | + y: vec![0; w * h], | |
| 31 | + u: vec![0; w / 2 * h / 2], | |
| 32 | + v: vec![0; w / 2 * h / 2], | |
| 33 | + } | |
| 34 | + } | |
| 35 | + | |
| 36 | + /// Frame `t`: a diagonal gradient, a moving box and a deterministic noise | |
| 37 | + /// field that keeps the residual from vanishing. | |
| 38 | + fn render(&mut self, t: usize) { | |
| 39 | + let (w, h) = (self.w, self.h); | |
| 40 | + for y in 0..h { | |
| 41 | + for x in 0..w { | |
| 42 | + let grad = ((x + y * 2 + t * 3) % 256) as u8; | |
| 43 | + let noise = ((x * 37 + y * 17 + t * 11) % 23) as u8; | |
| 44 | + let box_x = (t * 5) % (w.saturating_sub(40).max(1)); | |
| 45 | + let inside = x >= box_x && x < box_x + 40 && y >= h / 4 && y < h / 4 + 30; | |
| 46 | + self.y[y * w + x] = if inside { | |
| 47 | + 200u8.saturating_sub(noise) | |
| 48 | + } else { | |
| 49 | + grad / 2 + noise | |
| 50 | + }; | |
| 51 | + } | |
| 52 | + } | |
| 53 | + for y in 0..h / 2 { | |
| 54 | + for x in 0..w / 2 { | |
| 55 | + self.u[y * (w / 2) + x] = (100 + ((x + t) % 40)) as u8; | |
| 56 | + self.v[y * (w / 2) + x] = (140 + ((y + t * 2) % 30)) as u8; | |
| 57 | + } | |
| 58 | + } | |
| 59 | + } | |
| 60 | + | |
| 61 | + fn view(&self) -> PictureView<'_> { | |
| 62 | + PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// Decode a whole stream with this crate's decoder, returning one I420 triple | |
| 67 | +/// per picture. | |
| 68 | +fn decode_all(stream: &[u8]) -> Vec<Planes> { | |
| 69 | + let mut dec = Decoder::new(); | |
| 70 | + dec.set_output_order(OutputOrder::Decode); | |
| 71 | + let mut out = Vec::new(); | |
| 72 | + for nal in ec_h264_syntax::AnnexBIter::new(stream) { | |
| 73 | + if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { | |
| 74 | + dec.end_picture().expect("end of picture"); | |
| 75 | + dec.push_nal(nal).expect("decoder accepts the NAL"); | |
| 76 | + } | |
| 77 | + while let Some(frame) = dec.next_frame() { | |
| 78 | + out.push(planes_of(&frame)); | |
| 79 | + } | |
| 80 | + } | |
| 81 | + dec.flush().expect("flush"); | |
| 82 | + while let Some(frame) = dec.next_frame() { | |
| 83 | + out.push(planes_of(&frame)); | |
| 84 | + } | |
| 85 | + out | |
| 86 | +} | |
| 87 | + | |
| 88 | +fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { | |
| 89 | + let (w, h) = (frame.width as usize, frame.height as usize); | |
| 90 | + let mut planes = Vec::new(); | |
| 91 | + for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] | |
| 92 | + .into_iter() | |
| 93 | + .enumerate() | |
| 94 | + { | |
| 95 | + let plane = &frame.planes[i]; | |
| 96 | + let mut out = Vec::with_capacity(pw * ph); | |
| 97 | + for row in 0..ph { | |
| 98 | + out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | |
| 99 | + } | |
| 100 | + planes.push(out); | |
| 101 | + } | |
| 102 | + let v = planes.pop().unwrap(); | |
| 103 | + let u = planes.pop().unwrap(); | |
| 104 | + let y = planes.pop().unwrap(); | |
| 105 | + (y, u, v) | |
| 106 | +} | |
| 107 | + | |
| 108 | +fn psnr(a: &[u8], b: &[u8]) -> f64 { | |
| 109 | + let mse: f64 = a | |
| 110 | + .iter() | |
| 111 | + .zip(b) | |
| 112 | + .map(|(&x, &y)| { | |
| 113 | + let d = f64::from(x) - f64::from(y); | |
| 114 | + d * d | |
| 115 | + }) | |
| 116 | + .sum::<f64>() | |
| 117 | + / a.len() as f64; | |
| 118 | + if mse == 0.0 { | |
| 119 | + 99.0 | |
| 120 | + } else { | |
| 121 | + 10.0 * (255.0 * 255.0 / mse).log10() | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +/// The encoder's reconstruction and a decode of its bitstream agree sample for | |
| 126 | +/// sample, over a QP sweep, both presets, single and multi threaded. | |
| 127 | +#[test] | |
| 128 | +fn reconstruction_matches_the_decoder() { | |
| 129 | + for (w, h) in [(176, 144), (208, 122), (64, 48)] { | |
| 130 | + let mut clip = Clip::new(w, h); | |
| 131 | + for qp in [12, 24, 33, 44] { | |
| 132 | + for (threads, preset) in [(1usize, Preset::Fast), (4, Preset::Balanced)] { | |
| 133 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 134 | + cfg.qp = qp; | |
| 135 | + cfg.gop_size = 5; | |
| 136 | + cfg.threads = threads; | |
| 137 | + cfg.preset = preset; | |
| 138 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 139 | + let mut stream = Vec::new(); | |
| 140 | + let mut recons = Vec::new(); | |
| 141 | + for t in 0..8 { | |
| 142 | + clip.render(t); | |
| 143 | + let picture = enc.encode(&clip.view()).expect("encode"); | |
| 144 | + stream.extend_from_slice(&picture.au); | |
| 145 | + recons.push(enc.reconstruction().expect("a reconstruction")); | |
| 146 | + } | |
| 147 | + let decoded = decode_all(&stream); | |
| 148 | + assert_eq!( | |
| 149 | + decoded.len(), | |
| 150 | + recons.len(), | |
| 151 | + "{w}x{h} qp {qp}: picture count" | |
| 152 | + ); | |
| 153 | + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { | |
| 154 | + assert_eq!( | |
| 155 | + dec.0, rec.0, | |
| 156 | + "{w}x{h} qp {qp} t{threads}: luma of picture {i}" | |
| 157 | + ); | |
| 158 | + assert_eq!( | |
| 159 | + dec.1, rec.1, | |
| 160 | + "{w}x{h} qp {qp} t{threads}: Cb of picture {i}" | |
| 161 | + ); | |
| 162 | + assert_eq!( | |
| 163 | + dec.2, rec.2, | |
| 164 | + "{w}x{h} qp {qp} t{threads}: Cr of picture {i}" | |
| 165 | + ); | |
| 166 | + } | |
| 167 | + } | |
| 168 | + } | |
| 169 | + } | |
| 170 | +} | |
| 171 | + | |
| 172 | +/// Quality tracks the quantiser, and a low QP is close to lossless: a stream | |
| 173 | +/// that decodes bit-exactly could still be encoding garbage, and this is what | |
| 174 | +/// says it is not. | |
| 175 | +#[test] | |
| 176 | +fn quality_follows_the_quantiser() { | |
| 177 | + let (w, h) = (176, 144); | |
| 178 | + let mut clip = Clip::new(w, h); | |
| 179 | + let mut last = 0.0; | |
| 180 | + for qp in [40, 30, 20, 10] { | |
| 181 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 182 | + cfg.qp = qp; | |
| 183 | + cfg.gop_size = 4; | |
| 184 | + cfg.threads = 1; | |
| 185 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 186 | + let mut total = 0.0; | |
| 187 | + for t in 0..6 { | |
| 188 | + clip.render(t); | |
| 189 | + enc.encode(&clip.view()).expect("encode"); | |
| 190 | + let (y, _, _) = enc.reconstruction().unwrap(); | |
| 191 | + total += psnr(&clip.y, &y); | |
| 192 | + } | |
| 193 | + let avg = total / 6.0; | |
| 194 | + assert!( | |
| 195 | + avg > last, | |
| 196 | + "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}" | |
| 197 | + ); | |
| 198 | + if qp == 10 { | |
| 199 | + assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}"); | |
| 200 | + } | |
| 201 | + last = avg; | |
| 202 | + } | |
| 203 | +} | |
| 204 | + | |
| 205 | +/// Constant bitrate lands within a quarter of the target over a short clip, | |
| 206 | +/// and every GOP boundary is an IDR the decoder can start from. | |
| 207 | +#[test] | |
| 208 | +fn rate_control_hits_its_target() { | |
| 209 | + let (w, h) = (352, 288); | |
| 210 | + let mut clip = Clip::new(w, h); | |
| 211 | + let bitrate = 1_500_000u32; | |
| 212 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 213 | + cfg.bitrate = bitrate; | |
| 214 | + cfg.framerate = 25.0; | |
| 215 | + cfg.gop_size = 25; | |
| 216 | + cfg.threads = 2; | |
| 217 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 218 | + let mut bits = 0u64; | |
| 219 | + let frames = 50; | |
| 220 | + let mut keys = 0; | |
| 221 | + for t in 0..frames { | |
| 222 | + clip.render(t); | |
| 223 | + let p = enc.encode(&clip.view()).expect("encode"); | |
| 224 | + bits += p.au.len() as u64 * 8; | |
| 225 | + keys += u32::from(p.key_frame); | |
| 226 | + } | |
| 227 | + assert_eq!(keys, 2, "one IDR per GOP"); | |
| 228 | + let actual = bits as f64 / (frames as f64 / 25.0); | |
| 229 | + let ratio = actual / f64::from(bitrate); | |
| 230 | + assert!( | |
| 231 | + (0.7..1.35).contains(&ratio), | |
| 232 | + "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})" | |
| 233 | + ); | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// Every picture of a `gop_size` 1 stream is an IDR, which is what an | |
| 237 | +/// intraframe master asks for. | |
| 238 | +#[test] | |
| 239 | +fn all_intra_when_the_gop_is_one() { | |
| 240 | + let (w, h) = (64, 64); | |
| 241 | + let mut clip = Clip::new(w, h); | |
| 242 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 243 | + cfg.gop_size = 1; | |
| 244 | + cfg.qp = 26; | |
| 245 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 246 | + let mut stream = Vec::new(); | |
| 247 | + for t in 0..4 { | |
| 248 | + clip.render(t); | |
| 249 | + let p = enc.encode(&clip.view()).expect("encode"); | |
| 250 | + assert!(p.key_frame, "picture {t} is not a key frame"); | |
| 251 | + stream.extend_from_slice(&p.au); | |
| 252 | + } | |
| 253 | + assert_eq!(decode_all(&stream).len(), 4); | |
| 254 | +} | |
| 255 | + | |
| 256 | +// --------------------------------------------------------------------------- | |
| 257 | +// ffmpeg-driven half: the third-party oracle. Skipped loudly when ffmpeg is | |
| 258 | +// absent, exactly like the conformance suite's ffmpeg cross-check. | |
| 259 | +// --------------------------------------------------------------------------- | |
| 260 | + | |
| 261 | +fn have_ffmpeg() -> bool { | |
| 262 | + std::process::Command::new("ffmpeg") | |
| 263 | + .arg("-version") | |
| 264 | + .stdout(std::process::Stdio::null()) | |
| 265 | + .stderr(std::process::Stdio::null()) | |
| 266 | + .status() | |
| 267 | + .is_ok_and(|s| s.success()) | |
| 268 | +} | |
| 269 | + | |
| 270 | +/// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. | |
| 271 | +fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { | |
| 272 | + let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id())); | |
| 273 | + std::fs::create_dir_all(&dir).ok()?; | |
| 274 | + let path = dir.join(format!("s{}.264", stream.len())); | |
| 275 | + std::fs::write(&path, stream).ok()?; | |
| 276 | + let mut cmd = std::process::Command::new("ffmpeg"); | |
| 277 | + cmd.args(["-v", "error"]); | |
| 278 | + cmd.args(extra); | |
| 279 | + cmd.arg("-i").arg(&path); | |
| 280 | + cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]); | |
| 281 | + let out = cmd.output().ok()?; | |
| 282 | + let _ = std::fs::remove_file(&path); | |
| 283 | + if !out.status.success() { | |
| 284 | + eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); | |
| 285 | + return None; | |
| 286 | + } | |
| 287 | + let frame = w * h * 3 / 2; | |
| 288 | + if frame == 0 || out.stdout.len() % frame != 0 { | |
| 289 | + eprintln!( | |
| 290 | + "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", | |
| 291 | + out.stdout.len() | |
| 292 | + ); | |
| 293 | + return None; | |
| 294 | + } | |
| 295 | + Some( | |
| 296 | + out.stdout | |
| 297 | + .chunks(frame) | |
| 298 | + .map(|f| { | |
| 299 | + let (y, rest) = f.split_at(w * h); | |
| 300 | + let (u, v) = rest.split_at(w / 2 * h / 2); | |
| 301 | + (y.to_vec(), u.to_vec(), v.to_vec()) | |
| 302 | + }) | |
| 303 | + .collect(), | |
| 304 | + ) | |
| 305 | +} | |
| 306 | + | |
| 307 | +/// Encode a clip and hand back the stream with the encoder's reconstructions. | |
| 308 | +fn encode_clip( | |
| 309 | + w: usize, | |
| 310 | + h: usize, | |
| 311 | + frames: usize, | |
| 312 | + configure: impl FnOnce(&mut EncoderConfig), | |
| 313 | +) -> (Vec<u8>, Vec<Planes>) { | |
| 314 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 315 | + cfg.gop_size = 10; | |
| 316 | + cfg.threads = 3; | |
| 317 | + configure(&mut cfg); | |
| 318 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 319 | + let mut clip = Clip::new(w, h); | |
| 320 | + let mut stream = Vec::new(); | |
| 321 | + let mut recons = Vec::new(); | |
| 322 | + for t in 0..frames { | |
| 323 | + clip.render(t); | |
| 324 | + stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); | |
| 325 | + recons.push(enc.reconstruction().expect("reconstruction")); | |
| 326 | + } | |
| 327 | + (stream, recons) | |
| 328 | +} | |
| 329 | + | |
| 330 | +/// ffmpeg's decode of our stream is our reconstruction, sample for sample, | |
| 331 | +/// across a QP sweep and at a size that is not a multiple of a macroblock. | |
| 332 | +#[test] | |
| 333 | +fn ffmpeg_decodes_bit_exactly() { | |
| 334 | + if !have_ffmpeg() { | |
| 335 | + eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH"); | |
| 336 | + return; | |
| 337 | + } | |
| 338 | + for (w, h) in [(176, 144), (322, 242)] { | |
| 339 | + for qp in [10, 20, 28, 37, 47] { | |
| 340 | + let (stream, recons) = encode_clip(w, h, 6, |cfg| { | |
| 341 | + cfg.qp = qp; | |
| 342 | + }); | |
| 343 | + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); | |
| 344 | + assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count"); | |
| 345 | + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { | |
| 346 | + assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}"); | |
| 347 | + assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}"); | |
| 348 | + assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}"); | |
| 349 | + } | |
| 350 | + } | |
| 351 | + } | |
| 352 | +} | |
| 353 | + | |
| 354 | +/// The same stream under constant bitrate, which is the mode edith exports in. | |
| 355 | +#[test] | |
| 356 | +fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { | |
| 357 | + if !have_ffmpeg() { | |
| 358 | + eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH"); | |
| 359 | + return; | |
| 360 | + } | |
| 361 | + let (w, h) = (352, 288); | |
| 362 | + let (stream, recons) = encode_clip(w, h, 12, |cfg| { | |
| 363 | + cfg.bitrate = 2_000_000; | |
| 364 | + cfg.framerate = 25.0; | |
| 365 | + }); | |
| 366 | + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); | |
| 367 | + assert_eq!(decoded.len(), recons.len()); | |
| 368 | + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { | |
| 369 | + assert_eq!(dec.0, rec.0, "luma of frame {i}"); | |
| 370 | + assert_eq!( | |
| 371 | + (dec.1.clone(), dec.2.clone()), | |
| 372 | + (rec.1.clone(), rec.2.clone()), | |
| 373 | + "chroma of frame {i}" | |
| 374 | + ); | |
| 375 | + } | |
| 376 | +} | |
| 377 | + | |
| 378 | +/// The VA-API hardware decoder on this machine accepts the same stream: a | |
| 379 | +/// bitstream a driver refuses is not a bitstream edith can ship, whatever a | |
| 380 | +/// software decoder says about it. | |
| 381 | +#[test] | |
| 382 | +fn vaapi_decodes_our_stream() { | |
| 383 | + if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() { | |
| 384 | + eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node"); | |
| 385 | + return; | |
| 386 | + } | |
| 387 | + let (w, h) = (352, 288); | |
| 388 | + let (stream, recons) = encode_clip(w, h, 6, |cfg| { | |
| 389 | + cfg.qp = 26; | |
| 390 | + }); | |
| 391 | + let Some(decoded) = ffmpeg_decode( | |
| 392 | + &stream, | |
| 393 | + w, | |
| 394 | + h, | |
| 395 | + &[ | |
| 396 | + "-hwaccel", | |
| 397 | + "vaapi", | |
| 398 | + "-hwaccel_device", | |
| 399 | + "/dev/dri/renderD128", | |
| 400 | + ], | |
| 401 | + ) else { | |
| 402 | + eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here"); | |
| 403 | + return; | |
| 404 | + }; | |
| 405 | + assert_eq!(decoded.len(), recons.len(), "VA-API frame count"); | |
| 406 | + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { | |
| 407 | + let p = psnr(&dec.0, &rec.0); | |
| 408 | + assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB"); | |
| 409 | + } | |
| 410 | +} | |
| 411 | + | |
| 412 | +/// Real 1080p pictures from this machine's library, demuxed by `ec-mp4` and | |
| 413 | +/// decoded by this crate, are re-encoded and handed back to ffmpeg. | |
| 414 | +/// | |
| 415 | +/// Synthetic clips do not have film grain, hard cuts, or the residual | |
| 416 | +/// statistics an encoder actually meets; a stream that survives a gradient and | |
| 417 | +/// a moving box says nothing about one. Every picture must decode to exactly | |
| 418 | +/// the encoder's own reconstruction, and the run reports the rate it landed on | |
| 419 | +/// against the rate it was asked for. | |
| 420 | +#[test] | |
| 421 | +fn real_library_frames_encode_and_decode_exactly() { | |
| 422 | + use ec_core::registry::{Decoder as _, Demuxer as _}; | |
| 423 | + | |
| 424 | + if !have_ffmpeg() { | |
| 425 | + eprintln!("SKIP real_library_frames: no ffmpeg on PATH"); | |
| 426 | + return; | |
| 427 | + } | |
| 428 | + let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) | |
| 429 | + .join("../../fixtures/real-library-manifest.tsv"); | |
| 430 | + let Ok(text) = std::fs::read_to_string(&manifest) else { | |
| 431 | + eprintln!("SKIP real_library_frames: {} missing", manifest.display()); | |
| 432 | + return; | |
| 433 | + }; | |
| 434 | + // The first 8-bit 4:2:0 H.264 mp4 of at least 720p in the manifest. | |
| 435 | + let mut source = None; | |
| 436 | + for line in text.lines().skip(1) { | |
| 437 | + let f: Vec<&str> = line.split('\t').collect(); | |
| 438 | + if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" { | |
| 439 | + continue; | |
| 440 | + } | |
| 441 | + let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else { | |
| 442 | + continue; | |
| 443 | + }; | |
| 444 | + if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) { | |
| 445 | + continue; | |
| 446 | + } | |
| 447 | + if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() { | |
| 448 | + continue; | |
| 449 | + } | |
| 450 | + source = Some((f[0].to_string(), w, h)); | |
| 451 | + break; | |
| 452 | + } | |
| 453 | + let Some((path, w, h)) = source else { | |
| 454 | + eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest"); | |
| 455 | + return; | |
| 456 | + }; | |
| 457 | + | |
| 458 | + // Decode a handful of real pictures. | |
| 459 | + let file = std::fs::File::open(&path).expect("source opens"); | |
| 460 | + let mut demux = | |
| 461 | + ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); | |
| 462 | + let (index, params) = demux | |
| 463 | + .streams() | |
| 464 | + .iter() | |
| 465 | + .find(|s| s.params.codec == ec_core::registry::CodecId::H264) | |
| 466 | + .map(|s| (s.index, s.params.clone())) | |
| 467 | + .expect("an H.264 track"); | |
| 468 | + let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); | |
| 469 | + let mut sources: Vec<Planes> = Vec::new(); | |
| 470 | + while sources.len() < 12 { | |
| 471 | + let Ok(packet) = demux.next_packet() else { | |
| 472 | + break; | |
| 473 | + }; | |
| 474 | + if packet.stream != index { | |
| 475 | + continue; | |
| 476 | + } | |
| 477 | + dec.send_packet(&packet).expect("decode"); | |
| 478 | + while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { | |
| 479 | + if sources.len() < 12 { | |
| 480 | + sources.push(planes_of(&f)); | |
| 481 | + } | |
| 482 | + } | |
| 483 | + } | |
| 484 | + assert!( | |
| 485 | + sources.len() >= 6, | |
| 486 | + "only {} pictures decoded from the library file", | |
| 487 | + sources.len() | |
| 488 | + ); | |
| 489 | + | |
| 490 | + let bitrate = 8_000_000u32; | |
| 491 | + let mut cfg = EncoderConfig::new(w as u32, h as u32); | |
| 492 | + cfg.bitrate = bitrate; | |
| 493 | + cfg.framerate = 25.0; | |
| 494 | + cfg.gop_size = 25; | |
| 495 | + cfg.threads = 0; | |
| 496 | + let mut enc = Encoder::new(cfg).expect("encoder"); | |
| 497 | + let mut stream = Vec::new(); | |
| 498 | + let mut recons = Vec::new(); | |
| 499 | + let mut bits = 0u64; | |
| 500 | + for (y, u, v) in &sources { | |
| 501 | + let view = PictureView::i420(w as u32, h as u32, y, u, v); | |
| 502 | + let p = enc.encode(&view).expect("encode"); | |
| 503 | + bits += p.au.len() as u64 * 8; | |
| 504 | + stream.extend_from_slice(&p.au); | |
| 505 | + recons.push(enc.reconstruction().expect("reconstruction")); | |
| 506 | + } | |
| 507 | + let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); | |
| 508 | + assert_eq!(decoded.len(), recons.len(), "picture count"); | |
| 509 | + for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { | |
| 510 | + assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip"); | |
| 511 | + assert_eq!(dec.1, rec.1, "Cb of picture {i}"); | |
| 512 | + assert_eq!(dec.2, rec.2, "Cr of picture {i}"); | |
| 513 | + } | |
| 514 | + let quality: f64 = sources | |
| 515 | + .iter() | |
| 516 | + .zip(&recons) | |
| 517 | + .map(|((y, ..), (ry, ..))| psnr(y, ry)) | |
| 518 | + .sum::<f64>() | |
| 519 | + / sources.len() as f64; | |
| 520 | + let rate = bits as f64 / (sources.len() as f64 / 25.0); | |
| 521 | + eprintln!( | |
| 522 | + "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB", | |
| 523 | + sources.len(), | |
| 524 | + rate / 1000.0, | |
| 525 | + f64::from(bitrate) / 1000.0 | |
| 526 | + ); | |
| 527 | + assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); | |
| 528 | +} |