U7: drop unlisted ec-h265 integration test modules and ec-h265-syntax sei_sweep (test bloat, no output change)
Browse files at this commit38b53e5d07dea3210daad6ebf7c7f76998b5b6c3Parent: 41510f015 changed files +0 -4491
- crates/ec-h265-syntax/tests/sei_sweep.rs +0 -83
- crates/ec-h265/tests/it/conformance.rs +0 -964
- crates/ec-h265/tests/it/conformance_intra.rs +0 -276
- crates/ec-h265/tests/it/conformance_rext.rs +0 -325
- crates/ec-h265/tests/it/conformance_rext422.rs +0 -128
- crates/ec-h265/tests/it/cu_syntax.rs +0 -130
- crates/ec-h265/tests/it/dec_meta.rs +0 -244
- crates/ec-h265/tests/it/dec_shell.rs +0 -454
- crates/ec-h265/tests/it/dolby_vision_p8.rs +0 -197
- crates/ec-h265/tests/it/encode.rs +0 -922
- crates/ec-h265/tests/it/main.rs +0 -13
- crates/ec-h265/tests/it/rate_control.rs +0 -207
- crates/ec-h265/tests/it/rdoq_cache_hash.rs +0 -70
- crates/ec-h265/tests/it/real_library.rs +0 -367
- crates/ec-h265/tests/it/scaling_lists.rs +0 -111
crates/ec-h265-syntax/tests/sei_sweep.rsdeleted+0 -83
| @@ -1,83 +0,0 @@ | |||
| 1 | -//! The SEI reader over the JCT-VC conformance streams. | ||
| 2 | -//! | ||
| 3 | -//! Every prefix and suffix SEI NAL unit of every stream must parse without error, | ||
| 4 | - | ||
| 5 | -use std::path::{Path, PathBuf}; | ||
| 6 | - | ||
| 7 | -use ec_h265_syntax::nal::split_annex_b; | ||
| 8 | -use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp}; | ||
| 9 | - | ||
| 10 | -fn streams() -> Vec<PathBuf> { | ||
| 11 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 12 | - fn walk(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 13 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 14 | - return; | ||
| 15 | - }; | ||
| 16 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 17 | - paths.sort(); | ||
| 18 | - for p in paths { | ||
| 19 | - if p.is_dir() && depth > 0 { | ||
| 20 | - walk(&p, depth - 1, out); | ||
| 21 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 22 | - out.push(p); | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - let mut out = Vec::new(); | ||
| 27 | - walk(&root, 2, &mut out); | ||
| 28 | - out | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -#[test] | ||
| 32 | -fn every_sei_in_the_conformance_streams_parses() { | ||
| 33 | - let streams = streams(); | ||
| 34 | - assert!(!streams.is_empty(), "no streams under vectors/hevc-jctvc"); | ||
| 35 | - let mut with_hash = 0usize; | ||
| 36 | - let mut hash_streams = Vec::new(); | ||
| 37 | - let mut sei_nals = 0usize; | ||
| 38 | - let mut messages = 0usize; | ||
| 39 | - let mut hashes = 0usize; | ||
| 40 | - let mut failures = Vec::new(); | ||
| 41 | - for path in &streams { | ||
| 42 | - let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); | ||
| 43 | - let data = match std::fs::read(path) { | ||
| 44 | - Ok(d) => d, | ||
| 45 | - Err(e) => { | ||
| 46 | - failures.push(format!("{name}: read: {e}")); | ||
| 47 | - continue; | ||
| 48 | - } | ||
| 49 | - }; | ||
| 50 | - let mut stream_hashes = 0usize; | ||
| 51 | - for nal in split_annex_b(&data) { | ||
| 52 | - if nal.header.layer_id > 0 || !matches!(nal.header.nal_type.code(), 39 | 40) { | ||
| 53 | - continue; | ||
| 54 | - } | ||
| 55 | - sei_nals += 1; | ||
| 56 | - match parse_sei_rbsp(&nal.rbsp()) { | ||
| 57 | - Ok(msgs) => { | ||
| 58 | - messages += msgs.len(); | ||
| 59 | - for msg in &msgs { | ||
| 60 | - if matches!(msg, SeiMessage::DecodedPictureHash(_)) { | ||
| 61 | - stream_hashes += 1; | ||
| 62 | - } | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - Err(e) => failures.push(format!("{name}: SEI NAL #{sei_nals}: {e}")), | ||
| 66 | - } | ||
| 67 | - } | ||
| 68 | - if stream_hashes > 0 { | ||
| 69 | - with_hash += 1; | ||
| 70 | - hash_streams.push(name.clone()); | ||
| 71 | - } | ||
| 72 | - hashes += stream_hashes; | ||
| 73 | - } | ||
| 74 | - eprintln!( | ||
| 75 | - "SEI sweep: {} streams, {with_hash} carry decoded_picture_hash ({hashes} hash messages), \ | ||
| 76 | - {sei_nals} SEI NAL units, {messages} messages, {} parse failures", | ||
| 77 | - streams.len(), | ||
| 78 | - failures.len() | ||
| 79 | - ); | ||
| 80 | - eprintln!("streams with decoded_picture_hash: {}", hash_streams.join(" ")); | ||
| 81 | - assert!(failures.is_empty(), "SEI that failed to parse:\n{}", failures.join("\n")); | ||
| 82 | - assert!(with_hash > 0, "no conformance stream carries decoded_picture_hash SEI"); | ||
| 83 | -} | ||
crates/ec-h265/tests/it/conformance.rsdeleted+0 -964
| @@ -1,964 +0,0 @@ | |||
| 1 | -//! Conformance: every access unit this encoder writes must decode in ffmpeg, | ||
| 2 | -//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own | ||
| 3 | -//! reconstruction. That equality is the whole point of coding with the in-loop | ||
| 4 | -//! filters off: it turns "the file plays" into "the decoder and the encoder | ||
| 5 | -//! agree on every sample". | ||
| 6 | - | ||
| 7 | -use crate::common::{natural_frame, pin_or_panic, test_frame}; | ||
| 8 | -use ec_core::frame::VideoFrame; | ||
| 9 | -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip}; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -fn scratch_dir() -> PathBuf { | ||
| 13 | - let dir = std::env::temp_dir().join("ec-h265-tests"); | ||
| 14 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 15 | - dir | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. | ||
| 19 | -fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> { | ||
| 20 | - let out = path.with_extension("yuv"); | ||
| 21 | - let status = ec_testkit::ffmpeg() | ||
| 22 | - .args(["-v", "error", "-y", "-i"]) | ||
| 23 | - .arg(path) | ||
| 24 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 25 | - .arg(&out) | ||
| 26 | - .output() | ||
| 27 | - .map_err(|e| e.to_string())?; | ||
| 28 | - if !status.status.success() { | ||
| 29 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 30 | - } | ||
| 31 | - let stderr = String::from_utf8_lossy(&status.stderr).to_string(); | ||
| 32 | - if !stderr.trim().is_empty() { | ||
| 33 | - return Err(format!("ffmpeg complained: {stderr}")); | ||
| 34 | - } | ||
| 35 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -/// Pin one access unit as an Annex-B file for [`ffmpeg_decode`]. | ||
| 39 | -/// | ||
| 40 | -/// lane-h26xpinloud: this used `File::create(..).expect(..)` + | ||
| 41 | -/// `write_all(..).expect("write bitstream")`, which closes only the ERROR path. | ||
| 42 | -/// A write that reports success and leaves a short file put a truncated stream | ||
| 43 | -/// at exactly the path ffmpeg then decoded, so the shortfall now carries the | ||
| 44 | -/// path, both counts, and the OS error. Panic semantics kept: this caller | ||
| 45 | -/// panicked before and still does, with the failure line as the message. | ||
| 46 | -fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { | ||
| 47 | - let path = scratch_dir().join(format!("{name}.265")); | ||
| 48 | - pin_or_panic("write_au", &path, &picture.au); | ||
| 49 | - path | ||
| 50 | -} | ||
| 51 | - | ||
| 52 | -fn planes_of(frame: &VideoFrame) -> Vec<u8> { | ||
| 53 | - let mut out = Vec::new(); | ||
| 54 | - let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 55 | - for (i, plane) in frame.planes.iter().enumerate() { | ||
| 56 | - let (pw, ph) = if i == 0 { | ||
| 57 | - (w, h) | ||
| 58 | - } else { | ||
| 59 | - (w.div_ceil(2), h.div_ceil(2)) | ||
| 60 | - }; | ||
| 61 | - for row in 0..ph { | ||
| 62 | - out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - out | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 69 | - assert_eq!(a.len(), b.len()); | ||
| 70 | - let mse: f64 = a | ||
| 71 | - .iter() | ||
| 72 | - .zip(b) | ||
| 73 | - .map(|(x, y)| { | ||
| 74 | - let d = f64::from(*x) - f64::from(*y); | ||
| 75 | - d * d | ||
| 76 | - }) | ||
| 77 | - .sum::<f64>() | ||
| 78 | - / a.len() as f64; | ||
| 79 | - if mse == 0.0 { | ||
| 80 | - 99.0 | ||
| 81 | - } else { | ||
| 82 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 83 | - } | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -/// Encode one picture; `ctb` of `None` takes the configured default. | ||
| 87 | -fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) { | ||
| 88 | - encode_with(width, height, qp, ctb, false, false) | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -fn encode_with( | ||
| 92 | - width: u32, | ||
| 93 | - height: u32, | ||
| 94 | - qp: i32, | ||
| 95 | - ctb: Option<usize>, | ||
| 96 | - chroma_mode_search: bool, | ||
| 97 | - intra_nxn: bool, | ||
| 98 | -) -> (VideoFrame, EncodedPicture) { | ||
| 99 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 100 | - cfg.chroma_mode_search = chroma_mode_search; | ||
| 101 | - cfg.intra_nxn = intra_nxn; | ||
| 102 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 103 | - if let Some(ctb) = ctb { | ||
| 104 | - cfg.ctb_size = ctb; | ||
| 105 | - } | ||
| 106 | - cfg.keep_recon = true; | ||
| 107 | - cfg.picture_hash = true; | ||
| 108 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 109 | - let frame = test_frame(width, height, 0); | ||
| 110 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 111 | - (frame, coded) | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -/// Same as `encode_with`, but on the grainy natural frame and with no chroma | ||
| 115 | -/// mode search — the synthetic test frame is flat enough that the quadtree | ||
| 116 | -/// never keeps an 8x8 coding unit, which is the only size PART_NxN applies to. | ||
| 117 | -fn encode_natural( | ||
| 118 | - width: u32, | ||
| 119 | - height: u32, | ||
| 120 | - qp: i32, | ||
| 121 | - intra_nxn: bool, | ||
| 122 | -) -> (VideoFrame, EncodedPicture) { | ||
| 123 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 124 | - cfg.intra_nxn = intra_nxn; | ||
| 125 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 126 | - cfg.keep_recon = true; | ||
| 127 | - cfg.picture_hash = true; | ||
| 128 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 129 | - let frame = natural_frame(width, height, 0); | ||
| 130 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 131 | - (frame, coded) | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -/// The chroma mode search is off by default (it loses on screen content, see | ||
| 135 | -/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an | ||
| 136 | -/// `intra_chroma_pred_mode` other than the derived one. This exercises the four | ||
| 137 | -/// explicit modes: the stream has to differ from the derived-only one — proving | ||
| 138 | -/// the search actually fired — and still decode bit-exactly. | ||
| 139 | -#[test] | ||
| 140 | -fn chroma_mode_search_decodes_bit_exactly() { | ||
| 141 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 142 | - let (source, coded) = encode_with(w, h, 27, None, true, false); | ||
| 143 | - let (_, derived) = encode_with(w, h, 27, None, false, false); | ||
| 144 | - let name = format!("chroma-rd-{w}x{h}"); | ||
| 145 | - assert_ne!( | ||
| 146 | - coded.au, derived.au, | ||
| 147 | - "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" | ||
| 148 | - ); | ||
| 149 | - let path = write_au(&name, &coded); | ||
| 150 | - let decoded = match ffmpeg_decode(&path) { | ||
| 151 | - Ok(bytes) => bytes, | ||
| 152 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 153 | - }; | ||
| 154 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 155 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 156 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 157 | - if mismatches != 0 { | ||
| 158 | - // Which plane and where: a luma-only divergence is the transform | ||
| 159 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 160 | - let luma = (w * h) as usize; | ||
| 161 | - let chroma = luma / 4; | ||
| 162 | - let first = decoded | ||
| 163 | - .iter() | ||
| 164 | - .zip(&recon) | ||
| 165 | - .position(|(a, b)| a != b) | ||
| 166 | - .unwrap(); | ||
| 167 | - let count = |range: std::ops::Range<usize>| { | ||
| 168 | - decoded[range.clone()] | ||
| 169 | - .iter() | ||
| 170 | - .zip(&recon[range]) | ||
| 171 | - .filter(|(a, b)| a != b) | ||
| 172 | - .count() | ||
| 173 | - }; | ||
| 174 | - let mut map = String::new(); | ||
| 175 | - for by in (0..h as usize).step_by(16) { | ||
| 176 | - for bx in (0..w as usize).step_by(16) { | ||
| 177 | - let mut c = 0; | ||
| 178 | - for row in by..by + 16 { | ||
| 179 | - for col in bx..bx + 16 { | ||
| 180 | - let i = row * w as usize + col; | ||
| 181 | - if decoded[i] != recon[i] { | ||
| 182 | - c += 1; | ||
| 183 | - } | ||
| 184 | - } | ||
| 185 | - } | ||
| 186 | - map.push_str(&format!("{c:4}")); | ||
| 187 | - } | ||
| 188 | - map.push('\n'); | ||
| 189 | - } | ||
| 190 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 191 | - panic!( | ||
| 192 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 193 | - ({}, {})", | ||
| 194 | - count(0..luma), | ||
| 195 | - count(luma..luma + chroma), | ||
| 196 | - count(luma + chroma..luma + 2 * chroma), | ||
| 197 | - first % w as usize, | ||
| 198 | - first / w as usize, | ||
| 199 | - ); | ||
| 200 | - } | ||
| 201 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 202 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 203 | - } | ||
| 204 | -} | ||
| 205 | - | ||
| 206 | -/// PART_NxN is off by default, so nothing else here codes a four-partition | ||
| 207 | -/// coding unit. This does: the stream has to differ from the 2Nx2N-only one — | ||
| 208 | -/// proving the partition actually fired — and still decode bit-exactly, which | ||
| 209 | -/// is the only check that the inferred transform split, the four `cbf_luma` | ||
| 210 | -/// flags at transform depth 1 and the chroma residual riding on the last | ||
| 211 | -/// partition are all where the decoder looks for them. | ||
| 212 | -#[test] | ||
| 213 | -fn intra_nxn_decodes_bit_exactly() { | ||
| 214 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 215 | - let (source, coded) = encode_natural(w, h, 22, true); | ||
| 216 | - let (_, square) = encode_natural(w, h, 22, false); | ||
| 217 | - let name = format!("intra-nxn-{w}x{h}"); | ||
| 218 | - assert_ne!( | ||
| 219 | - coded.au, square.au, | ||
| 220 | - "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" | ||
| 221 | - ); | ||
| 222 | - let path = write_au(&name, &coded); | ||
| 223 | - let decoded = match ffmpeg_decode(&path) { | ||
| 224 | - Ok(bytes) => bytes, | ||
| 225 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 226 | - }; | ||
| 227 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 228 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 229 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 230 | - if mismatches != 0 { | ||
| 231 | - // Which plane and where: a luma-only divergence is the transform | ||
| 232 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 233 | - let luma = (w * h) as usize; | ||
| 234 | - let chroma = luma / 4; | ||
| 235 | - let first = decoded | ||
| 236 | - .iter() | ||
| 237 | - .zip(&recon) | ||
| 238 | - .position(|(a, b)| a != b) | ||
| 239 | - .unwrap(); | ||
| 240 | - let count = |range: std::ops::Range<usize>| { | ||
| 241 | - decoded[range.clone()] | ||
| 242 | - .iter() | ||
| 243 | - .zip(&recon[range]) | ||
| 244 | - .filter(|(a, b)| a != b) | ||
| 245 | - .count() | ||
| 246 | - }; | ||
| 247 | - let mut map = String::new(); | ||
| 248 | - for by in (0..h as usize).step_by(16) { | ||
| 249 | - for bx in (0..w as usize).step_by(16) { | ||
| 250 | - let mut c = 0; | ||
| 251 | - for row in by..by + 16 { | ||
| 252 | - for col in bx..bx + 16 { | ||
| 253 | - let i = row * w as usize + col; | ||
| 254 | - if decoded[i] != recon[i] { | ||
| 255 | - c += 1; | ||
| 256 | - } | ||
| 257 | - } | ||
| 258 | - } | ||
| 259 | - map.push_str(&format!("{c:4}")); | ||
| 260 | - } | ||
| 261 | - map.push('\n'); | ||
| 262 | - } | ||
| 263 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 264 | - panic!( | ||
| 265 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 266 | - ({}, {})", | ||
| 267 | - count(0..luma), | ||
| 268 | - count(luma..luma + chroma), | ||
| 269 | - count(luma + chroma..luma + 2 * chroma), | ||
| 270 | - first % w as usize, | ||
| 271 | - first / w as usize, | ||
| 272 | - ); | ||
| 273 | - } | ||
| 274 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 275 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 276 | - } | ||
| 277 | -} | ||
| 278 | - | ||
| 279 | -/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for | ||
| 280 | -/// it by nudging a level, so the encoder and the decoder only agree if the | ||
| 281 | -/// parity the encoder wrote is the parity the decoder reads. The stream has to | ||
| 282 | -/// differ from the hiding-off one, and ffmpeg's decode has to match the | ||
| 283 | -/// encoder's reconstruction sample for sample. | ||
| 284 | -/// | ||
| 285 | -/// Size is deliberately not asserted here: hiding is not optional per | ||
| 286 | -/// sub-block, so a single small picture can come out a few bytes longer when | ||
| 287 | -/// the nudges cost more than the signs saved. Whether it pays is what the | ||
| 288 | -/// `EC_H265_SDH` arm of the clip gate measures. | ||
| 289 | -#[test] | ||
| 290 | -fn sign_hiding_decodes_bit_exactly() { | ||
| 291 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 292 | - let (source, coded) = encode_sdh(w, h, 22, true); | ||
| 293 | - let (_, plain) = encode_sdh(w, h, 22, false); | ||
| 294 | - let name = format!("sign-hiding-{w}x{h}"); | ||
| 295 | - assert_ne!( | ||
| 296 | - coded.au, plain.au, | ||
| 297 | - "{name}: no sub-block ever qualified, so this decode proves nothing" | ||
| 298 | - ); | ||
| 299 | - let path = write_au(&name, &coded); | ||
| 300 | - let decoded = match ffmpeg_decode(&path) { | ||
| 301 | - Ok(bytes) => bytes, | ||
| 302 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 303 | - }; | ||
| 304 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 305 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 306 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 307 | - if mismatches != 0 { | ||
| 308 | - // Which plane and where: a luma-only divergence is the transform | ||
| 309 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 310 | - let luma = (w * h) as usize; | ||
| 311 | - let chroma = luma / 4; | ||
| 312 | - let first = decoded | ||
| 313 | - .iter() | ||
| 314 | - .zip(&recon) | ||
| 315 | - .position(|(a, b)| a != b) | ||
| 316 | - .unwrap(); | ||
| 317 | - let count = |range: std::ops::Range<usize>| { | ||
| 318 | - decoded[range.clone()] | ||
| 319 | - .iter() | ||
| 320 | - .zip(&recon[range]) | ||
| 321 | - .filter(|(a, b)| a != b) | ||
| 322 | - .count() | ||
| 323 | - }; | ||
| 324 | - let mut map = String::new(); | ||
| 325 | - for by in (0..h as usize).step_by(16) { | ||
| 326 | - for bx in (0..w as usize).step_by(16) { | ||
| 327 | - let mut c = 0; | ||
| 328 | - for row in by..by + 16 { | ||
| 329 | - for col in bx..bx + 16 { | ||
| 330 | - let i = row * w as usize + col; | ||
| 331 | - if decoded[i] != recon[i] { | ||
| 332 | - c += 1; | ||
| 333 | - } | ||
| 334 | - } | ||
| 335 | - } | ||
| 336 | - map.push_str(&format!("{c:4}")); | ||
| 337 | - } | ||
| 338 | - map.push('\n'); | ||
| 339 | - } | ||
| 340 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 341 | - panic!( | ||
| 342 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 343 | - ({}, {})", | ||
| 344 | - count(0..luma), | ||
| 345 | - count(luma..luma + chroma), | ||
| 346 | - count(luma + chroma..luma + 2 * chroma), | ||
| 347 | - first % w as usize, | ||
| 348 | - first / w as usize, | ||
| 349 | - ); | ||
| 350 | - } | ||
| 351 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 352 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 353 | - } | ||
| 354 | -} | ||
| 355 | - | ||
| 356 | -/// The natural frame coded with sign data hiding on or off, everything else | ||
| 357 | -/// left at its default. | ||
| 358 | -fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { | ||
| 359 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 360 | - cfg.sign_hiding = sign_hiding; | ||
| 361 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 362 | - cfg.keep_recon = true; | ||
| 363 | - cfg.picture_hash = true; | ||
| 364 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 365 | - let frame = natural_frame(width, height, 0); | ||
| 366 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 367 | - (frame, coded) | ||
| 368 | -} | ||
| 369 | - | ||
| 370 | -/// The natural frame coded with transform skip on or off, everything else | ||
| 371 | -/// left at its default. | ||
| 372 | -fn encode_tskip( | ||
| 373 | - width: u32, | ||
| 374 | - height: u32, | ||
| 375 | - qp: i32, | ||
| 376 | - tskip: TransformSkip, | ||
| 377 | -) -> (VideoFrame, EncodedPicture) { | ||
| 378 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 379 | - cfg.transform_skip = tskip; | ||
| 380 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 381 | - cfg.keep_recon = true; | ||
| 382 | - cfg.picture_hash = true; | ||
| 383 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 384 | - let frame = natural_frame(width, height, 0); | ||
| 385 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 386 | - (frame, coded) | ||
| 387 | -} | ||
| 388 | - | ||
| 389 | -/// Transform skip bypasses the integer transform on 4x4 TUs, coding residual | ||
| 390 | -/// samples directly with a fixed shift. The encoder and decoder agree only if | ||
| 391 | -/// the shift matches on both sides; the stream has to differ from the | ||
| 392 | -/// skip-off one, and ffmpeg's decode has to match the encoder's reconstruction | ||
| 393 | -/// sample for sample. | ||
| 394 | -#[test] | ||
| 395 | -fn transform_skip_decodes_bit_exactly() { | ||
| 396 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 397 | - let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4); | ||
| 398 | - let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off); | ||
| 399 | - let name = format!("transform-skip-{w}x{h}"); | ||
| 400 | - assert_ne!( | ||
| 401 | - coded.au, plain.au, | ||
| 402 | - "{name}: no TU ever skipped, so this decode proves nothing" | ||
| 403 | - ); | ||
| 404 | - let path = write_au(&name, &coded); | ||
| 405 | - let decoded = match ffmpeg_decode(&path) { | ||
| 406 | - Ok(bytes) => bytes, | ||
| 407 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 408 | - }; | ||
| 409 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 410 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 411 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 412 | - if mismatches != 0 { | ||
| 413 | - // Which plane and where: a luma-only divergence is the transform | ||
| 414 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 415 | - let luma = (w * h) as usize; | ||
| 416 | - let chroma = luma / 4; | ||
| 417 | - let first = decoded | ||
| 418 | - .iter() | ||
| 419 | - .zip(&recon) | ||
| 420 | - .position(|(a, b)| a != b) | ||
| 421 | - .unwrap(); | ||
| 422 | - let count = |range: std::ops::Range<usize>| { | ||
| 423 | - decoded[range.clone()] | ||
| 424 | - .iter() | ||
| 425 | - .zip(&recon[range]) | ||
| 426 | - .filter(|(a, b)| a != b) | ||
| 427 | - .count() | ||
| 428 | - }; | ||
| 429 | - let mut map = String::new(); | ||
| 430 | - for by in (0..h as usize).step_by(16) { | ||
| 431 | - for bx in (0..w as usize).step_by(16) { | ||
| 432 | - let mut c = 0; | ||
| 433 | - for row in by..by + 16 { | ||
| 434 | - for col in bx..bx + 16 { | ||
| 435 | - let i = row * w as usize + col; | ||
| 436 | - if decoded[i] != recon[i] { | ||
| 437 | - c += 1; | ||
| 438 | - } | ||
| 439 | - } | ||
| 440 | - } | ||
| 441 | - map.push_str(&format!("{c:4}")); | ||
| 442 | - } | ||
| 443 | - map.push('\n'); | ||
| 444 | - } | ||
| 445 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 446 | - panic!( | ||
| 447 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 448 | - ({}, {})", | ||
| 449 | - count(0..luma), | ||
| 450 | - count(luma..luma + chroma), | ||
| 451 | - count(luma + chroma..luma + 2 * chroma), | ||
| 452 | - first % w as usize, | ||
| 453 | - first / w as usize, | ||
| 454 | - ); | ||
| 455 | - } | ||
| 456 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 457 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 458 | - } | ||
| 459 | -} | ||
| 460 | -#[test] | ||
| 461 | -fn ffmpeg_decodes_bit_exactly_at_every_shape() { | ||
| 462 | - // 1920x1080 needs the conformance window on the bottom (1088 coded rows are | ||
| 463 | - // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916 | ||
| 464 | - // needs it on the right, 130x66 exercises a partial CTB in both directions. | ||
| 465 | - // Both tree sizes are coded: the default is 32, and 64 is still offered. | ||
| 466 | - for &(w, h, ctb) in &[ | ||
| 467 | - (64u32, 64u32, None), | ||
| 468 | - (130, 66, None), | ||
| 469 | - (1916, 1080, None), | ||
| 470 | - (352, 288, None), | ||
| 471 | - (1916, 1080, Some(64)), | ||
| 472 | - (130, 66, Some(64)), | ||
| 473 | - ] { | ||
| 474 | - let (source, coded) = encode(w, h, 27, ctb); | ||
| 475 | - let name = format!( | ||
| 476 | - "shape-{w}x{h}-ctb{}", | ||
| 477 | - ctb.map_or("default".to_string(), |c| c.to_string()) | ||
| 478 | - ); | ||
| 479 | - let path = write_au(&name, &coded); | ||
| 480 | - let decoded = match ffmpeg_decode(&path) { | ||
| 481 | - Ok(bytes) => bytes, | ||
| 482 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 483 | - }; | ||
| 484 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 485 | - assert_eq!( | ||
| 486 | - decoded.len(), | ||
| 487 | - recon.len(), | ||
| 488 | - "{name}: decoded {} bytes, reconstruction {} bytes", | ||
| 489 | - decoded.len(), | ||
| 490 | - recon.len() | ||
| 491 | - ); | ||
| 492 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 493 | - if mismatches != 0 { | ||
| 494 | - // Which plane and where: a luma-only divergence is the transform | ||
| 495 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 496 | - let luma = (w * h) as usize; | ||
| 497 | - let chroma = luma / 4; | ||
| 498 | - let first = decoded | ||
| 499 | - .iter() | ||
| 500 | - .zip(&recon) | ||
| 501 | - .position(|(a, b)| a != b) | ||
| 502 | - .unwrap(); | ||
| 503 | - let count = |range: std::ops::Range<usize>| { | ||
| 504 | - decoded[range.clone()] | ||
| 505 | - .iter() | ||
| 506 | - .zip(&recon[range]) | ||
| 507 | - .filter(|(a, b)| a != b) | ||
| 508 | - .count() | ||
| 509 | - }; | ||
| 510 | - let mut map = String::new(); | ||
| 511 | - for by in (0..h as usize).step_by(16) { | ||
| 512 | - for bx in (0..w as usize).step_by(16) { | ||
| 513 | - let mut c = 0; | ||
| 514 | - for row in by..by + 16 { | ||
| 515 | - for col in bx..bx + 16 { | ||
| 516 | - let i = row * w as usize + col; | ||
| 517 | - if decoded[i] != recon[i] { | ||
| 518 | - c += 1; | ||
| 519 | - } | ||
| 520 | - } | ||
| 521 | - } | ||
| 522 | - map.push_str(&format!("{c:4}")); | ||
| 523 | - } | ||
| 524 | - map.push('\n'); | ||
| 525 | - } | ||
| 526 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 527 | - panic!( | ||
| 528 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 529 | - ({}, {})", | ||
| 530 | - count(0..luma), | ||
| 531 | - count(luma..luma + chroma), | ||
| 532 | - count(luma + chroma..luma + 2 * chroma), | ||
| 533 | - first % w as usize, | ||
| 534 | - first / w as usize, | ||
| 535 | - ); | ||
| 536 | - } | ||
| 537 | - // And the encode is worth something: PSNR against the source. | ||
| 538 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 539 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 540 | - } | ||
| 541 | -} | ||
| 542 | - | ||
| 543 | -/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one | ||
| 544 | -/// luma mode, with the transform split inferred rather than signalled | ||
| 545 | -/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a | ||
| 546 | -/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the | ||
| 547 | -/// stream has to differ from the same encode with `cu64` off, or the test would | ||
| 548 | -/// pass without a single 64x64 coding unit ever being kept. | ||
| 549 | -#[test] | ||
| 550 | -fn cu64_decodes_bit_exactly() { | ||
| 551 | - // 130x66 is here for the partial coding tree blocks, not for the decision: | ||
| 552 | - // at that size only two tree blocks are whole and the search keeps neither, | ||
| 553 | - // so its stream is allowed to come out identical. | ||
| 554 | - for &(w, h, qp, fires) in &[ | ||
| 555 | - (352u32, 288u32, 32i32, true), | ||
| 556 | - (256, 256, 37, true), | ||
| 557 | - (130, 66, 32, false), | ||
| 558 | - ] { | ||
| 559 | - let (source, off) = encode_cu64(w, h, qp, false); | ||
| 560 | - let (_, on) = encode_cu64(w, h, qp, true); | ||
| 561 | - let name = format!("cu64-{w}x{h}-qp{qp}"); | ||
| 562 | - if fires { | ||
| 563 | - assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); | ||
| 564 | - } | ||
| 565 | - | ||
| 566 | - let path = write_au(&name, &on); | ||
| 567 | - let decoded = match ffmpeg_decode(&path) { | ||
| 568 | - Ok(bytes) => bytes, | ||
| 569 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 570 | - }; | ||
| 571 | - let recon = planes_of(on.recon.as_ref().expect("recon kept")); | ||
| 572 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 573 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 574 | - if mismatches != 0 { | ||
| 575 | - let first = decoded | ||
| 576 | - .iter() | ||
| 577 | - .zip(&recon) | ||
| 578 | - .position(|(a, b)| a != b) | ||
| 579 | - .unwrap(); | ||
| 580 | - let luma = (w * h) as usize; | ||
| 581 | - panic!( | ||
| 582 | - "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", | ||
| 583 | - first % w as usize, | ||
| 584 | - first / w as usize, | ||
| 585 | - decoded[..luma] | ||
| 586 | - .iter() | ||
| 587 | - .zip(&recon[..luma]) | ||
| 588 | - .filter(|(a, b)| a != b) | ||
| 589 | - .count(), | ||
| 590 | - ); | ||
| 591 | - } | ||
| 592 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 593 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); | ||
| 594 | - } | ||
| 595 | -} | ||
| 596 | - | ||
| 597 | -fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { | ||
| 598 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 599 | - cfg.ctb_size = 64; | ||
| 600 | - cfg.cu64 = cu64; | ||
| 601 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 602 | - cfg.keep_recon = true; | ||
| 603 | - cfg.picture_hash = true; | ||
| 604 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 605 | - let frame = natural_frame(width, height, 0); | ||
| 606 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 607 | - (frame, coded) | ||
| 608 | -} | ||
| 609 | - | ||
| 610 | -/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower | ||
| 611 | -/// tree; that trade is only worth taking if the bits it costs are noise. | ||
| 612 | -#[test] | ||
| 613 | -fn the_default_tree_costs_almost_nothing_against_64() { | ||
| 614 | - let source = natural_frame(1920, 1080, 0); | ||
| 615 | - let mut coded = Vec::new(); | ||
| 616 | - for ctb in [32usize, 64] { | ||
| 617 | - let mut cfg = EncoderConfig::new(1920, 1080); | ||
| 618 | - cfg.rate_control = RateControl::ConstantQp(27); | ||
| 619 | - cfg.ctb_size = ctb; | ||
| 620 | - cfg.keep_recon = true; | ||
| 621 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 622 | - let picture = encoder.encode_idr(&source).expect("encode"); | ||
| 623 | - let quality = psnr( | ||
| 624 | - &planes_of(&source), | ||
| 625 | - &planes_of(picture.recon.as_ref().unwrap()), | ||
| 626 | - ); | ||
| 627 | - coded.push((picture.au.len(), quality)); | ||
| 628 | - } | ||
| 629 | - let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); | ||
| 630 | - println!( | ||
| 631 | - "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ | ||
| 632 | - ({:+.1}% bits, {:+.2} dB)", | ||
| 633 | - (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, | ||
| 634 | - psnr32 - psnr64 | ||
| 635 | - ); | ||
| 636 | - assert!( | ||
| 637 | - // Measured 1.0% on this fixture; the bound leaves room for the shape of | ||
| 638 | - // the picture, not for a change of coding behaviour. | ||
| 639 | - (bits32 as f64) < bits64 as f64 * 1.03, | ||
| 640 | - "CTB 32 spent {bits32} bytes against 64's {bits64}" | ||
| 641 | - ); | ||
| 642 | - assert!( | ||
| 643 | - (psnr32 - psnr64).abs() < 0.1, | ||
| 644 | - "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" | ||
| 645 | - ); | ||
| 646 | -} | ||
| 647 | - | ||
| 648 | -#[test] | ||
| 649 | -fn ffmpeg_verifies_the_decoded_picture_hash() { | ||
| 650 | - // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's | ||
| 651 | - // decoder checks that claim against what it decoded when asked to. This is | ||
| 652 | - // the one oracle that does not depend on this crate being right about | ||
| 653 | - // anything except the hash itself. | ||
| 654 | - let (_, coded) = encode(352, 288, 30, None); | ||
| 655 | - let path = write_au("hash-352x288", &coded); | ||
| 656 | - let output = ec_testkit::ffmpeg() | ||
| 657 | - .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) | ||
| 658 | - .arg(&path) | ||
| 659 | - .args(["-f", "null", "-"]) | ||
| 660 | - .output() | ||
| 661 | - .expect("run ffmpeg"); | ||
| 662 | - let log = String::from_utf8_lossy(&output.stderr).to_string(); | ||
| 663 | - let checks: Vec<&str> = log | ||
| 664 | - .lines() | ||
| 665 | - .filter(|line| line.contains("Verifying checksum")) | ||
| 666 | - .collect(); | ||
| 667 | - assert!(!checks.is_empty(), "ffmpeg checked no picture hash: {log}"); | ||
| 668 | - for line in checks { | ||
| 669 | - assert_eq!(line.matches("correct").count(), 3, "hash mismatch: {line}"); | ||
| 670 | - } | ||
| 671 | -} | ||
| 672 | - | ||
| 673 | -#[test] | ||
| 674 | -fn vaapi_hardware_decodes_the_stream() { | ||
| 675 | - // The other half of "it decodes": a GPU decoder is a different | ||
| 676 | - // implementation with different tolerances, and it is what edith's HEVC | ||
| 677 | - // path actually uses. Skipped where there is no render node. | ||
| 678 | - if !Path::new("/dev/dri/renderD128").exists() { | ||
| 679 | - eprintln!("skipping: no VA-API render node"); | ||
| 680 | - return; | ||
| 681 | - } | ||
| 682 | - let (_, coded) = encode(1920, 1080, 27, None); | ||
| 683 | - let path = write_au("vaapi-1080p", &coded); | ||
| 684 | - let output = ec_testkit::ffmpeg() | ||
| 685 | - .args([ | ||
| 686 | - "-v", | ||
| 687 | - "error", | ||
| 688 | - "-hwaccel", | ||
| 689 | - "vaapi", | ||
| 690 | - "-hwaccel_device", | ||
| 691 | - "/dev/dri/renderD128", | ||
| 692 | - "-i", | ||
| 693 | - ]) | ||
| 694 | - .arg(&path) | ||
| 695 | - .args(["-f", "null", "-"]) | ||
| 696 | - .output() | ||
| 697 | - .expect("run ffmpeg"); | ||
| 698 | - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); | ||
| 699 | - if stderr.contains("Failed to initialise VAAPI") | ||
| 700 | - || stderr.contains("No VA display found") | ||
| 701 | - || stderr.contains("Device creation failed") | ||
| 702 | - { | ||
| 703 | - eprintln!("skipping: VA-API unavailable here ({})", stderr.trim()); | ||
| 704 | - return; | ||
| 705 | - } | ||
| 706 | - assert!( | ||
| 707 | - output.status.success() && stderr.trim().is_empty(), | ||
| 708 | - "VA-API decode failed: {stderr}" | ||
| 709 | - ); | ||
| 710 | -} | ||
| 711 | - | ||
| 712 | -#[test] | ||
| 713 | -fn quality_rises_as_qp_falls() { | ||
| 714 | - let mut previous = 0.0; | ||
| 715 | - for &qp in &[40i32, 32, 27, 22] { | ||
| 716 | - let (source, coded) = encode(256, 144, qp, None); | ||
| 717 | - let recon = planes_of(coded.recon.as_ref().expect("recon")); | ||
| 718 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 719 | - assert!( | ||
| 720 | - quality > previous, | ||
| 721 | - "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" | ||
| 722 | - ); | ||
| 723 | - previous = quality; | ||
| 724 | - } | ||
| 725 | - assert!( | ||
| 726 | - previous > 40.0, | ||
| 727 | - "QP 22 should clear 40 dB, got {previous:.2}" | ||
| 728 | - ); | ||
| 729 | -} | ||
| 730 | - | ||
| 731 | -#[test] | ||
| 732 | -fn threads_do_not_change_the_bitstream() { | ||
| 733 | - let mut cfg = EncoderConfig::new(320, 192); | ||
| 734 | - cfg.rate_control = RateControl::ConstantQp(30); | ||
| 735 | - cfg.threads = 1; | ||
| 736 | - let single = Encoder::new(cfg.clone()).unwrap(); | ||
| 737 | - cfg.threads = 8; | ||
| 738 | - let many = Encoder::new(cfg).unwrap(); | ||
| 739 | - let frame = test_frame(320, 192, 3); | ||
| 740 | - let a = single.encode_idr(&frame).unwrap(); | ||
| 741 | - let b = many.encode_idr(&frame).unwrap(); | ||
| 742 | - assert_eq!(a.au, b.au, "wavefront changed the bitstream"); | ||
| 743 | -} | ||
| 744 | - | ||
| 745 | -#[test] | ||
| 746 | -fn a_bit_target_lands_near_its_target() { | ||
| 747 | - // The model picks a QP from bits-per-pixel; a picture that comes out more | ||
| 748 | - // than a quarter off is coded once more at a corrected QP. What is asserted | ||
| 749 | - // is the contract that mode offers — near the target, monotonic in it — not | ||
| 750 | - // a bitrate to the byte, which no single-picture encoder can promise. | ||
| 751 | - let mut previous = 0usize; | ||
| 752 | - for target in [400_000u64, 1_200_000, 3_000_000] { | ||
| 753 | - let mut cfg = EncoderConfig::new(640, 360); | ||
| 754 | - cfg.rate_control = RateControl::TargetBits(target); | ||
| 755 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 756 | - let frame = test_frame(640, 360, 5); | ||
| 757 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 758 | - let bits = coded.au.len() * 8; | ||
| 759 | - assert!( | ||
| 760 | - bits > previous, | ||
| 761 | - "target {target}: {bits} bits did not grow with the target" | ||
| 762 | - ); | ||
| 763 | - previous = bits; | ||
| 764 | - let ratio = bits as f64 / target as f64; | ||
| 765 | - assert!( | ||
| 766 | - (0.4..2.5).contains(&ratio), | ||
| 767 | - "target {target}: got {bits} bits (x{ratio:.2}) at QP {}", | ||
| 768 | - coded.qp | ||
| 769 | - ); | ||
| 770 | - } | ||
| 771 | -} | ||
| 772 | - | ||
| 773 | -#[test] | ||
| 774 | -fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { | ||
| 775 | - let cfg = EncoderConfig::new(128, 96); | ||
| 776 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 777 | - let frames: Vec<VideoFrame> = (0..3).map(|i| test_frame(128, 96, i * 11)).collect(); | ||
| 778 | - let coded = encoder.encode_batch(frames.iter()).expect("batch encode"); | ||
| 779 | - assert_eq!(coded.len(), 3); | ||
| 780 | - for picture in &coded { | ||
| 781 | - // Every access unit stands alone: parameter sets, then an IDR slice. | ||
| 782 | - let nals = ec_h265_syntax::split_annex_b(&picture.au); | ||
| 783 | - let types: Vec<_> = nals.iter().map(|n| n.header.nal_type).collect(); | ||
| 784 | - assert_eq!( | ||
| 785 | - &types[..4], | ||
| 786 | - &[ | ||
| 787 | - ec_h265_syntax::NalUnitType::Vps, | ||
| 788 | - ec_h265_syntax::NalUnitType::Sps, | ||
| 789 | - ec_h265_syntax::NalUnitType::Pps, | ||
| 790 | - ec_h265_syntax::NalUnitType::IdrWRadl, | ||
| 791 | - ], | ||
| 792 | - "access unit is not self-contained" | ||
| 793 | - ); | ||
| 794 | - } | ||
| 795 | - // Different pictures, different bitstreams. | ||
| 796 | - assert_ne!(coded[0].au, coded[1].au); | ||
| 797 | -} | ||
| 798 | - | ||
| 799 | -/// Rate-distortion quantisation changes which levels are coded, so the streams | ||
| 800 | -/// it produces are a different set of bins from the plain quantiser's; ffmpeg | ||
| 801 | -/// has to read them back to the same samples the encoder reconstructed. | ||
| 802 | -#[test] | ||
| 803 | -fn rdoq_decodes_bit_exactly() { | ||
| 804 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 805 | - let (source, coded) = encode_rdoq(w, h, 27, true); | ||
| 806 | - let (_, plain) = encode_rdoq(w, h, 27, false); | ||
| 807 | - let name = format!("rdoq-{w}x{h}"); | ||
| 808 | - assert_ne!( | ||
| 809 | - coded.au, plain.au, | ||
| 810 | - "{name}: the level search changed no byte, so it is not running" | ||
| 811 | - ); | ||
| 812 | - let path = write_au(&name, &coded); | ||
| 813 | - let decoded = match ffmpeg_decode(&path) { | ||
| 814 | - Ok(bytes) => bytes, | ||
| 815 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 816 | - }; | ||
| 817 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 818 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 819 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 820 | - if mismatches != 0 { | ||
| 821 | - // Which plane and where: a luma-only divergence is the transform | ||
| 822 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 823 | - let luma = (w * h) as usize; | ||
| 824 | - let chroma = luma / 4; | ||
| 825 | - let first = decoded | ||
| 826 | - .iter() | ||
| 827 | - .zip(&recon) | ||
| 828 | - .position(|(a, b)| a != b) | ||
| 829 | - .unwrap(); | ||
| 830 | - let count = |range: std::ops::Range<usize>| { | ||
| 831 | - decoded[range.clone()] | ||
| 832 | - .iter() | ||
| 833 | - .zip(&recon[range]) | ||
| 834 | - .filter(|(a, b)| a != b) | ||
| 835 | - .count() | ||
| 836 | - }; | ||
| 837 | - let mut map = String::new(); | ||
| 838 | - for by in (0..h as usize).step_by(16) { | ||
| 839 | - for bx in (0..w as usize).step_by(16) { | ||
| 840 | - let mut c = 0; | ||
| 841 | - for row in by..by + 16 { | ||
| 842 | - for col in bx..bx + 16 { | ||
| 843 | - let i = row * w as usize + col; | ||
| 844 | - if decoded[i] != recon[i] { | ||
| 845 | - c += 1; | ||
| 846 | - } | ||
| 847 | - } | ||
| 848 | - } | ||
| 849 | - map.push_str(&format!("{c:4}")); | ||
| 850 | - } | ||
| 851 | - map.push('\n'); | ||
| 852 | - } | ||
| 853 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 854 | - panic!( | ||
| 855 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 856 | - ({}, {})", | ||
| 857 | - count(0..luma), | ||
| 858 | - count(luma..luma + chroma), | ||
| 859 | - count(luma + chroma..luma + 2 * chroma), | ||
| 860 | - first % w as usize, | ||
| 861 | - first / w as usize, | ||
| 862 | - ); | ||
| 863 | - } | ||
| 864 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 865 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 866 | - } | ||
| 867 | -} | ||
| 868 | - | ||
| 869 | -/// The natural frame coded with the level search on or off, everything else | ||
| 870 | -/// left at its default. | ||
| 871 | -fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { | ||
| 872 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 873 | - cfg.rdoq = rdoq; | ||
| 874 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 875 | - cfg.keep_recon = true; | ||
| 876 | - cfg.picture_hash = true; | ||
| 877 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 878 | - let frame = natural_frame(width, height, 0); | ||
| 879 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 880 | - (frame, coded) | ||
| 881 | -} | ||
| 882 | - | ||
| 883 | -/// RQT must produce a bitstream a conformant decoder reads back to the exact | ||
| 884 | -/// samples the encoder reconstructed. | ||
| 885 | -#[test] | ||
| 886 | -fn rqt_decodes_bit_exactly() { | ||
| 887 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 888 | - let (source, coded) = encode_rqt(w, h, 27, true); | ||
| 889 | - let (_, plain) = encode_rqt(w, h, 27, false); | ||
| 890 | - let name = format!("rqt-{w}x{h}"); | ||
| 891 | - assert_ne!( | ||
| 892 | - coded.au, plain.au, | ||
| 893 | - "{name}: RQT changed no byte, so the split path is not running" | ||
| 894 | - ); | ||
| 895 | - let path = write_au(&name, &coded); | ||
| 896 | - let decoded = match ffmpeg_decode(&path) { | ||
| 897 | - Ok(bytes) => bytes, | ||
| 898 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 899 | - }; | ||
| 900 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 901 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 902 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 903 | - if mismatches != 0 { | ||
| 904 | - // Which plane and where: a luma-only divergence is the transform | ||
| 905 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 906 | - let luma = (w * h) as usize; | ||
| 907 | - let chroma = luma / 4; | ||
| 908 | - let first = decoded | ||
| 909 | - .iter() | ||
| 910 | - .zip(&recon) | ||
| 911 | - .position(|(a, b)| a != b) | ||
| 912 | - .unwrap(); | ||
| 913 | - let count = |range: std::ops::Range<usize>| { | ||
| 914 | - decoded[range.clone()] | ||
| 915 | - .iter() | ||
| 916 | - .zip(&recon[range]) | ||
| 917 | - .filter(|(a, b)| a != b) | ||
| 918 | - .count() | ||
| 919 | - }; | ||
| 920 | - let mut map = String::new(); | ||
| 921 | - for by in (0..h as usize).step_by(16) { | ||
| 922 | - for bx in (0..w as usize).step_by(16) { | ||
| 923 | - let mut c = 0; | ||
| 924 | - for row in by..by + 16 { | ||
| 925 | - for col in bx..bx + 16 { | ||
| 926 | - let i = row * w as usize + col; | ||
| 927 | - if decoded[i] != recon[i] { | ||
| 928 | - c += 1; | ||
| 929 | - } | ||
| 930 | - } | ||
| 931 | - } | ||
| 932 | - map.push_str(&format!("{c:4}")); | ||
| 933 | - } | ||
| 934 | - map.push('\n'); | ||
| 935 | - } | ||
| 936 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 937 | - panic!( | ||
| 938 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 939 | - ({}, {})", | ||
| 940 | - count(0..luma), | ||
| 941 | - count(luma..luma + chroma), | ||
| 942 | - count(luma + chroma..luma + 2 * chroma), | ||
| 943 | - first % w as usize, | ||
| 944 | - first / w as usize, | ||
| 945 | - ); | ||
| 946 | - } | ||
| 947 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 948 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 949 | - } | ||
| 950 | -} | ||
| 951 | - | ||
| 952 | -/// The natural frame coded with RQT on or off, everything else left at its | ||
| 953 | -/// default. | ||
| 954 | -fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { | ||
| 955 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 956 | - cfg.rqt = rqt; | ||
| 957 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 958 | - cfg.keep_recon = true; | ||
| 959 | - cfg.picture_hash = true; | ||
| 960 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 961 | - let frame = natural_frame(width, height, 0); | ||
| 962 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 963 | - (frame, coded) | ||
| 964 | -} | ||
crates/ec-h265/tests/it/conformance_intra.rsdeleted+0 -276
| @@ -1,276 +0,0 @@ | |||
| 1 | -//! Checks every output picture of each JCT-VC conformance stream against the | ||
| 2 | -//! MD5 in its decoded picture hash SEI (D.3.19). | ||
| 3 | -//! | ||
| 4 | -//! Streams the decoder refuses are reported with the error text. Mismatches are | ||
| 5 | -//! reported, never asserted. The digest is computed with the SEI writer of | ||
| 6 | -//! `ec-h265-syntax`, which is the same MD5 the hash message carries. | ||
| 7 | - | ||
| 8 | -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; | ||
| 9 | -use std::panic::{self, AssertUnwindSafe}; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -use ec_h265::dec::Decoder; | ||
| 13 | - | ||
| 14 | -/// The outcome of one stream, one row of the report. | ||
| 15 | -struct Row { | ||
| 16 | - name: String, | ||
| 17 | - accepted: &'static str, | ||
| 18 | - checked: usize, | ||
| 19 | - exact: usize, | ||
| 20 | - detail: String, | ||
| 21 | - /// Whether any picture was checked against the reference YUV (no hash SEI). | ||
| 22 | - by_reference: bool, | ||
| 23 | - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). | ||
| 24 | - decode_secs: f64, | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -fn jctvc_root() -> PathBuf { | ||
| 28 | - ec_testkit::fixture("vectors/hevc-jctvc") | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 32 | -/// directory under the root, sorted by name. Some zips extract one directory | ||
| 33 | -/// deeper, so two levels are searched. | ||
| 34 | -fn streams() -> Vec<PathBuf> { | ||
| 35 | - let root = jctvc_root(); | ||
| 36 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 37 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 38 | - return; | ||
| 39 | - }; | ||
| 40 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 41 | - paths.sort(); | ||
| 42 | - for p in paths { | ||
| 43 | - if p.is_dir() && depth > 0 { | ||
| 44 | - bitstreams_in(&p, depth - 1, out); | ||
| 45 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 46 | - out.push(p); | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - } | ||
| 50 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 51 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 52 | - dirs.sort(); | ||
| 53 | - dirs.into_iter() | ||
| 54 | - .filter(|d| d.is_dir()) | ||
| 55 | - .filter_map(|d| { | ||
| 56 | - let mut found = Vec::new(); | ||
| 57 | - bitstreams_in(&d, 2, &mut found); | ||
| 58 | - found.into_iter().next() | ||
| 59 | - }) | ||
| 60 | - .collect() | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -/// Decodes one stream and checks every output picture against its MD5 SEI. | ||
| 64 | -fn check_stream(path: &Path, name: &str) -> Row { | ||
| 65 | - let mut row = Row { | ||
| 66 | - name: name.to_string(), | ||
| 67 | - accepted: "no", | ||
| 68 | - checked: 0, | ||
| 69 | - exact: 0, | ||
| 70 | - detail: String::new(), | ||
| 71 | - by_reference: false, | ||
| 72 | - decode_secs: 0.0, | ||
| 73 | - }; | ||
| 74 | - let data = match std::fs::read(path) { | ||
| 75 | - Ok(d) => d, | ||
| 76 | - Err(e) => { | ||
| 77 | - row.detail = format!("read error: {e}"); | ||
| 78 | - return row; | ||
| 79 | - } | ||
| 80 | - }; | ||
| 81 | - let reference = std::fs::read(path.with_extension("yuv")).ok(); | ||
| 82 | - // A `<name>_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It | ||
| 83 | - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a | ||
| 84 | - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). | ||
| 85 | - let whole_output = std::fs::read_to_string(path.with_file_name(format!("{name}_md5.txt"))) | ||
| 86 | - .ok() | ||
| 87 | - .and_then(|text| whole_output_digest(&text)); | ||
| 88 | - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); | ||
| 89 | - let mut whole_output_checked = 0usize; | ||
| 90 | - | ||
| 91 | - let started = std::time::Instant::now(); | ||
| 92 | - let mut dec = Decoder::new(); | ||
| 93 | - if let Err(e) = dec.decode_annex_b(&data) { | ||
| 94 | - row.detail = format!("error: {e}"); | ||
| 95 | - return row; | ||
| 96 | - } | ||
| 97 | - if let Err(e) = dec.flush() { | ||
| 98 | - row.detail = format!("error: {e}"); | ||
| 99 | - return row; | ||
| 100 | - } | ||
| 101 | - row.accepted = "yes"; | ||
| 102 | - | ||
| 103 | - let mut out_index = 0usize; | ||
| 104 | - let mut first: Option<String> = None; | ||
| 105 | - while let Some(frame) = dec.next_frame() { | ||
| 106 | - let index = out_index; | ||
| 107 | - out_index += 1; | ||
| 108 | - let Some(expected) = frame.meta.picture_hash.as_ref() else { | ||
| 109 | - if whole_output.is_some() { | ||
| 110 | - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); | ||
| 111 | - whole_output_checked += 1; | ||
| 112 | - continue; | ||
| 113 | - } | ||
| 114 | - // No hash SEI: the frame is checked against the reference YUV, when there is one. | ||
| 115 | - if let Some(reference) = reference.as_deref() { | ||
| 116 | - let want = cropped_bytes(&frame.picture, &frame.window); | ||
| 117 | - let start = index * want.len(); | ||
| 118 | - row.checked += 1; | ||
| 119 | - if reference.get(start..start + want.len()) == Some(&want[..]) { | ||
| 120 | - row.exact += 1; | ||
| 121 | - } else if first.is_none() { | ||
| 122 | - let at = (0..3) | ||
| 123 | - .find_map(|plane| { | ||
| 124 | - let d = | ||
| 125 | - describe(Some(reference), index, &frame.picture, frame.poc, plane); | ||
| 126 | - (!d.contains("no sample differs")).then_some(d) | ||
| 127 | - }) | ||
| 128 | - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); | ||
| 129 | - first = Some(format!("{at} (reference YUV, cropped)")); | ||
| 130 | - } | ||
| 131 | - row.by_reference = true; | ||
| 132 | - } | ||
| 133 | - continue; | ||
| 134 | - }; | ||
| 135 | - row.checked += 1; | ||
| 136 | - let pic = &*frame.picture; | ||
| 137 | - let mut exact = true; | ||
| 138 | - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { | ||
| 139 | - if ok { | ||
| 140 | - continue; | ||
| 141 | - } | ||
| 142 | - exact = false; | ||
| 143 | - if first.is_none() { | ||
| 144 | - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; | ||
| 145 | - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); | ||
| 146 | - first = Some(format!("{at} slices={kind}")); | ||
| 147 | - } | ||
| 148 | - } | ||
| 149 | - if exact { | ||
| 150 | - row.exact += 1; | ||
| 151 | - } | ||
| 152 | - } | ||
| 153 | - row.decode_secs = started.elapsed().as_secs_f64(); | ||
| 154 | - if let Some(want) = whole_output { | ||
| 155 | - let got = whole_output_md5.finish(); | ||
| 156 | - row.checked += whole_output_checked; | ||
| 157 | - if got == want { | ||
| 158 | - row.exact += whole_output_checked; | ||
| 159 | - } else { | ||
| 160 | - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); | ||
| 161 | - first.get_or_insert(format!( | ||
| 162 | - "whole-output MD5 {hex} differs from {name}_md5.txt" | ||
| 163 | - )); | ||
| 164 | - } | ||
| 165 | - row.by_reference = true; | ||
| 166 | - } | ||
| 167 | - row.detail = match (first, row.checked) { | ||
| 168 | - (Some(f), _) => format!("first mismatch {f}"), | ||
| 169 | - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), | ||
| 170 | - (None, _) if whole_output.is_some() => { | ||
| 171 | - "ok (whole-output MD5 from the conformance package)".to_string() | ||
| 172 | - } | ||
| 173 | - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), | ||
| 174 | - (None, _) => "ok".to_string(), | ||
| 175 | - }; | ||
| 176 | - row | ||
| 177 | -} | ||
| 178 | - | ||
| 179 | -#[test] | ||
| 180 | -fn conformance_pictures_match_the_sei_hash() { | ||
| 181 | - let root = jctvc_root(); | ||
| 182 | - let streams = streams(); | ||
| 183 | - assert!( | ||
| 184 | - !streams.is_empty(), | ||
| 185 | - "no conformance streams under {}", | ||
| 186 | - root.display() | ||
| 187 | - ); | ||
| 188 | - | ||
| 189 | - let mut rows = Vec::new(); | ||
| 190 | - for path in &streams { | ||
| 191 | - let name = path | ||
| 192 | - .file_stem() | ||
| 193 | - .map(|s| s.to_string_lossy().into_owned()) | ||
| 194 | - .unwrap_or_default(); | ||
| 195 | - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); | ||
| 196 | - let mut row = match outcome { | ||
| 197 | - Ok(row) => row, | ||
| 198 | - Err(payload) => { | ||
| 199 | - let msg = payload | ||
| 200 | - .downcast_ref::<&str>() | ||
| 201 | - .map(|s| s.to_string()) | ||
| 202 | - .or_else(|| payload.downcast_ref::<String>().cloned()) | ||
| 203 | - .unwrap_or_default(); | ||
| 204 | - Row { | ||
| 205 | - name: name.clone(), | ||
| 206 | - accepted: "panic", | ||
| 207 | - checked: 0, | ||
| 208 | - exact: 0, | ||
| 209 | - detail: format!("panic: {msg}"), | ||
| 210 | - by_reference: false, | ||
| 211 | - decode_secs: 0.0, | ||
| 212 | - } | ||
| 213 | - } | ||
| 214 | - }; | ||
| 215 | - row.detail = row.detail.replace(['\t', '\n'], " "); | ||
| 216 | - rows.push(row); | ||
| 217 | - } | ||
| 218 | - | ||
| 219 | - let mut table = | ||
| 220 | - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); | ||
| 221 | - for r in &rows { | ||
| 222 | - println!( | ||
| 223 | - "{} | {} | {} | {} | {} | {:.2}s", | ||
| 224 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 225 | - ); | ||
| 226 | - table.push_str(&format!( | ||
| 227 | - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", | ||
| 228 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 229 | - )); | ||
| 230 | - } | ||
| 231 | - let checked: usize = rows.iter().map(|r| r.checked).sum(); | ||
| 232 | - let exact: usize = rows.iter().map(|r| r.exact).sum(); | ||
| 233 | - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); | ||
| 234 | - println!( | ||
| 235 | - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", | ||
| 236 | - rows.len() | ||
| 237 | - ); | ||
| 238 | - let report = std::env::var("EC_H265_INTRA_REPORT") | ||
| 239 | - .ok() | ||
| 240 | - .filter(|p| !p.is_empty()); | ||
| 241 | - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); | ||
| 242 | - if let Some(Err((path, e))) = written { | ||
| 243 | - eprintln!("could not write report {path}: {e}"); | ||
| 244 | - } | ||
| 245 | - | ||
| 246 | - // Every accepted stream must be fully exact, except the streams named in KNOWN_INEXACT. | ||
| 247 | - let failing: Vec<String> = rows | ||
| 248 | - .iter() | ||
| 249 | - .filter(|r| r.accepted == "yes" && r.checked > 0 && r.exact != r.checked) | ||
| 250 | - .filter(|r| !KNOWN_INEXACT.iter().any(|(name, _)| *name == r.name)) | ||
| 251 | - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) | ||
| 252 | - .collect(); | ||
| 253 | - assert!( | ||
| 254 | - failing.is_empty(), | ||
| 255 | - "accepted streams that are not exact and not in KNOWN_INEXACT:\n{}", | ||
| 256 | - failing.join("\n") | ||
| 257 | - ); | ||
| 258 | -} | ||
| 259 | - | ||
| 260 | -#[test] | ||
| 261 | -fn whole_output_digest_reads_the_first_word() { | ||
| 262 | - let digest = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea").unwrap(); | ||
| 263 | - assert_eq!(digest[0], 0x1d); | ||
| 264 | - assert_eq!(digest[15], 0xea); | ||
| 265 | - let with_name = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea out.yuv\n"); | ||
| 266 | - assert_eq!(with_name, Some(digest)); | ||
| 267 | - assert_eq!(whole_output_digest("1ddf7426"), None); | ||
| 268 | - assert_eq!( | ||
| 269 | - whole_output_digest("zzdf74263cb4953cfdfcf99c563d88ea"), | ||
| 270 | - None | ||
| 271 | - ); | ||
| 272 | -} | ||
| 273 | - | ||
| 274 | -/// Accepted streams that are knowingly not fully exact, each with the reason. Remove an entry | ||
| 275 | -/// once the stream is exact. Nothing else may be listed. | ||
| 276 | -const KNOWN_INEXACT: &[(&str, &str)] = &[]; | ||
crates/ec-h265/tests/it/conformance_rext.rsdeleted+0 -325
| @@ -1,325 +0,0 @@ | |||
| 1 | -//! Checks every output picture of each JCT-VC range extension conformance stream | ||
| 2 | -//! (D.3.19), or against the whole-output MD5 of the package when the stream has no hash. | ||
| 3 | -//! | ||
| 4 | -//! A stream the decoder refuses must be refused by name: the error text has to be one of | ||
| 5 | -//! `REFUSED`. Every other stream has to decode exactly, picture for picture. | ||
| 6 | - | ||
| 7 | -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; | ||
| 8 | -use std::panic::{self, AssertUnwindSafe}; | ||
| 9 | -use std::path::{Path, PathBuf}; | ||
| 10 | - | ||
| 11 | -use ec_h265::dec::Decoder; | ||
| 12 | - | ||
| 13 | -/// The outcome of one stream, one row of the report. | ||
| 14 | -struct Row { | ||
| 15 | - name: String, | ||
| 16 | - accepted: &'static str, | ||
| 17 | - checked: usize, | ||
| 18 | - exact: usize, | ||
| 19 | - detail: String, | ||
| 20 | - /// Whether any picture was checked against the reference YUV (no hash SEI). | ||
| 21 | - by_reference: bool, | ||
| 22 | - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). | ||
| 23 | - decode_secs: f64, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -fn jctvc_root() -> PathBuf { | ||
| 27 | - ec_testkit::fixture("vectors/hevc-rext") | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 31 | -/// directory under the root, sorted by name. Some zips extract one directory | ||
| 32 | -/// deeper, so two levels are searched. | ||
| 33 | -fn streams() -> Vec<PathBuf> { | ||
| 34 | - let root = jctvc_root(); | ||
| 35 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 36 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 37 | - return; | ||
| 38 | - }; | ||
| 39 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 40 | - paths.sort(); | ||
| 41 | - for p in paths { | ||
| 42 | - if p.is_dir() && depth > 0 { | ||
| 43 | - bitstreams_in(&p, depth - 1, out); | ||
| 44 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 45 | - out.push(p); | ||
| 46 | - } | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 50 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 51 | - dirs.sort(); | ||
| 52 | - dirs.into_iter() | ||
| 53 | - .filter(|d| d.is_dir()) | ||
| 54 | - .filter(|d| { | ||
| 55 | - std::env::var("EC_H265_REXT_ONLY") | ||
| 56 | - .map_or(true, |only| d.to_string_lossy().contains(&only)) | ||
| 57 | - }) | ||
| 58 | - .filter_map(|d| { | ||
| 59 | - let mut found = Vec::new(); | ||
| 60 | - bitstreams_in(&d, 2, &mut found); | ||
| 61 | - found.into_iter().next() | ||
| 62 | - }) | ||
| 63 | - .collect() | ||
| 64 | -} | ||
| 65 | - | ||
| 66 | -/// Every 32-digit hex word of the MD5 files beside the bitstream (`*md5*`): one of them is the | ||
| 67 | -/// MD5 of the whole decoded output, the others are the bitstream's own. | ||
| 68 | -fn candidate_digests(path: &Path) -> Vec<[u8; 16]> { | ||
| 69 | - let mut out = Vec::new(); | ||
| 70 | - let Some(dir) = path.parent() else { | ||
| 71 | - return out; | ||
| 72 | - }; | ||
| 73 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 74 | - return out; | ||
| 75 | - }; | ||
| 76 | - for e in entries.flatten() { | ||
| 77 | - let name = e.file_name().to_string_lossy().to_lowercase(); | ||
| 78 | - if !name.contains("md5") { | ||
| 79 | - continue; | ||
| 80 | - } | ||
| 81 | - if let Ok(text) = std::fs::read_to_string(e.path()) { | ||
| 82 | - for word in text.split_whitespace() { | ||
| 83 | - if let Some(d) = whole_output_digest(word) { | ||
| 84 | - out.push(d); | ||
| 85 | - } | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - } | ||
| 89 | - out | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -/// The stream cut at its start codes: each chunk is one NAL unit with its start code. | ||
| 93 | -fn nal_chunks(data: &[u8]) -> Vec<&[u8]> { | ||
| 94 | - let mut starts: Vec<usize> = (0..data.len().saturating_sub(2)) | ||
| 95 | - .filter(|&i| data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) | ||
| 96 | - .collect(); | ||
| 97 | - starts.push(data.len()); | ||
| 98 | - starts.windows(2).map(|w| &data[w[0]..w[1]]).collect() | ||
| 99 | -} | ||
| 100 | - | ||
| 101 | -/// Decodes one stream and checks every output picture against its MD5 SEI. | ||
| 102 | -fn check_stream(path: &Path, name: &str) -> Row { | ||
| 103 | - let mut row = Row { | ||
| 104 | - name: name.to_string(), | ||
| 105 | - accepted: "no", | ||
| 106 | - checked: 0, | ||
| 107 | - exact: 0, | ||
| 108 | - detail: String::new(), | ||
| 109 | - by_reference: false, | ||
| 110 | - decode_secs: 0.0, | ||
| 111 | - }; | ||
| 112 | - let data = match std::fs::read(path) { | ||
| 113 | - Ok(d) => d, | ||
| 114 | - Err(e) => { | ||
| 115 | - row.detail = format!("read error: {e}"); | ||
| 116 | - return row; | ||
| 117 | - } | ||
| 118 | - }; | ||
| 119 | - let reference = std::fs::read(path.with_extension("yuv")).ok(); | ||
| 120 | - // A `<name>_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It | ||
| 121 | - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a | ||
| 122 | - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). | ||
| 123 | - let whole_output = Some(candidate_digests(path)).filter(|d| !d.is_empty()); | ||
| 124 | - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); | ||
| 125 | - let mut whole_output_checked = 0usize; | ||
| 126 | - | ||
| 127 | - let started = std::time::Instant::now(); | ||
| 128 | - let mut dec = Decoder::new(); | ||
| 129 | - let mut out_index = 0usize; | ||
| 130 | - let mut first: Option<String> = None; | ||
| 131 | - let mut handle = |frame: ec_h265::dec::Frame| { | ||
| 132 | - let index = out_index; | ||
| 133 | - out_index += 1; | ||
| 134 | - if whole_output.is_some() { | ||
| 135 | - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); | ||
| 136 | - } | ||
| 137 | - let Some(expected) = frame.meta.picture_hash.as_ref() else { | ||
| 138 | - if whole_output.is_some() { | ||
| 139 | - whole_output_checked += 1; | ||
| 140 | - return; | ||
| 141 | - } | ||
| 142 | - // No hash SEI: the frame is checked against the reference YUV, when there is one. | ||
| 143 | - if let Some(reference) = reference.as_deref() { | ||
| 144 | - let want = cropped_bytes(&frame.picture, &frame.window); | ||
| 145 | - let start = index * want.len(); | ||
| 146 | - row.checked += 1; | ||
| 147 | - if reference.get(start..start + want.len()) == Some(&want[..]) { | ||
| 148 | - row.exact += 1; | ||
| 149 | - } else if first.is_none() { | ||
| 150 | - let at = (0..3) | ||
| 151 | - .find_map(|plane| { | ||
| 152 | - let d = | ||
| 153 | - describe(Some(reference), index, &frame.picture, frame.poc, plane); | ||
| 154 | - (!d.contains("no sample differs")).then_some(d) | ||
| 155 | - }) | ||
| 156 | - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); | ||
| 157 | - first = Some(format!("{at} (reference YUV, cropped)")); | ||
| 158 | - } | ||
| 159 | - row.by_reference = true; | ||
| 160 | - } | ||
| 161 | - return; | ||
| 162 | - }; | ||
| 163 | - row.checked += 1; | ||
| 164 | - let pic = &*frame.picture; | ||
| 165 | - let mut exact = true; | ||
| 166 | - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { | ||
| 167 | - if ok { | ||
| 168 | - continue; | ||
| 169 | - } | ||
| 170 | - exact = false; | ||
| 171 | - if first.is_none() { | ||
| 172 | - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; | ||
| 173 | - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); | ||
| 174 | - first = Some(format!("{at} slices={kind}")); | ||
| 175 | - } | ||
| 176 | - } | ||
| 177 | - if exact { | ||
| 178 | - row.exact += 1; | ||
| 179 | - } | ||
| 180 | - }; | ||
| 181 | - // Frames are drained after every NAL unit, so the output of a long stream is not held. | ||
| 182 | - for unit in nal_chunks(&data) { | ||
| 183 | - if let Err(e) = dec.decode_annex_b(unit) { | ||
| 184 | - row.detail = format!("error: {e}"); | ||
| 185 | - return row; | ||
| 186 | - } | ||
| 187 | - while let Some(frame) = dec.next_frame() { | ||
| 188 | - handle(frame); | ||
| 189 | - } | ||
| 190 | - } | ||
| 191 | - if let Err(e) = dec.flush() { | ||
| 192 | - row.detail = format!("error: {e}"); | ||
| 193 | - return row; | ||
| 194 | - } | ||
| 195 | - row.accepted = "yes"; | ||
| 196 | - while let Some(frame) = dec.next_frame() { | ||
| 197 | - handle(frame); | ||
| 198 | - } | ||
| 199 | - row.decode_secs = started.elapsed().as_secs_f64(); | ||
| 200 | - if let Some(want) = whole_output.as_ref().filter(|_| whole_output_checked > 0) { | ||
| 201 | - let got = whole_output_md5.finish(); | ||
| 202 | - row.checked += whole_output_checked; | ||
| 203 | - if want.contains(&got) { | ||
| 204 | - row.exact += whole_output_checked; | ||
| 205 | - } else { | ||
| 206 | - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); | ||
| 207 | - first.get_or_insert(format!( | ||
| 208 | - "whole-output MD5 {hex} differs from {name}_md5.txt" | ||
| 209 | - )); | ||
| 210 | - } | ||
| 211 | - row.by_reference = true; | ||
| 212 | - } | ||
| 213 | - row.detail = match (first, row.checked) { | ||
| 214 | - (Some(f), _) => format!("first mismatch {f}"), | ||
| 215 | - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), | ||
| 216 | - (None, _) if whole_output.is_some() && whole_output_checked > 0 => { | ||
| 217 | - "ok (whole-output MD5 from the conformance package)".to_string() | ||
| 218 | - } | ||
| 219 | - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), | ||
| 220 | - (None, _) => "ok".to_string(), | ||
| 221 | - }; | ||
| 222 | - row | ||
| 223 | -} | ||
| 224 | - | ||
| 225 | -#[test] | ||
| 226 | -fn rext_conformance_pictures_match_the_sei_hash() { | ||
| 227 | - let root = jctvc_root(); | ||
| 228 | - let streams = streams(); | ||
| 229 | - assert!( | ||
| 230 | - !streams.is_empty(), | ||
| 231 | - "no conformance streams under {}", | ||
| 232 | - root.display() | ||
| 233 | - ); | ||
| 234 | - | ||
| 235 | - let mut rows = Vec::new(); | ||
| 236 | - for path in &streams { | ||
| 237 | - let name = path | ||
| 238 | - .file_stem() | ||
| 239 | - .map(|s| s.to_string_lossy().into_owned()) | ||
| 240 | - .unwrap_or_default(); | ||
| 241 | - eprintln!("stream {name}"); | ||
| 242 | - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); | ||
| 243 | - let mut row = match outcome { | ||
| 244 | - Ok(row) => row, | ||
| 245 | - Err(payload) => { | ||
| 246 | - let msg = payload | ||
| 247 | - .downcast_ref::<&str>() | ||
| 248 | - .map(|s| s.to_string()) | ||
| 249 | - .or_else(|| payload.downcast_ref::<String>().cloned()) | ||
| 250 | - .unwrap_or_default(); | ||
| 251 | - Row { | ||
| 252 | - name: name.clone(), | ||
| 253 | - accepted: "panic", | ||
| 254 | - checked: 0, | ||
| 255 | - exact: 0, | ||
| 256 | - detail: format!("panic: {msg}"), | ||
| 257 | - by_reference: false, | ||
| 258 | - decode_secs: 0.0, | ||
| 259 | - } | ||
| 260 | - } | ||
| 261 | - }; | ||
| 262 | - row.detail = row.detail.replace(['\t', '\n'], " "); | ||
| 263 | - rows.push(row); | ||
| 264 | - } | ||
| 265 | - | ||
| 266 | - let mut table = | ||
| 267 | - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); | ||
| 268 | - for r in &rows { | ||
| 269 | - println!( | ||
| 270 | - "{} | {} | {} | {} | {} | {:.2}s", | ||
| 271 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 272 | - ); | ||
| 273 | - table.push_str(&format!( | ||
| 274 | - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", | ||
| 275 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 276 | - )); | ||
| 277 | - } | ||
| 278 | - let checked: usize = rows.iter().map(|r| r.checked).sum(); | ||
| 279 | - let exact: usize = rows.iter().map(|r| r.exact).sum(); | ||
| 280 | - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); | ||
| 281 | - println!( | ||
| 282 | - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", | ||
| 283 | - rows.len() | ||
| 284 | - ); | ||
| 285 | - let report = std::env::var("EC_H265_REXT_REPORT") | ||
| 286 | - .ok() | ||
| 287 | - .filter(|p| !p.is_empty()); | ||
| 288 | - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); | ||
| 289 | - if let Some(Err((path, e))) = written { | ||
| 290 | - eprintln!("could not write report {path}: {e}"); | ||
| 291 | - } | ||
| 292 | - | ||
| 293 | - // Every accepted stream must be fully exact; a refusal must name a tool in REFUSED. | ||
| 294 | - let failing: Vec<String> = rows | ||
| 295 | - .iter() | ||
| 296 | - .filter(|r| r.accepted == "yes" && (r.checked == 0 || r.exact != r.checked)) | ||
| 297 | - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) | ||
| 298 | - .collect(); | ||
| 299 | - assert!( | ||
| 300 | - failing.is_empty(), | ||
| 301 | - "accepted streams that are not exact:\n{}", | ||
| 302 | - failing.join("\n") | ||
| 303 | - ); | ||
| 304 | - let unexpected: Vec<String> = rows | ||
| 305 | - .iter() | ||
| 306 | - .filter(|r| r.accepted != "yes") | ||
| 307 | - .filter(|r| !REFUSED.iter().any(|name| r.detail.contains(name))) | ||
| 308 | - .map(|r| format!("{} ({}: {})", r.name, r.accepted, r.detail)) | ||
| 309 | - .collect(); | ||
| 310 | - assert!( | ||
| 311 | - unexpected.is_empty(), | ||
| 312 | - "streams refused for a reason not in REFUSED:\n{}", | ||
| 313 | - unexpected.join("\n") | ||
| 314 | - ); | ||
| 315 | -} | ||
| 316 | - | ||
| 317 | -/// The refusals a conformance stream may end in: tools this decoder names and does not decode. | ||
| 318 | -const REFUSED: &[&str] = &[ | ||
| 319 | - "extended_precision_processing_flag", | ||
| 320 | - "cabac_bypass_alignment_enabled_flag", | ||
| 321 | - "high_precision_offsets_enabled_flag", | ||
| 322 | - "bit depth 16", | ||
| 323 | - "bit depth 14", | ||
| 324 | - "bit depth 13", | ||
| 325 | -]; | ||
crates/ec-h265/tests/it/conformance_rext422.rsdeleted+0 -128
| @@ -1,128 +0,0 @@ | |||
| 1 | -//! HEVC RExt 4:2:2 (Main 4:2:2 10 and the 8-bit generated clips) against ffmpeg. | ||
| 2 | -//! | ||
| 3 | -//! The committed 64x64 stream is decoded by ffmpeg at run time and compared sample for | ||
| 4 | -//! sample. The Sony RExt conformance streams and the generated GOP/intra clips live in the | ||
| 5 | - | ||
| 6 | -use std::path::{Path, PathBuf}; | ||
| 7 | - | ||
| 8 | -use ec_h265::Decoder; | ||
| 9 | - | ||
| 10 | -const YUV422_10: &[u8] = include_bytes!("../data/refusals/yuv422_10.265"); | ||
| 11 | - | ||
| 12 | -fn decode(data: &[u8]) -> Vec<ec_h265::decode::DecodedPicture> { | ||
| 13 | - let mut dec = Decoder::new(); | ||
| 14 | - dec.decode_annex_b(data).expect("decode"); | ||
| 15 | - dec.flush().expect("flush"); | ||
| 16 | - let mut out = Vec::new(); | ||
| 17 | - while let Some(f) = dec.next_frame() { | ||
| 18 | - out.push((*f.picture).clone()); | ||
| 19 | - } | ||
| 20 | - out | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -/// The first coded-size-cropped `w` x `h` window of every picture, as planar little-endian | ||
| 24 | -/// samples (one byte per sample at 8 bit, two above), the layout of ffmpeg's rawvideo. | ||
| 25 | -fn raw(pictures: &[ec_h265::decode::DecodedPicture], w: usize, h: usize) -> Vec<u8> { | ||
| 26 | - let mut out = Vec::new(); | ||
| 27 | - for p in pictures { | ||
| 28 | - let wide = p.bit_depth > 8; | ||
| 29 | - for (plane, pw, cw) in [ | ||
| 30 | - (&p.y, p.width, w), | ||
| 31 | - (&p.cb, p.width / 2, w / 2), | ||
| 32 | - (&p.cr, p.width / 2, w / 2), | ||
| 33 | - ] { | ||
| 34 | - for y in 0..h { | ||
| 35 | - for x in 0..cw { | ||
| 36 | - let v = plane[y * pw + x]; | ||
| 37 | - if wide { | ||
| 38 | - out.extend_from_slice(&v.to_le_bytes()); | ||
| 39 | - } else { | ||
| 40 | - out.push(v as u8); | ||
| 41 | - } | ||
| 42 | - } | ||
| 43 | - } | ||
| 44 | - } | ||
| 45 | - } | ||
| 46 | - out | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> { | ||
| 50 | - if a.len() != b.len() { | ||
| 51 | - return Some(a.len().min(b.len())); | ||
| 52 | - } | ||
| 53 | - a.iter().zip(b).position(|(x, y)| x != y) | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -fn ffmpeg_422_10(src: &Path, reference: &Path) { | ||
| 57 | - let st = ec_testkit::ffmpeg() | ||
| 58 | - .args(["-v", "error", "-y", "-i"]) | ||
| 59 | - .arg(src) | ||
| 60 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv422p10le"]) | ||
| 61 | - .arg(reference) | ||
| 62 | - .status() | ||
| 63 | - .unwrap(); | ||
| 64 | - assert!(st.success(), "ffmpeg failed on {}", src.display()); | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -#[test] | ||
| 68 | -fn committed_422_stream_matches_ffmpeg() { | ||
| 69 | - let dir = std::env::temp_dir().join("ec-h265-rext422"); | ||
| 70 | - std::fs::create_dir_all(&dir).unwrap(); | ||
| 71 | - let src = dir.join("yuv422_10.265"); | ||
| 72 | - let reference = dir.join("yuv422_10.yuv"); | ||
| 73 | - std::fs::write(&src, YUV422_10).unwrap(); | ||
| 74 | - ffmpeg_422_10(&src, &reference); | ||
| 75 | - let want = std::fs::read(&reference).unwrap(); | ||
| 76 | - let got = raw(&decode(YUV422_10), 64, 64); | ||
| 77 | - assert_eq!( | ||
| 78 | - first_diff(&got, &want), | ||
| 79 | - None, | ||
| 80 | - "4:2:2 10-bit differs from ffmpeg" | ||
| 81 | - ); | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -fn rext_root() -> PathBuf { | ||
| 85 | - ec_testkit::fixture("vectors/hevc-rext") | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -fn find_stream(dir: &Path) -> Option<PathBuf> { | ||
| 89 | - for e in std::fs::read_dir(dir).ok()?.flatten() { | ||
| 90 | - let p = e.path(); | ||
| 91 | - if p.is_dir() { | ||
| 92 | - if let Some(f) = find_stream(&p) { | ||
| 93 | - return Some(f); | ||
| 94 | - } | ||
| 95 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 96 | - return Some(p); | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - None | ||
| 100 | -} | ||
| 101 | - | ||
| 102 | -#[test] | ||
| 103 | -fn rext_422_vectors_are_byte_exact() { | ||
| 104 | - let root = rext_root(); | ||
| 105 | - let dir = std::env::temp_dir().join("ec-h265-rext422-vectors"); | ||
| 106 | - std::fs::create_dir_all(&dir).unwrap(); | ||
| 107 | - let mut checked = 0; | ||
| 108 | - for (name, w, h) in [ | ||
| 109 | - ("GENERAL_10b_422_RExt_Sony_1", 400, 384), | ||
| 110 | - ("Main_422_10_A_RExt_Sony_2", 1920, 1080), | ||
| 111 | - ("Main_422_10_B_RExt_Sony_2", 2560, 1600), | ||
| 112 | - ] { | ||
| 113 | - let stream = find_stream(&root.join(name)).unwrap_or_else(|| panic!("{name}: no stream")); | ||
| 114 | - let reference = dir.join(format!("{name}.yuv")); | ||
| 115 | - ffmpeg_422_10(&stream, &reference); | ||
| 116 | - let data = std::fs::read(&stream).unwrap_or_else(|e| panic!("{}: {e}", stream.display())); | ||
| 117 | - let want = std::fs::read(&reference).unwrap(); | ||
| 118 | - let got = raw(&decode(&data), w, h); | ||
| 119 | - assert_eq!( | ||
| 120 | - first_diff(&got, &want), | ||
| 121 | - None, | ||
| 122 | - "{} differs from ffmpeg", | ||
| 123 | - stream.display() | ||
| 124 | - ); | ||
| 125 | - checked += 1; | ||
| 126 | - } | ||
| 127 | - eprintln!("4:2:2 vectors checked byte-exact: {checked}"); | ||
| 128 | -} | ||
crates/ec-h265/tests/it/cu_syntax.rsdeleted+0 -130
| @@ -1,130 +0,0 @@ | |||
| 1 | -//! CU syntax tests over the JCT-VC conformance streams: the P/B slice syntax with the | ||
| 2 | -//! zero-motion stand-in (the sweep, pixel-pipeline and motion-determinism tests were removed by | ||
| 3 | -//! testcut Phase 2). | ||
| 4 | - | ||
| 5 | -use ec_core::error::Error; | ||
| 6 | -use ec_h265::dec::Decoder; | ||
| 7 | -use std::path::{Path, PathBuf}; | ||
| 8 | - | ||
| 9 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each directory | ||
| 10 | -fn streams() -> Vec<PathBuf> { | ||
| 11 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 12 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 13 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 14 | - return; | ||
| 15 | - }; | ||
| 16 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 17 | - paths.sort(); | ||
| 18 | - for p in paths { | ||
| 19 | - if p.is_dir() && depth > 0 { | ||
| 20 | - bitstreams_in(&p, depth - 1, out); | ||
| 21 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 22 | - out.push(p); | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 27 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 28 | - dirs.sort(); | ||
| 29 | - dirs.into_iter() | ||
| 30 | - .filter(|d| d.is_dir()) | ||
| 31 | - .filter_map(|d| { | ||
| 32 | - let mut found = Vec::new(); | ||
| 33 | - bitstreams_in(&d, 2, &mut found); | ||
| 34 | - found.into_iter().next() | ||
| 35 | - }) | ||
| 36 | - .collect() | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -/// Split an Annex-B byte stream into NAL units (header included, start codes and | ||
| 40 | -/// trailing zero bytes removed). | ||
| 41 | -fn nal_units(data: &[u8]) -> Vec<&[u8]> { | ||
| 42 | - let mut starts = Vec::new(); | ||
| 43 | - let mut i = 0; | ||
| 44 | - while i + 3 <= data.len() { | ||
| 45 | - if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { | ||
| 46 | - starts.push(i + 3); | ||
| 47 | - i += 3; | ||
| 48 | - } else { | ||
| 49 | - i += 1; | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - let mut out = Vec::new(); | ||
| 53 | - for (k, &s) in starts.iter().enumerate() { | ||
| 54 | - let mut e = starts.get(k + 1).map_or(data.len(), |&next| next - 3); | ||
| 55 | - while e > s && data[e - 1] == 0 { | ||
| 56 | - e -= 1; | ||
| 57 | - } | ||
| 58 | - if e > s { | ||
| 59 | - out.push(&data[s..e]); | ||
| 60 | - } | ||
| 61 | - } | ||
| 62 | - out | ||
| 63 | -} | ||
| 64 | - | ||
| 65 | -/// Whether a NAL unit is a coded slice segment (types 0 to 9 and 16 to 21). | ||
| 66 | -fn is_slice(nal: &[u8]) -> bool { | ||
| 67 | - let t = (nal[0] >> 1) & 0x3f; | ||
| 68 | - t <= 9 || (16..=21).contains(&t) | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -/// The P/B slice syntax ([`ec_h265::dec::cu_syntax::parse_slice`] with the zero-motion | ||
| 72 | -/// stand-in, no DPB to derive motion from) over every P and B slice segment of every | ||
| 73 | -/// stream. Pixel decode is off so the decoder only keeps parameter sets. Refusals are | ||
| 74 | -/// fine; any other error is a failure. | ||
| 75 | -#[test] | ||
| 76 | -fn inter_placeholder_runs_over_pb_slices() { | ||
| 77 | - use ec_core::bitio::BitReader; | ||
| 78 | - use ec_h265_syntax::nal::{NalUnitType, unescape_rbsp}; | ||
| 79 | - use ec_h265_syntax::slice::{SliceHeader, SliceType}; | ||
| 80 | - let streams = streams(); | ||
| 81 | - assert!(!streams.is_empty(), "no conformance streams"); | ||
| 82 | - let (mut pb_slices, mut decoded, mut refused) = (0usize, 0usize, 0usize); | ||
| 83 | - for path in &streams { | ||
| 84 | - let data = std::fs::read(path).expect("read bitstream"); | ||
| 85 | - let mut dec = Decoder::new(); | ||
| 86 | - dec.set_pixel_decode(false); | ||
| 87 | - for nal in nal_units(&data) { | ||
| 88 | - let code = (nal[0] >> 1) & 0x3f; | ||
| 89 | - if is_slice(nal) { | ||
| 90 | - let rbsp = unescape_rbsp(&nal[2..]); | ||
| 91 | - let mut r = BitReader::new(&rbsp); | ||
| 92 | - let _first = r.read_bit(); | ||
| 93 | - if (16..=21).contains(&code) { | ||
| 94 | - let _no_output_of_prior_pics = r.read_bit(); | ||
| 95 | - } | ||
| 96 | - let pps_id = r.read_ue().unwrap_or(u32::MAX); | ||
| 97 | - if let Some(pps) = dec.pps(pps_id) | ||
| 98 | - && let Some(sps) = dec.sps(pps.sps_id) | ||
| 99 | - && let Ok((header, pos)) = | ||
| 100 | - SliceHeader::parse(&rbsp, sps, pps, NalUnitType::from_code(code)) | ||
| 101 | - && header.slice_type != SliceType::I | ||
| 102 | - && header.first_slice_segment_in_pic | ||
| 103 | - { | ||
| 104 | - pb_slices += 1; | ||
| 105 | - let off = (pos.header_bits / 8) as usize; | ||
| 106 | - let slice_data = rbsp.get(off..).unwrap_or(&[]); | ||
| 107 | - let mut zero = ec_h265::dec::cu_syntax::ZeroMotion; | ||
| 108 | - match ec_h265::dec::cu_syntax::parse_slice( | ||
| 109 | - sps, | ||
| 110 | - pps, | ||
| 111 | - &header, | ||
| 112 | - slice_data, | ||
| 113 | - &mut zero, | ||
| 114 | - &mut |_| {}, | ||
| 115 | - ) { | ||
| 116 | - Ok(_) => decoded += 1, | ||
| 117 | - Err(Error::Unsupported { .. }) => refused += 1, | ||
| 118 | - Err(err) => { | ||
| 119 | - panic!("{}: P/B placeholder failed: {err}", path.display()) | ||
| 120 | - } | ||
| 121 | - } | ||
| 122 | - } | ||
| 123 | - } | ||
| 124 | - let _ = dec.push_nal(nal); | ||
| 125 | - } | ||
| 126 | - } | ||
| 127 | - println!( | ||
| 128 | - "inter syntax: {decoded} P/B slices parsed, {refused} refused by name, of {pb_slices} first-slice P/B segments" | ||
| 129 | - ); | ||
| 130 | -} | ||
crates/ec-h265/tests/it/dec_meta.rsdeleted+0 -244
| @@ -1,244 +0,0 @@ | |||
| 1 | -//! Metadata on the decoder's output frames: HDR SEI from the IRAP on, the VUI | ||
| 2 | -//! colour description, the decoded picture hash, and the rule that Dolby Vision | ||
| 3 | -//! NAL units (62, 63) and malformed SEI change nothing. | ||
| 4 | -//! | ||
| 5 | -//! The streams come from `fixtures/vectors/hevc-jctvc`. Without them the tests | ||
| 6 | - | ||
| 7 | -use std::path::{Path, PathBuf}; | ||
| 8 | - | ||
| 9 | -use ec_h265::dec::{Decoder, Frame}; | ||
| 10 | -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; | ||
| 11 | -use ec_h265_syntax::sei::{ContentLightLevel, MasteringDisplay, PictureHash}; | ||
| 12 | - | ||
| 13 | -fn stream_files() -> Vec<PathBuf> { | ||
| 14 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 15 | - fn walk(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 16 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 17 | - return; | ||
| 18 | - }; | ||
| 19 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 20 | - paths.sort(); | ||
| 21 | - for p in paths { | ||
| 22 | - if p.is_dir() && depth > 0 { | ||
| 23 | - walk(&p, depth - 1, out); | ||
| 24 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 25 | - out.push(p); | ||
| 26 | - } | ||
| 27 | - } | ||
| 28 | - } | ||
| 29 | - let mut out = Vec::new(); | ||
| 30 | - walk(&root, 2, &mut out); | ||
| 31 | - out | ||
| 32 | -} | ||
| 33 | - | ||
| 34 | -/// The raw NAL units (two-byte header and escaped payload) of an Annex-B stream. | ||
| 35 | -fn raw_nals(data: &[u8]) -> Vec<Vec<u8>> { | ||
| 36 | - split_annex_b(data) | ||
| 37 | - .iter() | ||
| 38 | - .map(|n| { | ||
| 39 | - let mut v = n.header.to_bytes().to_vec(); | ||
| 40 | - v.extend_from_slice(n.payload); | ||
| 41 | - v | ||
| 42 | - }) | ||
| 43 | - .collect() | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -/// Decode with picture management only, returning every frame, or the first error. | ||
| 47 | -fn decode(nals: &[Vec<u8>]) -> Result<Vec<Frame>, String> { | ||
| 48 | - let mut dec = Decoder::new(); | ||
| 49 | - dec.set_pixel_decode(false); | ||
| 50 | - for nal in nals { | ||
| 51 | - dec.push_nal(nal).map_err(|e| e.to_string())?; | ||
| 52 | - } | ||
| 53 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 54 | - let mut frames = Vec::new(); | ||
| 55 | - while let Some(f) = dec.next_frame() { | ||
| 56 | - frames.push(f); | ||
| 57 | - } | ||
| 58 | - Ok(frames) | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -/// The first conformance stream that decodes without error, with its NAL units. | ||
| 62 | -fn clean_stream() -> Option<(String, Vec<Vec<u8>>)> { | ||
| 63 | - for path in stream_files() { | ||
| 64 | - let Ok(data) = std::fs::read(&path) else { | ||
| 65 | - continue; | ||
| 66 | - }; | ||
| 67 | - let nals = raw_nals(&data); | ||
| 68 | - if decode(&nals).is_ok() { | ||
| 69 | - let name = path | ||
| 70 | - .file_name() | ||
| 71 | - .unwrap_or_default() | ||
| 72 | - .to_string_lossy() | ||
| 73 | - .to_string(); | ||
| 74 | - return Some((name, nals)); | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - None | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -fn require_stream() -> (String, Vec<Vec<u8>>) { | ||
| 81 | - clean_stream().expect("no clean conformance stream") | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -/// What a frame looks like to a caller, for comparing two decodes. | ||
| 85 | -fn key(f: &Frame) -> (i32, u32, usize, usize, Vec<u16>, Vec<u16>, Vec<u16>) { | ||
| 86 | - ( | ||
| 87 | - f.poc, | ||
| 88 | - f.au_index, | ||
| 89 | - f.picture.width, | ||
| 90 | - f.picture.height, | ||
| 91 | - f.picture.y.clone(), | ||
| 92 | - f.picture.cb.clone(), | ||
| 93 | - f.picture.cr.clone(), | ||
| 94 | - ) | ||
| 95 | -} | ||
| 96 | - | ||
| 97 | -/// A NAL unit of the given type, with the payload escaped. | ||
| 98 | -fn nal_unit(nal_type: u8, rbsp: &[u8]) -> Vec<u8> { | ||
| 99 | - let mut v = vec![nal_type << 1, 1]; | ||
| 100 | - escape_rbsp(rbsp, &mut v); | ||
| 101 | - v | ||
| 102 | -} | ||
| 103 | - | ||
| 104 | -fn is_vcl(nal: &[u8]) -> bool { | ||
| 105 | - matches!((nal[0] >> 1) & 0x3f, 0..=21) | ||
| 106 | -} | ||
| 107 | - | ||
| 108 | -/// The HDR10 mastering display of a 1000 nit, 0.0050 nit BT.2020 grade, then a | ||
| 109 | -/// content light level of MaxCLL 1000 and MaxFALL 400, as one prefix SEI RBSP. | ||
| 110 | -fn hdr10_prefix_rbsp() -> Vec<u8> { | ||
| 111 | - let mut mdcv = Vec::new(); | ||
| 112 | - for (x, y) in [ | ||
| 113 | - (8500u16, 39_850u16), | ||
| 114 | - (6550, 2300), | ||
| 115 | - (35_400, 14_600), | ||
| 116 | - (15_635, 16_450), | ||
| 117 | - ] { | ||
| 118 | - mdcv.extend_from_slice(&x.to_be_bytes()); | ||
| 119 | - mdcv.extend_from_slice(&y.to_be_bytes()); | ||
| 120 | - } | ||
| 121 | - mdcv.extend_from_slice(&10_000_000u32.to_be_bytes()); | ||
| 122 | - mdcv.extend_from_slice(&50u32.to_be_bytes()); | ||
| 123 | - let mut rbsp = vec![137, 24]; | ||
| 124 | - rbsp.extend_from_slice(&mdcv); | ||
| 125 | - rbsp.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90, 0x80]); | ||
| 126 | - rbsp | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -#[test] | ||
| 130 | -fn dolby_vision_nal_units_change_nothing() { | ||
| 131 | - let (name, nals) = require_stream(); | ||
| 132 | - let base = decode(&nals).unwrap(); | ||
| 133 | - let mut injected = Vec::new(); | ||
| 134 | - for nal in &nals { | ||
| 135 | - injected.push(vec![62 << 1, 1, 0xde, 0xad, 0xbe, 0xef]); | ||
| 136 | - injected.push(vec![63 << 1, 1, 0x80]); | ||
| 137 | - injected.push(nal.clone()); | ||
| 138 | - } | ||
| 139 | - let with_rpu = decode(&injected).unwrap(); | ||
| 140 | - assert!(!base.is_empty(), "{name}: no frames"); | ||
| 141 | - assert_eq!(base.len(), with_rpu.len(), "{name}: frame count changed"); | ||
| 142 | - for (a, b) in base.iter().zip(&with_rpu) { | ||
| 143 | - assert_eq!( | ||
| 144 | - key(a), | ||
| 145 | - key(b), | ||
| 146 | - "{name}: a frame changed with type 62/63 NAL units" | ||
| 147 | - ); | ||
| 148 | - } | ||
| 149 | -} | ||
| 150 | - | ||
| 151 | -#[test] | ||
| 152 | -fn malformed_sei_is_skipped_and_the_stream_decodes_the_same() { | ||
| 153 | - let (name, nals) = require_stream(); | ||
| 154 | - let base = decode(&nals).unwrap(); | ||
| 155 | - let mut injected = Vec::new(); | ||
| 156 | - for nal in &nals { | ||
| 157 | - // A message that runs past the RBSP, a suffix SEI with a reserved hash type, | ||
| 158 | - // and one with a short mastering display payload. | ||
| 159 | - injected.push(nal_unit(39, &[5, 9, 1, 2, 0x80])); | ||
| 160 | - injected.push(nal_unit(40, &[132, 2, 3, 0, 0x80])); | ||
| 161 | - let mut short_mdcv = vec![137, 23]; | ||
| 162 | - short_mdcv.extend_from_slice(&[0; 23]); | ||
| 163 | - short_mdcv.push(0x80); | ||
| 164 | - injected.push(nal_unit(39, &short_mdcv)); | ||
| 165 | - injected.push(nal.clone()); | ||
| 166 | - } | ||
| 167 | - let with_bad = decode(&injected).unwrap(); | ||
| 168 | - assert_eq!(base.len(), with_bad.len(), "{name}: frame count changed"); | ||
| 169 | - for (a, b) in base.iter().zip(&with_bad) { | ||
| 170 | - assert_eq!(key(a), key(b), "{name}: a frame changed with malformed SEI"); | ||
| 171 | - assert!( | ||
| 172 | - b.mastering_display().is_none(), | ||
| 173 | - "{name}: a malformed SEI produced metadata" | ||
| 174 | - ); | ||
| 175 | - } | ||
| 176 | -} | ||
| 177 | - | ||
| 178 | -#[test] | ||
| 179 | -fn hdr_sei_applies_to_every_frame_from_the_irap_on() { | ||
| 180 | - let (name, nals) = require_stream(); | ||
| 181 | - let mut injected = Vec::new(); | ||
| 182 | - let mut placed = false; | ||
| 183 | - for nal in &nals { | ||
| 184 | - if !placed && is_vcl(nal) { | ||
| 185 | - // A prefix SEI in the first access unit, before its first slice. | ||
| 186 | - injected.push(nal_unit(39, &hdr10_prefix_rbsp())); | ||
| 187 | - placed = true; | ||
| 188 | - } | ||
| 189 | - injected.push(nal.clone()); | ||
| 190 | - } | ||
| 191 | - let frames = decode(&injected).unwrap(); | ||
| 192 | - assert!(!frames.is_empty(), "{name}: no frames"); | ||
| 193 | - for f in &frames { | ||
| 194 | - let md: &MasteringDisplay = f.mastering_display().expect("MDCV on every frame"); | ||
| 195 | - assert_eq!(md.display_primaries[0], (8500, 39_850)); | ||
| 196 | - assert_eq!(md.white_point, (15_635, 16_450)); | ||
| 197 | - assert_eq!(md.max_nits(), 1000.0); | ||
| 198 | - assert!((md.min_nits() - 0.005).abs() < 1e-6); | ||
| 199 | - let cll: &ContentLightLevel = f.content_light_level().expect("CLL on every frame"); | ||
| 200 | - assert_eq!( | ||
| 201 | - (cll.max_content_light_level, cll.max_pic_average_light_level), | ||
| 202 | - (1000, 400) | ||
| 203 | - ); | ||
| 204 | - assert_eq!(f.alternative_transfer_characteristics(), None); | ||
| 205 | - } | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -#[test] | ||
| 209 | -fn picture_hash_attaches_to_the_picture_it_follows() { | ||
| 210 | - let (name, nals) = require_stream(); | ||
| 211 | - // One MD5 plane: payloadType 132, payloadSize 17, hash_type 0, the digest. | ||
| 212 | - let digest = [0x5au8; 16]; | ||
| 213 | - let mut hash_rbsp = vec![132, 17, 0]; | ||
| 214 | - hash_rbsp.extend_from_slice(&digest); | ||
| 215 | - hash_rbsp.push(0x80); | ||
| 216 | - | ||
| 217 | - let mut injected = Vec::new(); | ||
| 218 | - let mut placed = false; | ||
| 219 | - for nal in &nals { | ||
| 220 | - injected.push(nal.clone()); | ||
| 221 | - // A suffix SEI right after the first slice: it belongs to access unit 0. | ||
| 222 | - if !placed && is_vcl(nal) { | ||
| 223 | - injected.push(nal_unit(40, &hash_rbsp)); | ||
| 224 | - placed = true; | ||
| 225 | - } | ||
| 226 | - } | ||
| 227 | - let frames = decode(&injected).unwrap(); | ||
| 228 | - assert!(placed, "{name}: no slice NAL unit"); | ||
| 229 | - let first = frames | ||
| 230 | - .iter() | ||
| 231 | - .find(|f| f.au_index == 0) | ||
| 232 | - .expect("access unit 0 is output"); | ||
| 233 | - match first.picture_hash() { | ||
| 234 | - Some(PictureHash::Md5(d)) => assert_eq!(d, &[digest]), | ||
| 235 | - other => panic!("{name}: access unit 0 hash is {other:?}"), | ||
| 236 | - } | ||
| 237 | - assert!( | ||
| 238 | - frames | ||
| 239 | - .iter() | ||
| 240 | - .filter(|f| f.au_index != 0) | ||
| 241 | - .all(|f| f.picture_hash().is_none()), | ||
| 242 | - "{name}: a hash leaked to another picture" | ||
| 243 | - ); | ||
| 244 | -} | ||
crates/ec-h265/tests/it/dec_shell.rsdeleted+0 -454
| @@ -1,454 +0,0 @@ | |||
| 1 | -//! Picture management of the stateful decoder (`ec_h265::dec`): POC, RPS and | ||
| 2 | -//! marking, bumping, reference lists, and the JCT-VC conformance sweep. | ||
| 3 | -//! | ||
| 4 | -//! The sweep parses every slice of every stream through the picture-management | ||
| 5 | -//! path (pixel decode off) and checks the output order against ffprobe. Streams | ||
| 6 | -//! whose slices are all intra are also pixel-decoded and compared with ffmpeg's | ||
| 7 | - | ||
| 8 | -use std::collections::VecDeque; | ||
| 9 | -use std::path::{Path, PathBuf}; | ||
| 10 | - | ||
| 11 | -use ec_h265::dec::dpb::{Dpb, DpbLimits, Marking, PendingFrame}; | ||
| 12 | -use ec_h265::dec::poc::derive_poc; | ||
| 13 | -use ec_h265::dec::rps::{RpsInput, build_ref_lists}; | ||
| 14 | -use ec_h265::dec::shared::SharedPic; | ||
| 15 | -use ec_h265::dec::{Decoder, NalOutcome}; | ||
| 16 | -use ec_h265::decode::DecodedPicture; | ||
| 17 | -use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType}; | ||
| 18 | -use ec_h265_syntax::{ConformanceWindow, Pps, ShortTermRefPicSet}; | ||
| 19 | - | ||
| 20 | -fn picture(w: usize, h: usize) -> DecodedPicture { | ||
| 21 | - DecodedPicture { | ||
| 22 | - width: w, | ||
| 23 | - height: h, | ||
| 24 | - bit_depth: 8, | ||
| 25 | - bit_depth_c: 8, | ||
| 26 | - chroma_format_idc: 1, | ||
| 27 | - y: Vec::new(), | ||
| 28 | - cb: Vec::new(), | ||
| 29 | - cr: Vec::new(), | ||
| 30 | - } | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -fn st_set(before: &[i32], after: &[i32]) -> ShortTermRefPicSet { | ||
| 34 | - let mut st = ShortTermRefPicSet { | ||
| 35 | - num_negative: before.len() as u32, | ||
| 36 | - num_positive: after.len() as u32, | ||
| 37 | - ..ShortTermRefPicSet::default() | ||
| 38 | - }; | ||
| 39 | - for (i, &d) in before.iter().enumerate() { | ||
| 40 | - st.delta_poc_s0[i] = d; | ||
| 41 | - st.used_s0[i] = true; | ||
| 42 | - } | ||
| 43 | - for (i, &d) in after.iter().enumerate() { | ||
| 44 | - st.delta_poc_s1[i] = d; | ||
| 45 | - st.used_s1[i] = true; | ||
| 46 | - } | ||
| 47 | - st | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -fn rps_input<'a>( | ||
| 51 | - poc: i32, | ||
| 52 | - st: &'a ShortTermRefPicSet, | ||
| 53 | - lt: &'a [LongTermRef], | ||
| 54 | - fill: Option<(u32, u32)>, | ||
| 55 | -) -> RpsInput<'a> { | ||
| 56 | - RpsInput { | ||
| 57 | - poc, | ||
| 58 | - log2_max_poc_lsb: 4, | ||
| 59 | - st, | ||
| 60 | - lt, | ||
| 61 | - irap_no_rasl: false, | ||
| 62 | - width: 16, | ||
| 63 | - height: 16, | ||
| 64 | - chroma_format_idc: 1, | ||
| 65 | - fill, | ||
| 66 | - } | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -fn add(dpb: &mut Dpb, poc: i32, marking: Marking, output: bool) -> u32 { | ||
| 70 | - dpb.insert( | ||
| 71 | - poc, | ||
| 72 | - marking, | ||
| 73 | - output, | ||
| 74 | - std::sync::Arc::new(SharedPic::from_planes(poc, picture(16, 16))), | ||
| 75 | - ConformanceWindow::default(), | ||
| 76 | - poc as u32, | ||
| 77 | - ) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -#[test] | ||
| 81 | -fn poc_follows_the_lsb_without_wrapping() { | ||
| 82 | - assert_eq!(derive_poc(5, 4, 7, false), 7); | ||
| 83 | - assert_eq!(derive_poc(0, 4, 0, false), 0); | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -#[test] | ||
| 87 | -fn poc_msb_wraps_forward_at_the_half_window() { | ||
| 88 | - // prevTid0 = 0, lsb 14 of 16: 14 - 0 > 8, so the MSB is -16 and POC is -2. | ||
| 89 | - assert_eq!(derive_poc(0, 4, 14, false), -2); | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -#[test] | ||
| 93 | -fn poc_msb_wraps_backward_past_the_maximum() { | ||
| 94 | - // prevTid0 = 14 (lsb 14), lsb 2: 14 - 2 >= 8, so the MSB advances to 16. | ||
| 95 | - assert_eq!(derive_poc(14, 4, 2, false), 18); | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -#[test] | ||
| 99 | -fn poc_of_an_irap_with_no_rasl_output_has_no_msb() { | ||
| 100 | - assert_eq!(derive_poc(37, 4, 5, true), 5); | ||
| 101 | -} | ||
| 102 | - | ||
| 103 | -#[test] | ||
| 104 | -fn rps_marks_what_it_names_and_drops_the_rest() { | ||
| 105 | - let mut dpb = Dpb::new(); | ||
| 106 | - let ids: Vec<u32> = [0, 1, 2, 3, 4, 5, 6, 7] | ||
| 107 | - .iter() | ||
| 108 | - .map(|&p| add(&mut dpb, p, Marking::ShortTerm, false)) | ||
| 109 | - .collect(); | ||
| 110 | - // Current POC 8 names 7, 5 and 4 (deltas -1, -3, -4). 0..3 and 6 drop out. | ||
| 111 | - let st = st_set(&[-1, -3, -4], &[]); | ||
| 112 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 113 | - let before: Vec<i32> = set.st_curr_before.iter().map(|e| e.poc).collect(); | ||
| 114 | - assert_eq!(before, vec![7, 5, 4]); | ||
| 115 | - assert!(set.st_curr_after.is_empty()); | ||
| 116 | - assert!(set.lt_curr.is_empty()); | ||
| 117 | - assert_eq!(set.st_curr_before[0].id, ids[7]); | ||
| 118 | - for &p in &[0usize, 1, 2, 3, 6] { | ||
| 119 | - assert_eq!(dpb.get(ids[p]).unwrap().marking, Marking::Unused, "POC {p}"); | ||
| 120 | - } | ||
| 121 | - assert_eq!(dpb.get(ids[5]).unwrap().marking, Marking::ShortTerm); | ||
| 122 | - dpb.remove_unneeded(); | ||
| 123 | - assert_eq!(dpb.len(), 3); | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -#[test] | ||
| 127 | -fn rps_generates_a_missing_reference_as_grey() { | ||
| 128 | - let mut dpb = Dpb::new(); | ||
| 129 | - add(&mut dpb, 4, Marking::ShortTerm, false); | ||
| 130 | - // Current POC 8 names POC 6 (absent) and POC 4. | ||
| 131 | - let st = st_set(&[-2, -4], &[]); | ||
| 132 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 133 | - assert_eq!(set.st_curr_before.len(), 2); | ||
| 134 | - let generated = dpb | ||
| 135 | - .get(set.st_curr_before[0].id) | ||
| 136 | - .expect("generated picture"); | ||
| 137 | - assert_eq!(generated.poc, 6); | ||
| 138 | - assert!(!generated.needed_for_output); | ||
| 139 | - let planes = generated.picture.read_planes(); | ||
| 140 | - assert_eq!(planes.y.len(), 16 * 16); | ||
| 141 | - assert!(planes.y.iter().all(|&v| v == 128)); | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -#[test] | ||
| 145 | -fn rps_long_term_entry_matches_by_lsb_and_converts_marking() { | ||
| 146 | - let mut dpb = Dpb::new(); | ||
| 147 | - let lt_id = add(&mut dpb, 16, Marking::ShortTerm, false); | ||
| 148 | - // PocLsbLt 0 with no MSB: the picture with POC & 15 == 0 is POC 16. | ||
| 149 | - let lt = [LongTermRef { | ||
| 150 | - poc_lsb_lt: 0, | ||
| 151 | - used_by_curr: true, | ||
| 152 | - delta_poc_msb_present: false, | ||
| 153 | - delta_poc_msb_cycle: 0, | ||
| 154 | - }]; | ||
| 155 | - let st = ShortTermRefPicSet::default(); | ||
| 156 | - let set = dpb.apply_rps(&rps_input(20, &st, <, Some((8, 8)))); | ||
| 157 | - assert_eq!(set.lt_curr.len(), 1); | ||
| 158 | - assert_eq!(set.lt_curr[0].id, lt_id); | ||
| 159 | - assert!(set.lt_curr[0].long_term); | ||
| 160 | - assert_eq!(dpb.get(lt_id).unwrap().marking, Marking::LongTerm); | ||
| 161 | -} | ||
| 162 | - | ||
| 163 | -#[test] | ||
| 164 | -fn bumping_outputs_in_poc_order_under_the_reorder_limit() { | ||
| 165 | - let limits = DpbLimits { | ||
| 166 | - max_dec_pic_buffering: 6, | ||
| 167 | - max_num_reorder: 2, | ||
| 168 | - max_latency_plus1: 0, | ||
| 169 | - }; | ||
| 170 | - let mut dpb = Dpb::new(); | ||
| 171 | - let mut out: VecDeque<PendingFrame> = VecDeque::new(); | ||
| 172 | - // Decode order 0, 8, 4, 2: a reorder limit of 2 forces output as it goes. | ||
| 173 | - for poc in [0, 8, 4, 2] { | ||
| 174 | - add(&mut dpb, poc, Marking::Unused, true); | ||
| 175 | - while dpb.needs_bumping(&limits, false) && dpb.bump(&mut out) {} | ||
| 176 | - } | ||
| 177 | - let early: Vec<i32> = out.iter().map(|f| f.poc).collect(); | ||
| 178 | - assert_eq!(early, vec![0, 2]); | ||
| 179 | - dpb.drain(&mut out); | ||
| 180 | - let all: Vec<i32> = out.iter().map(|f| f.poc).collect(); | ||
| 181 | - assert_eq!(all, vec![0, 2, 4, 8]); | ||
| 182 | - assert!(dpb.is_empty()); | ||
| 183 | -} | ||
| 184 | - | ||
| 185 | -#[test] | ||
| 186 | -fn bumping_honours_the_latency_limit() { | ||
| 187 | - let limits = DpbLimits { | ||
| 188 | - max_dec_pic_buffering: 6, | ||
| 189 | - max_num_reorder: 4, | ||
| 190 | - max_latency_plus1: 1, | ||
| 191 | - }; | ||
| 192 | - let mut dpb = Dpb::new(); | ||
| 193 | - let mut out = VecDeque::new(); | ||
| 194 | - add(&mut dpb, 0, Marking::Unused, true); | ||
| 195 | - assert!(!dpb.needs_bumping(&limits, false)); | ||
| 196 | - // SpsMaxLatencyPictures = 4 + 1 - 1 = 4: a picture that waited 4 times goes out. | ||
| 197 | - dpb.pictures_mut()[0].latency = 4; | ||
| 198 | - assert!(dpb.needs_bumping(&limits, false)); | ||
| 199 | - assert!(dpb.bump(&mut out)); | ||
| 200 | - assert_eq!(out.len(), 1); | ||
| 201 | -} | ||
| 202 | - | ||
| 203 | -#[test] | ||
| 204 | -fn bumping_drops_a_full_buffer_only_when_asked() { | ||
| 205 | - let limits = DpbLimits { | ||
| 206 | - max_dec_pic_buffering: 2, | ||
| 207 | - max_num_reorder: 8, | ||
| 208 | - max_latency_plus1: 0, | ||
| 209 | - }; | ||
| 210 | - let mut dpb = Dpb::new(); | ||
| 211 | - add(&mut dpb, 0, Marking::ShortTerm, false); | ||
| 212 | - add(&mut dpb, 2, Marking::ShortTerm, false); | ||
| 213 | - assert!(dpb.needs_bumping(&limits, true)); | ||
| 214 | - assert!(!dpb.needs_bumping(&limits, false)); | ||
| 215 | -} | ||
| 216 | - | ||
| 217 | -#[test] | ||
| 218 | -fn reference_lists_cycle_and_follow_the_modification() { | ||
| 219 | - let mut dpb = Dpb::new(); | ||
| 220 | - let a = add(&mut dpb, 4, Marking::ShortTerm, false); | ||
| 221 | - let b = add(&mut dpb, 6, Marking::ShortTerm, false); | ||
| 222 | - let c = add(&mut dpb, 10, Marking::ShortTerm, false); | ||
| 223 | - let st = st_set(&[-4, -2], &[2]); | ||
| 224 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 225 | - assert_eq!( | ||
| 226 | - set.st_curr_before.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 227 | - vec![a, b] | ||
| 228 | - ); | ||
| 229 | - assert_eq!( | ||
| 230 | - set.st_curr_after.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 231 | - vec![c] | ||
| 232 | - ); | ||
| 233 | - | ||
| 234 | - let pps = Pps::default(); | ||
| 235 | - let mut header = SliceHeader::intra(&pps, 0); | ||
| 236 | - header.slice_type = SliceType::B; | ||
| 237 | - header.num_ref_idx_l0_active_minus1 = 3; | ||
| 238 | - header.num_ref_idx_l1_active_minus1 = 1; | ||
| 239 | - let lists = build_ref_lists(&set, &header).expect("lists"); | ||
| 240 | - let l0: Vec<u32> = lists.l0.iter().map(|e| e.id).collect(); | ||
| 241 | - assert_eq!(l0, vec![a, b, c, a]); | ||
| 242 | - let l1: Vec<u32> = lists.l1.iter().map(|e| e.id).collect(); | ||
| 243 | - assert_eq!(l1, vec![c, a]); | ||
| 244 | - | ||
| 245 | - header.list_entry = [vec![2, 2, 0, 1], vec![1, 0]]; | ||
| 246 | - let lists = build_ref_lists(&set, &header).expect("modified lists"); | ||
| 247 | - assert_eq!( | ||
| 248 | - lists.l0.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 249 | - vec![c, c, a, b] | ||
| 250 | - ); | ||
| 251 | - assert_eq!( | ||
| 252 | - lists.l1.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 253 | - vec![a, c] | ||
| 254 | - ); | ||
| 255 | -} | ||
| 256 | - | ||
| 257 | -#[test] | ||
| 258 | -fn decoder_refuses_out_of_scope_parameter_sets_and_skips_layers() { | ||
| 259 | - let mut dec = Decoder::new(); | ||
| 260 | - // A VPS-typed NAL on layer 1 is skipped whatever its payload. | ||
| 261 | - let layer1 = [32u8 << 1, 0b0000_1001, 0xff]; | ||
| 262 | - assert_eq!(dec.push_nal(&layer1).unwrap(), NalOutcome::Skipped); | ||
| 263 | - // SEI and filler are ignored. | ||
| 264 | - assert_eq!( | ||
| 265 | - dec.push_nal(&[39 << 1, 1, 0x80]).unwrap(), | ||
| 266 | - NalOutcome::Skipped | ||
| 267 | - ); | ||
| 268 | - assert_eq!( | ||
| 269 | - dec.push_nal(&[62 << 1, 1, 0x80]).unwrap(), | ||
| 270 | - NalOutcome::Skipped | ||
| 271 | - ); | ||
| 272 | - assert!(dec.next_frame().is_none()); | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -fn run(args: &[&str], file: &Path) -> Result<Vec<u8>, String> { | ||
| 276 | - let out = ec_testkit::ffprobe() | ||
| 277 | - .args(["-v", "error"]) | ||
| 278 | - .args(args) | ||
| 279 | - .arg(file) | ||
| 280 | - .output() | ||
| 281 | - .map_err(|e| e.to_string())?; | ||
| 282 | - if !out.status.success() { | ||
| 283 | - return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); | ||
| 284 | - } | ||
| 285 | - Ok(out.stdout) | ||
| 286 | -} | ||
| 287 | - | ||
| 288 | -fn numbers(text: &[u8]) -> Vec<u64> { | ||
| 289 | - String::from_utf8_lossy(text) | ||
| 290 | - .lines() | ||
| 291 | - .filter_map(|l| l.trim().trim_end_matches(',').parse().ok()) | ||
| 292 | - .collect() | ||
| 293 | -} | ||
| 294 | - | ||
| 295 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 296 | -/// by name. Some zips extract one directory deeper, so two levels are searched. | ||
| 297 | -fn streams() -> Vec<PathBuf> { | ||
| 298 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 299 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 300 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 301 | - return; | ||
| 302 | - }; | ||
| 303 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 304 | - paths.sort(); | ||
| 305 | - for p in paths { | ||
| 306 | - if p.is_dir() && depth > 0 { | ||
| 307 | - bitstreams_in(&p, depth - 1, out); | ||
| 308 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 309 | - out.push(p); | ||
| 310 | - } | ||
| 311 | - } | ||
| 312 | - } | ||
| 313 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 314 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 315 | - dirs.sort(); | ||
| 316 | - dirs.into_iter() | ||
| 317 | - .filter(|d| d.is_dir()) | ||
| 318 | - .filter_map(|d| { | ||
| 319 | - let mut found = Vec::new(); | ||
| 320 | - bitstreams_in(&d, 2, &mut found); | ||
| 321 | - found.into_iter().next() | ||
| 322 | - }) | ||
| 323 | - .collect() | ||
| 324 | -} | ||
| 325 | - | ||
| 326 | -/// Output order from our decoder, picture management only: (POC, AU index). | ||
| 327 | -fn our_order(data: &[u8]) -> Result<Vec<(i32, u32)>, String> { | ||
| 328 | - let mut dec = Decoder::new(); | ||
| 329 | - dec.set_pixel_decode(false); | ||
| 330 | - dec.decode_annex_b(data).map_err(|e| e.to_string())?; | ||
| 331 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 332 | - let mut order = Vec::new(); | ||
| 333 | - while let Some(f) = dec.next_frame() { | ||
| 334 | - order.push((f.poc, f.au_index)); | ||
| 335 | - } | ||
| 336 | - Ok(order) | ||
| 337 | -} | ||
| 338 | - | ||
| 339 | -/// Output order from ffprobe: the access-unit index (by packet position in | ||
| 340 | -/// decode order) of each frame, in display order. | ||
| 341 | -fn ffprobe_order(path: &Path) -> Result<Vec<u32>, String> { | ||
| 342 | - let packets = numbers(&run( | ||
| 343 | - &[ | ||
| 344 | - "-select_streams", | ||
| 345 | - "v:0", | ||
| 346 | - "-show_entries", | ||
| 347 | - "packet=pos", | ||
| 348 | - "-of", | ||
| 349 | - "csv=p=0", | ||
| 350 | - ], | ||
| 351 | - path, | ||
| 352 | - )?); | ||
| 353 | - let frames = numbers(&run( | ||
| 354 | - &[ | ||
| 355 | - "-select_streams", | ||
| 356 | - "v:0", | ||
| 357 | - "-show_entries", | ||
| 358 | - "frame=pkt_pos", | ||
| 359 | - "-of", | ||
| 360 | - "csv=p=0", | ||
| 361 | - ], | ||
| 362 | - path, | ||
| 363 | - )?); | ||
| 364 | - frames | ||
| 365 | - .iter() | ||
| 366 | - .map(|pos| { | ||
| 367 | - packets | ||
| 368 | - .iter() | ||
| 369 | - .position(|p| p == pos) | ||
| 370 | - .map(|i| i as u32) | ||
| 371 | - .ok_or_else(|| format!("frame position {pos} is no packet position")) | ||
| 372 | - }) | ||
| 373 | - .collect() | ||
| 374 | -} | ||
| 375 | - | ||
| 376 | -/// Streams where ffprobe is not the reference: the spec's frame count (from the | ||
| 377 | -/// conformance description) and why ffprobe differs. Our count must equal the spec's. | ||
| 378 | -fn spec_expectation(name: &str) -> Option<(usize, &'static str)> { | ||
| 379 | - match name { | ||
| 380 | - // Unequal luma (10) and chroma (9) bit depth: ffmpeg decodes nothing. | ||
| 381 | - "TSUNEQBD_A_MAIN10_Technicolor_2" => Some((8, "ffmpeg unsupported (unequal bit depths)")), | ||
| 382 | - // Six IDR pictures, each with its own VPS/SPS/PPS and resolution: ffmpeg outputs 2. | ||
| 383 | - "VPSSPSPPS_A_MainConcept_1" => Some((6, "ffmpeg outputs 2")), | ||
| 384 | - _ => None, | ||
| 385 | - } | ||
| 386 | -} | ||
| 387 | - | ||
| 388 | -#[test] | ||
| 389 | -fn conformance_output_order_matches_ffprobe() { | ||
| 390 | - let streams = streams(); | ||
| 391 | - assert!(!streams.is_empty(), "no conformance streams"); | ||
| 392 | - let mut table = String::from("stream\tpictures_out\tffprobe_out\tresult\tdetail\n"); | ||
| 393 | - let mut pass = 0usize; | ||
| 394 | - let mut spec_ok = 0usize; | ||
| 395 | - for path in &streams { | ||
| 396 | - let name = path | ||
| 397 | - .file_stem() | ||
| 398 | - .unwrap_or_default() | ||
| 399 | - .to_string_lossy() | ||
| 400 | - .to_string(); | ||
| 401 | - let data = match std::fs::read(path) { | ||
| 402 | - Ok(d) => d, | ||
| 403 | - Err(e) => { | ||
| 404 | - table.push_str(&format!("{name}\t-\t-\tFAIL\tread: {e}\n")); | ||
| 405 | - continue; | ||
| 406 | - } | ||
| 407 | - }; | ||
| 408 | - let ours = our_order(&data); | ||
| 409 | - let theirs = ffprobe_order(path); | ||
| 410 | - let row = match (ours, theirs) { | ||
| 411 | - (Ok(ours), Ok(theirs)) => { | ||
| 412 | - let our_aus: Vec<u32> = ours.iter().map(|(_, au)| *au).collect(); | ||
| 413 | - let pocs: Vec<String> = ours.iter().take(8).map(|(p, _)| p.to_string()).collect(); | ||
| 414 | - let detail = format!("first POCs {}", pocs.join(",")); | ||
| 415 | - match spec_expectation(&name) { | ||
| 416 | - // The spec's own count is the reference where ffprobe is wrong. | ||
| 417 | - Some((frames, why)) => { | ||
| 418 | - let verdict = if ours.len() == frames { "SPEC" } else { "FAIL" }; | ||
| 419 | - if verdict == "SPEC" { | ||
| 420 | - spec_ok += 1; | ||
| 421 | - } | ||
| 422 | - format!( | ||
| 423 | - "{name}\t{}\t{}\t{verdict}\tspec: {frames} frames, {why}; {detail}\n", | ||
| 424 | - ours.len(), | ||
| 425 | - theirs.len(), | ||
| 426 | - ) | ||
| 427 | - } | ||
| 428 | - None => { | ||
| 429 | - let verdict = if our_aus == theirs { "PASS" } else { "FAIL" }; | ||
| 430 | - if verdict == "PASS" { | ||
| 431 | - pass += 1; | ||
| 432 | - } | ||
| 433 | - format!( | ||
| 434 | - "{name}\t{}\t{}\t{verdict}\t{detail}\n", | ||
| 435 | - ours.len(), | ||
| 436 | - theirs.len(), | ||
| 437 | - ) | ||
| 438 | - } | ||
| 439 | - } | ||
| 440 | - } | ||
| 441 | - (Err(e), _) => format!("{name}\t-\t-\tREFUSED\t{e}\n"), | ||
| 442 | - (_, Err(e)) => format!("{name}\t-\t-\tSKIP\tffprobe: {e}\n"), | ||
| 443 | - }; | ||
| 444 | - table.push_str(&row); | ||
| 445 | - } | ||
| 446 | - match std::env::var("EC_H265_POC_TABLE") { | ||
| 447 | - Ok(path) => std::fs::write(&path, &table).expect("write POC table"), | ||
| 448 | - Err(_) => print!("{table}"), | ||
| 449 | - } | ||
| 450 | - eprintln!( | ||
| 451 | - "POC/output order: {pass}/{} streams PASS, {spec_ok} SPEC (spec frame count, ffprobe differs)", | ||
| 452 | - streams.len() | ||
| 453 | - ); | ||
| 454 | -} | ||
crates/ec-h265/tests/it/dolby_vision_p8.rsdeleted+0 -197
| @@ -1,197 +0,0 @@ | |||
| 1 | -//! Dolby Vision profile 8 layout: the HEVC base layer decodes, and the RPU NAL | ||
| 2 | -//! units (type 62) are ignored. | ||
| 3 | -//! | ||
| 4 | -//! The base layer is generated here with ffmpeg's libx265 from a test pattern, so no | ||
| 5 | -//! copyrighted media is involved. Type 62 NAL units with arbitrary payload are then | ||
| 6 | -//! inserted in front of every VCL NAL unit. ec-h265 must decode the injected stream | ||
| 7 | -//! to exactly the pictures it decodes from the clean one, and ffmpeg must decode the | ||
| 8 | -//! injected stream to the same bytes. | ||
| 9 | - | ||
| 10 | -use ec_h265::Decoder; | ||
| 11 | -use ec_h265::dec::Frame; | ||
| 12 | -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; | ||
| 13 | -use std::path::Path; | ||
| 14 | - | ||
| 15 | -const WIDTH: usize = 352; | ||
| 16 | -const HEIGHT: usize = 288; | ||
| 17 | -const FRAMES: usize = 12; | ||
| 18 | - | ||
| 19 | -/// The base layer: libx265, an IDR every 4 pictures, P pictures in between, no B. | ||
| 20 | -fn encode_base_layer(dir: &Path) -> Result<Vec<u8>, String> { | ||
| 21 | - let out = dir.join("base.hevc"); | ||
| 22 | - let frames = FRAMES.to_string(); | ||
| 23 | - let source = format!("testsrc2=size={WIDTH}x{HEIGHT}:rate=30"); | ||
| 24 | - let status = ec_testkit::ffmpeg() | ||
| 25 | - .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) | ||
| 26 | - .arg(&source) | ||
| 27 | - .arg("-frames:v") | ||
| 28 | - .arg(&frames) | ||
| 29 | - .args([ | ||
| 30 | - "-c:v", "libx265", "-preset", "veryfast", "-pix_fmt", "yuv420p", | ||
| 31 | - ]) | ||
| 32 | - .args([ | ||
| 33 | - "-x265-params", | ||
| 34 | - "keyint=4:min-keyint=4:bframes=0:scenecut=0:log-level=error", | ||
| 35 | - "-f", | ||
| 36 | - "hevc", | ||
| 37 | - ]) | ||
| 38 | - .arg(&out) | ||
| 39 | - .output() | ||
| 40 | - .map_err(|e| e.to_string())?; | ||
| 41 | - if !status.status.success() { | ||
| 42 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 43 | - } | ||
| 44 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -/// A type 62 NAL unit with arbitrary payload: zero runs, start-code-like bytes and | ||
| 48 | -/// a trailing zero, escaped as a NAL unit must be. `seed` varies it per slice. | ||
| 49 | -fn rpu_nal(seed: u8) -> Vec<u8> { | ||
| 50 | - let rbsp = [ | ||
| 51 | - 0x19, 0x08, 0x00, 0x00, 0x01, seed, 0x00, 0x00, 0x03, 0xff, 0x80, 0x00, | ||
| 52 | - ]; | ||
| 53 | - let mut v = vec![62 << 1, 1]; | ||
| 54 | - escape_rbsp(&rbsp, &mut v); | ||
| 55 | - v | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -/// The stream with a type 62 NAL unit in front of every VCL NAL unit, each with | ||
| 59 | -/// a four-byte start code. | ||
| 60 | -fn inject_rpu(annex_b: &[u8]) -> Vec<u8> { | ||
| 61 | - let mut out = Vec::with_capacity(annex_b.len() * 2); | ||
| 62 | - let mut slice = 0u8; | ||
| 63 | - for n in split_annex_b(annex_b) { | ||
| 64 | - let mut nal = n.header.to_bytes().to_vec(); | ||
| 65 | - nal.extend_from_slice(n.payload); | ||
| 66 | - if matches!((nal[0] >> 1) & 0x3f, 0..=21) { | ||
| 67 | - out.extend_from_slice(&[0, 0, 0, 1]); | ||
| 68 | - out.extend_from_slice(&rpu_nal(slice)); | ||
| 69 | - slice = slice.wrapping_add(1); | ||
| 70 | - } | ||
| 71 | - out.extend_from_slice(&[0, 0, 0, 1]); | ||
| 72 | - out.extend_from_slice(&nal); | ||
| 73 | - } | ||
| 74 | - out | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -/// Count of NAL units of `nal_type` in an Annex B stream. | ||
| 78 | -fn count_nal_type(annex_b: &[u8], nal_type: u8) -> usize { | ||
| 79 | - split_annex_b(annex_b) | ||
| 80 | - .iter() | ||
| 81 | - .filter(|n| (n.header.to_bytes()[0] >> 1) & 0x3f == nal_type) | ||
| 82 | - .count() | ||
| 83 | -} | ||
| 84 | - | ||
| 85 | -/// One picture as 4:2:0 bytes, cropped to the conformance window. | ||
| 86 | -fn cropped_yuv(frame: &Frame) -> Vec<u8> { | ||
| 87 | - let pic = &frame.picture; | ||
| 88 | - let win = &frame.window; | ||
| 89 | - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); | ||
| 90 | - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); | ||
| 91 | - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); | ||
| 92 | - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); | ||
| 93 | - let mut out = Vec::new(); | ||
| 94 | - for row in ly0..ly1 { | ||
| 95 | - out.extend( | ||
| 96 | - pic.y[row * pic.width + lx0..row * pic.width + lx1] | ||
| 97 | - .iter() | ||
| 98 | - .map(|&v| v as u8), | ||
| 99 | - ); | ||
| 100 | - } | ||
| 101 | - let cw = pic.width / 2; | ||
| 102 | - for plane in [&pic.cb, &pic.cr] { | ||
| 103 | - for row in cy0..cy1 { | ||
| 104 | - out.extend( | ||
| 105 | - plane[row * cw + cx0..row * cw + cx1] | ||
| 106 | - .iter() | ||
| 107 | - .map(|&v| v as u8), | ||
| 108 | - ); | ||
| 109 | - } | ||
| 110 | - } | ||
| 111 | - out | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -/// Every picture ec-h265 outputs, as one yuv420p byte string, and the picture count. | ||
| 115 | -fn decode_ec(annex_b: &[u8]) -> Result<(Vec<u8>, usize), String> { | ||
| 116 | - let mut dec = Decoder::new(); | ||
| 117 | - dec.decode_annex_b(annex_b).map_err(|e| e.to_string())?; | ||
| 118 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 119 | - let mut out = Vec::new(); | ||
| 120 | - let mut count = 0; | ||
| 121 | - while let Some(frame) = dec.next_frame() { | ||
| 122 | - out.extend(cropped_yuv(&frame)); | ||
| 123 | - count += 1; | ||
| 124 | - } | ||
| 125 | - Ok((out, count)) | ||
| 126 | -} | ||
| 127 | - | ||
| 128 | -/// Every picture ffmpeg outputs, as yuv420p. | ||
| 129 | -fn decode_ffmpeg(path: &Path, out: &Path) -> Result<Vec<u8>, String> { | ||
| 130 | - let status = ec_testkit::ffmpeg() | ||
| 131 | - .args(["-v", "error", "-y", "-i"]) | ||
| 132 | - .arg(path) | ||
| 133 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 134 | - .arg(out) | ||
| 135 | - .output() | ||
| 136 | - .map_err(|e| e.to_string())?; | ||
| 137 | - if !status.status.success() { | ||
| 138 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 139 | - } | ||
| 140 | - std::fs::read(out).map_err(|e| e.to_string()) | ||
| 141 | -} | ||
| 142 | - | ||
| 143 | -fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> { | ||
| 144 | - a.iter() | ||
| 145 | - .zip(b) | ||
| 146 | - .position(|(x, y)| x != y) | ||
| 147 | - .or_else(|| (a.len() != b.len()).then(|| a.len().min(b.len()))) | ||
| 148 | -} | ||
| 149 | - | ||
| 150 | -#[test] | ||
| 151 | -fn dolby_vision_p8_base_layer_decodes_and_rpu_is_ignored() { | ||
| 152 | - let dir = std::env::temp_dir().join(format!("ec-h265-dvp8-{}", std::process::id())); | ||
| 153 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 154 | - | ||
| 155 | - let clean = encode_base_layer(&dir).expect("libx265 base layer"); | ||
| 156 | - let injected = inject_rpu(&clean); | ||
| 157 | - let vcl = split_annex_b(&clean) | ||
| 158 | - .iter() | ||
| 159 | - .filter(|n| matches!((n.header.to_bytes()[0] >> 1) & 0x3f, 0..=21)) | ||
| 160 | - .count(); | ||
| 161 | - assert_eq!( | ||
| 162 | - count_nal_type(&clean, 62), | ||
| 163 | - 0, | ||
| 164 | - "clean base layer has type 62 NAL units" | ||
| 165 | - ); | ||
| 166 | - assert_eq!( | ||
| 167 | - count_nal_type(&injected, 62), | ||
| 168 | - vcl, | ||
| 169 | - "one type 62 NAL unit per slice" | ||
| 170 | - ); | ||
| 171 | - | ||
| 172 | - let (ec_clean, n_clean) = decode_ec(&clean).expect("ec-h265 decodes the clean base layer"); | ||
| 173 | - let (ec_injected, n_injected) = | ||
| 174 | - decode_ec(&injected).expect("ec-h265 decodes the stream with type 62 NAL units"); | ||
| 175 | - assert_eq!(n_clean, FRAMES, "clean stream picture count"); | ||
| 176 | - assert_eq!(n_injected, FRAMES, "injected stream picture count"); | ||
| 177 | - let frame_bytes = WIDTH * HEIGHT * 3 / 2; | ||
| 178 | - assert_eq!(ec_clean.len(), FRAMES * frame_bytes); | ||
| 179 | - if let Some(at) = first_difference(&ec_clean, &ec_injected) { | ||
| 180 | - panic!("type 62 NAL units changed ec-h265's output at byte {at}"); | ||
| 181 | - } | ||
| 182 | - | ||
| 183 | - let injected_path = dir.join("dv-p8.hevc"); | ||
| 184 | - std::fs::write(&injected_path, &injected).expect("write injected stream"); | ||
| 185 | - let ffmpeg = decode_ffmpeg(&injected_path, &dir.join("ffmpeg.yuv")) | ||
| 186 | - .expect("ffmpeg decodes the injected stream"); | ||
| 187 | - assert_eq!( | ||
| 188 | - ffmpeg.len(), | ||
| 189 | - ec_injected.len(), | ||
| 190 | - "ffmpeg picture bytes differ from ec-h265's" | ||
| 191 | - ); | ||
| 192 | - if let Some(at) = first_difference(&ec_injected, &ffmpeg) { | ||
| 193 | - panic!("ec-h265 and ffmpeg differ on the injected stream at byte {at}"); | ||
| 194 | - } | ||
| 195 | - | ||
| 196 | - let _ = std::fs::remove_dir_all(&dir); | ||
| 197 | -} | ||
crates/ec-h265/tests/it/encode.rsdeleted+0 -922
| @@ -1,922 +0,0 @@ | |||
| 1 | -//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched | ||
| 2 | -//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`. | ||
| 3 | -//! | ||
| 4 | -//! Both encoders code the same synthetic 352x288 24-picture clip, both are read | ||
| 5 | -//! the same way — on ffmpeg's decode of the stream, not on either encoder's | ||
| 6 | -//! own reconstruction — and x265's psychovisual and adaptive tools are off so | ||
| 7 | -//! the comparison is at matched features, not at matched marketing. | ||
| 8 | - | ||
| 9 | -use crate::common::{pin_loud, pin_or_bail}; | ||
| 10 | -use ec_core::frame::VideoFrame; | ||
| 11 | -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; | ||
| 12 | - | ||
| 13 | -/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. | ||
| 14 | -type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); | ||
| 15 | - | ||
| 16 | -/// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the | ||
| 17 | -/// measured value with 0.15 dB of room for platform noise, so the advantage can | ||
| 18 | -/// shrink but not grow unnoticed; it is not a claim that the number is fine. | ||
| 19 | -/// | ||
| 20 | -/// Measured +2.507 dB luma / +3.238 dB YUV at `rdo_candidates: 5` (352x288, | ||
| 21 | -/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder | ||
| 22 | -/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through | ||
| 23 | -/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a | ||
| 24 | -/// smooth-gradient result: it does NOT hold on real content, where our | ||
| 25 | -/// encoder is no leaner than x265 at matched QP (the probe measures a shift of | ||
| 26 | -/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after | ||
| 27 | -/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides: | ||
| 28 | -/// • 3840x1608 film: -0.685 dB luma / -0.703 dB YUV | ||
| 29 | -/// • 1138x640 web clip: -0.507 dB luma / -0.556 dB YUV | ||
| 30 | -/// • 2560x1440 screen capture: -2.465 dB luma / -2.360 dB YUV | ||
| 31 | -/// • 1080p phone clip: -0.366 dB luma / -0.387 dB YUV | ||
| 32 | -/// Those two are the real gap to close; the synthetic number only guards | ||
| 33 | -/// against regression on a clip whose content is pinned. | ||
| 34 | -/// | ||
| 35 | -/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; | ||
| 36 | -/// that number was meaningless because the two curves' bitrate ranges did not | ||
| 37 | -/// overlap (50% extrapolation on our side) — a fixed QP offset could not | ||
| 38 | -/// bridge encoders whose relative leanness varies with content. The shallow | ||
| 39 | -/// all-intra rate-quality slope is genuine content behaviour (x264 forced | ||
| 40 | -/// all-intra shows the same shape); the fix is to auto-align the ladders from | ||
| 41 | -/// a probe encode, not to change x265's rate control. | ||
| 42 | -const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; | ||
| 43 | - | ||
| 44 | -/// A synthetic source with real structure: smooth gradients, a band of | ||
| 45 | -/// sinusoidal texture and a translating box, so prediction matters — the half | ||
| 46 | -/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip` | ||
| 47 | -/// (minus the `view()` method this encoder's `encode_idr_planes` does not | ||
| 48 | -/// need). | ||
| 49 | -struct Clip { | ||
| 50 | - w: usize, | ||
| 51 | - h: usize, | ||
| 52 | - y: Vec<u8>, | ||
| 53 | - u: Vec<u8>, | ||
| 54 | - v: Vec<u8>, | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -impl Clip { | ||
| 58 | - fn new(w: usize, h: usize) -> Clip { | ||
| 59 | - Clip { | ||
| 60 | - w, | ||
| 61 | - h, | ||
| 62 | - y: vec![0; w * h], | ||
| 63 | - u: vec![0; w / 2 * h / 2], | ||
| 64 | - v: vec![0; w / 2 * h / 2], | ||
| 65 | - } | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - /// Frame `t` without a per-sample noise field: smooth gradients, a band of | ||
| 69 | - /// sinusoidal texture and a box translating by whole and sub-sample | ||
| 70 | - /// amounts. Content where prediction matters, not where residual is | ||
| 71 | - /// incompressible. | ||
| 72 | - fn render_smooth(&mut self, t: usize) { | ||
| 73 | - let (w, h) = (self.w, self.h); | ||
| 74 | - let ft = t as f64; | ||
| 75 | - for y in 0..h { | ||
| 76 | - for x in 0..w { | ||
| 77 | - let (fx, fy) = (x as f64, y as f64); | ||
| 78 | - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; | ||
| 79 | - let texture = if y > h / 3 && y < 2 * h / 3 { | ||
| 80 | - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) | ||
| 81 | - } else { | ||
| 82 | - 0.0 | ||
| 83 | - }; | ||
| 84 | - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); | ||
| 85 | - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; | ||
| 86 | - let v = if inside { | ||
| 87 | - 196.0 - texture * 0.5 | ||
| 88 | - } else { | ||
| 89 | - 40.0 + (ramp % 90.0).abs() + texture | ||
| 90 | - }; | ||
| 91 | - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; | ||
| 92 | - } | ||
| 93 | - } | ||
| 94 | - for y in 0..h / 2 { | ||
| 95 | - for x in 0..w / 2 { | ||
| 96 | - let (fx, fy) = (x as f64, y as f64); | ||
| 97 | - self.u[y * (w / 2) + x] = | ||
| 98 | - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; | ||
| 99 | - self.v[y * (w / 2) + x] = | ||
| 100 | - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction. | ||
| 107 | -fn planes_of(frame: &VideoFrame) -> Planes { | ||
| 108 | - let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 109 | - let mut out = Vec::new(); | ||
| 110 | - for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] | ||
| 111 | - .into_iter() | ||
| 112 | - .enumerate() | ||
| 113 | - { | ||
| 114 | - let plane = &frame.planes[i]; | ||
| 115 | - let mut buf = Vec::with_capacity(pw * ph); | ||
| 116 | - for row in 0..ph { | ||
| 117 | - buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | ||
| 118 | - } | ||
| 119 | - out.push(buf); | ||
| 120 | - } | ||
| 121 | - let v = out.pop().unwrap(); | ||
| 122 | - let u = out.pop().unwrap(); | ||
| 123 | - let y = out.pop().unwrap(); | ||
| 124 | - (y, u, v) | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -/// Mean squared error between two equal-length planes. | ||
| 128 | -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { | ||
| 129 | - a.iter() | ||
| 130 | - .zip(b) | ||
| 131 | - .map(|(&x, &y)| { | ||
| 132 | - let d = f64::from(x) - f64::from(y); | ||
| 133 | - d * d | ||
| 134 | - }) | ||
| 135 | - .sum::<f64>() | ||
| 136 | - / a.len() as f64 | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | -/// PSNR over all three planes, pooled by sample count the way x265 reports it: | ||
| 140 | -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number | ||
| 141 | -/// rewards an encoder for throwing chroma away, so any decision that can move | ||
| 142 | -/// chroma bits is read here instead. | ||
| 143 | -fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { | ||
| 144 | - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); | ||
| 145 | - let sse = | ||
| 146 | - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; | ||
| 147 | - let mse = sse / (n_y + 2.0 * n_c); | ||
| 148 | - if mse == 0.0 { | ||
| 149 | - 99.0 | ||
| 150 | - } else { | ||
| 151 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 152 | - } | ||
| 153 | -} | ||
| 154 | - | ||
| 155 | -fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 156 | - let mse: f64 = a | ||
| 157 | - .iter() | ||
| 158 | - .zip(b) | ||
| 159 | - .map(|(&x, &y)| { | ||
| 160 | - let d = f64::from(x) - f64::from(y); | ||
| 161 | - d * d | ||
| 162 | - }) | ||
| 163 | - .sum::<f64>() | ||
| 164 | - / a.len() as f64; | ||
| 165 | - if mse == 0.0 { | ||
| 166 | - 99.0 | ||
| 167 | - } else { | ||
| 168 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 169 | - } | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | -#[allow(clippy::needless_range_loop)] | ||
| 173 | -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { | ||
| 174 | - let mut a = [[0.0; 5]; 4]; | ||
| 175 | - for i in 0..4 { | ||
| 176 | - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; | ||
| 177 | - } | ||
| 178 | - for col in 0..4 { | ||
| 179 | - let mut pivot = col; | ||
| 180 | - for row in col + 1..4 { | ||
| 181 | - if a[row][col].abs() > a[pivot][col].abs() { | ||
| 182 | - pivot = row; | ||
| 183 | - } | ||
| 184 | - } | ||
| 185 | - a.swap(col, pivot); | ||
| 186 | - let div = a[col][col]; | ||
| 187 | - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); | ||
| 188 | - for j in col..5 { | ||
| 189 | - a[col][j] /= div; | ||
| 190 | - } | ||
| 191 | - for row in 0..4 { | ||
| 192 | - if row == col { | ||
| 193 | - continue; | ||
| 194 | - } | ||
| 195 | - let f = a[row][col]; | ||
| 196 | - for j in col..5 { | ||
| 197 | - a[row][j] -= f * a[col][j]; | ||
| 198 | - } | ||
| 199 | - } | ||
| 200 | - } | ||
| 201 | - [a[0][4], a[1][4], a[2][4], a[3][4]] | ||
| 202 | -} | ||
| 203 | - | ||
| 204 | -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | ||
| 205 | - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -/// BD-PSNR: average PSNR difference between two rate-quality curves over a | ||
| 209 | -/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one | ||
| 210 | -/// departure: the integration range is the *union* of the two curves' bitrate | ||
| 211 | -/// extents, not their intersection. | ||
| 212 | -/// | ||
| 213 | -/// The h264 gate's encoders land in the same bitrate band at the same QP, so | ||
| 214 | -/// the intersection is non-empty and the standard Bjøntegaard cubic integral | ||
| 215 | -/// over it is well defined. Our h265 encoder's bitrate at matched QP can be | ||
| 216 | -/// leaner or fatter than x265's depending on content, so the QP-ladder shift | ||
| 217 | -/// is measured from a probe encode, not fixed — the union range is kept (not | ||
| 218 | -/// clipped to the intersection) so the extrapolation share can be measured: | ||
| 219 | -/// if either curve is extrapolated over more than 20% of the range, the test | ||
| 220 | -/// fails with a named message instead of reporting a BD number that is a cubic | ||
| 221 | -/// guess, not a measurement. The extrapolation shares are returned alongside | ||
| 222 | -/// the number. | ||
| 223 | -/// | ||
| 224 | -/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the | ||
| 225 | -/// fraction of the integration range that each curve's measured bitrate span | ||
| 226 | -/// does not cover (0 = fully measured, 1 = entirely extrapolated). | ||
| 227 | -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) { | ||
| 228 | - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); | ||
| 229 | - let ys_candidate = std::array::from_fn(|i| candidate[i].1); | ||
| 230 | - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); | ||
| 231 | - let ys_anchor = std::array::from_fn(|i| anchor[i].1); | ||
| 232 | - // Union, not intersection: see the doc comment above. | ||
| 233 | - let lo = xs_candidate | ||
| 234 | - .iter() | ||
| 235 | - .copied() | ||
| 236 | - .fold(f64::INFINITY, f64::min) | ||
| 237 | - .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); | ||
| 238 | - let hi = xs_candidate | ||
| 239 | - .iter() | ||
| 240 | - .copied() | ||
| 241 | - .fold(f64::NEG_INFINITY, f64::max) | ||
| 242 | - .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); | ||
| 243 | - let c_candidate = cubic_fit(xs_candidate, ys_candidate); | ||
| 244 | - let c_anchor = cubic_fit(xs_anchor, ys_anchor); | ||
| 245 | - let (cand_lo, cand_hi) = ( | ||
| 246 | - xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 247 | - xs_candidate | ||
| 248 | - .iter() | ||
| 249 | - .copied() | ||
| 250 | - .fold(f64::NEG_INFINITY, f64::max), | ||
| 251 | - ); | ||
| 252 | - let (anc_lo, anc_hi) = ( | ||
| 253 | - xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 254 | - xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), | ||
| 255 | - ); | ||
| 256 | - let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); | ||
| 257 | - let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); | ||
| 258 | - eprintln!( | ||
| 259 | - " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" | ||
| 260 | - ); | ||
| 261 | - let bd = (cubic_integral(c_candidate, hi) | ||
| 262 | - - cubic_integral(c_candidate, lo) | ||
| 263 | - - cubic_integral(c_anchor, hi) | ||
| 264 | - + cubic_integral(c_anchor, lo)) | ||
| 265 | - / (hi - lo); | ||
| 266 | - (bd, cand_extrap, anc_extrap) | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -fn have_x265() -> bool { | ||
| 270 | - ec_testkit::ffmpeg() | ||
| 271 | - .args(["-v", "error", "-hide_banner", "-encoders"]) | ||
| 272 | - .output() | ||
| 273 | - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) | ||
| 274 | -} | ||
| 275 | - | ||
| 276 | -#[cfg(unix)] | ||
| 277 | -#[test] | ||
| 278 | -fn pin_loud_reds_on_an_ok_but_short_write() { | ||
| 279 | - // The shape the two sites above left open: a write that reports success and | ||
| 280 | - // leaves a file of a different length. A symlink to /dev/null accepts every | ||
| 281 | - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- | ||
| 282 | - // a stream path, silently empty. | ||
| 283 | - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id())); | ||
| 284 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 285 | - let path = dir.join("ok-but-short.265"); | ||
| 286 | - let _ = std::fs::remove_file(&path); | ||
| 287 | - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); | ||
| 288 | - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); | ||
| 289 | - assert!(why.contains(&path.display().to_string()), "{why}"); | ||
| 290 | - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); | ||
| 291 | - std::fs::remove_file(&path).ok(); | ||
| 292 | - | ||
| 293 | - // The control: the same call on a real file succeeds and leaves every byte. | ||
| 294 | - let good = dir.join("whole.265"); | ||
| 295 | - let bytes = vec![7u8; 1234]; | ||
| 296 | - pin_loud("control", &good, &bytes).expect("a whole write is not short"); | ||
| 297 | - assert_eq!(std::fs::read(&good).expect("read back"), bytes); | ||
| 298 | - std::fs::remove_file(&good).ok(); | ||
| 299 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -#[cfg(unix)] | ||
| 303 | -#[test] | ||
| 304 | -fn pin_loud_reports_what_landed_under_a_size_cap() { | ||
| 305 | - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores | ||
| 306 | - // everything up to the cap and only then returns EFBIG. The line must carry | ||
| 307 | - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count | ||
| 308 | - // the writer confirmed, which is zero. | ||
| 309 | - use std::process::Command; | ||
| 310 | - let Ok(exe) = std::env::current_exe() else { | ||
| 311 | - return; | ||
| 312 | - }; | ||
| 313 | - // SIGXFSZ's default action would kill the child before it can print; | ||
| 314 | - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. | ||
| 315 | - let script = format!( | ||
| 316 | - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", | ||
| 317 | - exe.display() | ||
| 318 | - ); | ||
| 319 | - let out = Command::new("sh") | ||
| 320 | - .args(["-c", &script]) | ||
| 321 | - .env("EC_PINLOUD_CHILD", "1") | ||
| 322 | - .output() | ||
| 323 | - .expect("run the capped child"); | ||
| 324 | - let text = format!( | ||
| 325 | - "{}{}", | ||
| 326 | - String::from_utf8_lossy(&out.stdout), | ||
| 327 | - String::from_utf8_lossy(&out.stderr) | ||
| 328 | - ); | ||
| 329 | - assert!(!out.status.success(), "the capped write must fail: {text}"); | ||
| 330 | - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); | ||
| 331 | - assert!( | ||
| 332 | - text.contains("EFBIG") || text.contains("File too large"), | ||
| 333 | - "{text}" | ||
| 334 | - ); | ||
| 335 | -} | ||
| 336 | - | ||
| 337 | -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under | ||
| 338 | -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails | ||
| 339 | -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. | ||
| 340 | -#[test] | ||
| 341 | -fn pin_loud_cap_child() { | ||
| 342 | - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { | ||
| 343 | - return; | ||
| 344 | - } | ||
| 345 | - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id())); | ||
| 346 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 347 | - let path = dir.join("capped.265"); | ||
| 348 | - let why = | ||
| 349 | - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); | ||
| 350 | - std::fs::remove_file(&path).ok(); | ||
| 351 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 352 | - panic!("{why}"); | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture. | ||
| 356 | -fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> { | ||
| 357 | - let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); | ||
| 358 | - std::fs::create_dir_all(&dir).ok()?; | ||
| 359 | - let path = dir.join(format!("s{}.265", stream.len())); | ||
| 360 | - pin_or_bail("ffmpeg_decode", &path, stream)?; | ||
| 361 | - let out = ec_testkit::ffmpeg() | ||
| 362 | - .args(["-v", "error"]) | ||
| 363 | - .arg("-i") | ||
| 364 | - .arg(&path) | ||
| 365 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) | ||
| 366 | - .output() | ||
| 367 | - .ok()?; | ||
| 368 | - let _ = std::fs::remove_file(&path); | ||
| 369 | - if !out.status.success() { | ||
| 370 | - eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); | ||
| 371 | - return None; | ||
| 372 | - } | ||
| 373 | - let frame = w * h * 3 / 2; | ||
| 374 | - if frame == 0 || out.stdout.len() % frame != 0 { | ||
| 375 | - eprintln!( | ||
| 376 | - "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", | ||
| 377 | - out.stdout.len() | ||
| 378 | - ); | ||
| 379 | - return None; | ||
| 380 | - } | ||
| 381 | - Some( | ||
| 382 | - out.stdout | ||
| 383 | - .chunks(frame) | ||
| 384 | - .map(|f| { | ||
| 385 | - let (y, rest) = f.split_at(w * h); | ||
| 386 | - let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 387 | - (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 388 | - }) | ||
| 389 | - .collect(), | ||
| 390 | - ) | ||
| 391 | -} | ||
| 392 | - | ||
| 393 | -/// Encode raw I420 pictures with x265 at constant QP, matched to what this | ||
| 394 | -/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut | ||
| 395 | -/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off, | ||
| 396 | -/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU | ||
| 397 | -/// depth x265 allows (1, the closest it has to our | ||
| 398 | -/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so | ||
| 399 | -/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B | ||
| 400 | -/// stream. | ||
| 401 | -fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> { | ||
| 402 | - let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); | ||
| 403 | - std::fs::create_dir_all(&dir).ok()?; | ||
| 404 | - let raw = dir.join(format!("in-q{qp}.yuv")); | ||
| 405 | - let out = dir.join(format!("out-q{qp}.265")); | ||
| 406 | - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); | ||
| 407 | - for (y, u, v) in sources { | ||
| 408 | - buf.extend_from_slice(y); | ||
| 409 | - buf.extend_from_slice(u); | ||
| 410 | - buf.extend_from_slice(v); | ||
| 411 | - } | ||
| 412 | - pin_or_bail("x265_encode_qp", &raw, &buf)?; | ||
| 413 | - // The param list is the h264 gate's x264 list translated to x265's option | ||
| 414 | - // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off, | ||
| 415 | - // plus the in-loop filters x265 adds and x264 does not have (no-sao, | ||
| 416 | - // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits | ||
| 417 | - // the same way ours does. The quantiser goes inside the param string as | ||
| 418 | - // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce | ||
| 419 | - // byte-identical streams, so the `rc=cqp:` prefix is unnecessary. | ||
| 420 | - // EC_H265_X265_PARAMS appends to attribute a single feature the same way | ||
| 421 | - // EC_H264_X264_PARAMS does. | ||
| 422 | - let params = format!( | ||
| 423 | - "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\ | ||
| 424 | - aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ | ||
| 425 | - pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}", | ||
| 426 | - // x265 deblocks by default; `no-deblock` matches an encoder that does | ||
| 427 | - // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter. | ||
| 428 | - deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") { | ||
| 429 | - "" | ||
| 430 | - } else { | ||
| 431 | - "no-deblock:" | ||
| 432 | - }, | ||
| 433 | - extra = match std::env::var("EC_H265_X265_PARAMS") { | ||
| 434 | - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => | ||
| 435 | - format!(":{}", extra.trim().trim_matches(':')), | ||
| 436 | - _ => String::new(), | ||
| 437 | - } | ||
| 438 | - ); | ||
| 439 | - let status = ec_testkit::ffmpeg() | ||
| 440 | - .args(["-v", "error", "-y"]) | ||
| 441 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 442 | - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) | ||
| 443 | - .arg("-i") | ||
| 444 | - .arg(&raw) | ||
| 445 | - .args(["-c:v", "libx265", "-preset", "medium"]) | ||
| 446 | - .args(["-x265-params", ¶ms]) | ||
| 447 | - .args(["-f", "hevc"]) | ||
| 448 | - .arg(&out) | ||
| 449 | - .status() | ||
| 450 | - .ok()?; | ||
| 451 | - let _ = std::fs::remove_file(&raw); | ||
| 452 | - if !status.success() { | ||
| 453 | - return None; | ||
| 454 | - } | ||
| 455 | - let stream = std::fs::read(&out).ok(); | ||
| 456 | - let _ = std::fs::remove_file(&out); | ||
| 457 | - stream | ||
| 458 | -} | ||
| 459 | - | ||
| 460 | -/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored | ||
| 461 | -/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a | ||
| 462 | -/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the | ||
| 463 | -/// cubic fit interpolates instead of extrapolating — regardless of whether | ||
| 464 | -/// our encoder is leaner or fatter than x265 at matched QP on the content at | ||
| 465 | -/// hand. Runs on the synthetic clip by default, so the number cannot rot | ||
| 466 | -/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the | ||
| 467 | -/// same thing on real content. | ||
| 468 | -/// | ||
| 469 | -/// Both curves are (bits, luma PSNR against the same source pictures), and | ||
| 470 | -/// both are measured on ffmpeg's decode of the stream rather than on an | ||
| 471 | -/// encoder's own reconstruction, so the two halves are read the same way. | ||
| 472 | -/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each | ||
| 473 | -/// chroma 1 for 4:2:0), the way x265 reports it. | ||
| 474 | -/// | ||
| 475 | -/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture | ||
| 476 | -/// EC_H265_CLIP=<file> cargo test --release -p ec-h265 --test encode \ | ||
| 477 | -/// bd_psnr_vs_x265 -- --nocapture | ||
| 478 | -#[test] | ||
| 479 | -fn bd_psnr_vs_x265() { | ||
| 480 | - assert!(have_x265(), "the pinned ffmpeg has no libx265"); | ||
| 481 | - let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { | ||
| 482 | - Some(path) => clip_sources(&path, 24), | ||
| 483 | - None => { | ||
| 484 | - let (w, h, frames) = (352, 288, 24); | ||
| 485 | - let mut clip = Clip::new(w, h); | ||
| 486 | - let mut sources = Vec::with_capacity(frames); | ||
| 487 | - for t in 0..frames { | ||
| 488 | - clip.render_smooth(t); | ||
| 489 | - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); | ||
| 490 | - } | ||
| 491 | - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); | ||
| 492 | - (w, h, sources) | ||
| 493 | - } | ||
| 494 | - }; | ||
| 495 | - | ||
| 496 | - let ours = |qp: i32| { | ||
| 497 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 498 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 499 | - cfg.keep_recon = true; | ||
| 500 | - cfg.threads = 0; | ||
| 501 | - // Ablation knob: how many SATD survivors reach the full rate-distortion | ||
| 502 | - // trial in the luma mode search. The shipped default is 5. | ||
| 503 | - if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { | ||
| 504 | - cfg.chroma_mode_search = v != "0"; | ||
| 505 | - } | ||
| 506 | - if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { | ||
| 507 | - cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); | ||
| 508 | - } | ||
| 509 | - if let Ok(v) = std::env::var("EC_H265_SDH") { | ||
| 510 | - cfg.sign_hiding = v != "0"; | ||
| 511 | - } | ||
| 512 | - if let Ok(v) = std::env::var("EC_H265_RDOQ") { | ||
| 513 | - cfg.rdoq = v != "0"; | ||
| 514 | - } | ||
| 515 | - if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") { | ||
| 516 | - cfg.rdoq_estimate = v != "0"; | ||
| 517 | - } | ||
| 518 | - if let Ok(v) = std::env::var("EC_H265_TSKIP") { | ||
| 519 | - cfg.transform_skip = match v.as_str() { | ||
| 520 | - "0" => TransformSkip::Off, | ||
| 521 | - "always" => TransformSkip::AlwaysFor4x4, | ||
| 522 | - _ => TransformSkip::Rd, | ||
| 523 | - }; | ||
| 524 | - } | ||
| 525 | - if let Ok(v) = std::env::var("EC_H265_NXN") { | ||
| 526 | - cfg.intra_nxn = v != "0"; | ||
| 527 | - } | ||
| 528 | - if let Ok(v) = std::env::var("EC_H265_CTB") { | ||
| 529 | - cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); | ||
| 530 | - } | ||
| 531 | - if let Ok(v) = std::env::var("EC_H265_CU64") { | ||
| 532 | - cfg.cu64 = v != "0"; | ||
| 533 | - } | ||
| 534 | - if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { | ||
| 535 | - cfg.deblock = v != "0"; | ||
| 536 | - } | ||
| 537 | - if let Ok(v) = std::env::var("EC_H265_RQT") { | ||
| 538 | - cfg.rqt = v != "0"; | ||
| 539 | - } | ||
| 540 | - if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { | ||
| 541 | - cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); | ||
| 542 | - } | ||
| 543 | - let enc = Encoder::new(cfg).expect("encoder"); | ||
| 544 | - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); | ||
| 545 | - for (y, u, v) in &sources { | ||
| 546 | - let coded = enc | ||
| 547 | - .encode_idr_planes(y, w, u, w / 2, v, w / 2) | ||
| 548 | - .expect("encode"); | ||
| 549 | - stream.extend_from_slice(&coded.au); | ||
| 550 | - let recon = coded.recon.as_ref().expect("reconstruction"); | ||
| 551 | - let (ry, _ru, _rv) = planes_of(recon); | ||
| 552 | - sum_recon += psnr(y, &ry); | ||
| 553 | - } | ||
| 554 | - // Measured the same way x265 is: on what a decoder shows, not on the | ||
| 555 | - // encoder's own reconstruction. The two are printed together because a | ||
| 556 | - // gap between them is a bug in one of the halves, not a rate-quality | ||
| 557 | - // result. | ||
| 558 | - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); | ||
| 559 | - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); | ||
| 560 | - let n = sources.len() as f64; | ||
| 561 | - let sum: f64 = sources | ||
| 562 | - .iter() | ||
| 563 | - .zip(&decoded) | ||
| 564 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 565 | - .sum(); | ||
| 566 | - let sum_yuv: f64 = sources | ||
| 567 | - .iter() | ||
| 568 | - .zip(&decoded) | ||
| 569 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 570 | - .sum(); | ||
| 571 | - let (sum_u, sum_v) = ( | ||
| 572 | - sources | ||
| 573 | - .iter() | ||
| 574 | - .zip(&decoded) | ||
| 575 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 576 | - .sum::<f64>(), | ||
| 577 | - sources | ||
| 578 | - .iter() | ||
| 579 | - .zip(&decoded) | ||
| 580 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 581 | - .sum::<f64>(), | ||
| 582 | - ); | ||
| 583 | - eprintln!( | ||
| 584 | - " ours qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 585 | - sum_u / n, | ||
| 586 | - sum_v / n | ||
| 587 | - ); | ||
| 588 | - let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); | ||
| 589 | - assert!( | ||
| 590 | - (decoded_psnr - recon_psnr).abs() < 0.05, | ||
| 591 | - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ | ||
| 592 | - stream decodes to {decoded_psnr:.2} dB" | ||
| 593 | - ); | ||
| 594 | - ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) | ||
| 595 | - }; | ||
| 596 | - let x265 = |qp: i32| { | ||
| 597 | - let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); | ||
| 598 | - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); | ||
| 599 | - assert_eq!( | ||
| 600 | - decoded.len(), | ||
| 601 | - sources.len(), | ||
| 602 | - "x265 returned {} pictures for {} sources", | ||
| 603 | - decoded.len(), | ||
| 604 | - sources.len() | ||
| 605 | - ); | ||
| 606 | - let n = sources.len() as f64; | ||
| 607 | - let sum: f64 = sources | ||
| 608 | - .iter() | ||
| 609 | - .zip(&decoded) | ||
| 610 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 611 | - .sum(); | ||
| 612 | - let sum_yuv: f64 = sources | ||
| 613 | - .iter() | ||
| 614 | - .zip(&decoded) | ||
| 615 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 616 | - .sum(); | ||
| 617 | - eprintln!( | ||
| 618 | - " x265 qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 619 | - sources | ||
| 620 | - .iter() | ||
| 621 | - .zip(&decoded) | ||
| 622 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 623 | - .sum::<f64>() | ||
| 624 | - / n, | ||
| 625 | - sources | ||
| 626 | - .iter() | ||
| 627 | - .zip(&decoded) | ||
| 628 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 629 | - .sum::<f64>() | ||
| 630 | - / n | ||
| 631 | - ); | ||
| 632 | - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) | ||
| 633 | - }; | ||
| 634 | - | ||
| 635 | - // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP | ||
| 636 | - // delta measured from a single probe encode, not a constant: both sides | ||
| 637 | - // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP | ||
| 638 | - // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that | ||
| 639 | - // shift. If the extrapolation share still exceeds 20% after measuring, the | ||
| 640 | - // shift is re-estimated from the geometric-mean bit ratio of the two full | ||
| 641 | - // curves and the ladder is rebuilt; once the rates match and the curves | ||
| 642 | - // still do not meet, our ladder is drawn in towards its own centre until | ||
| 643 | - // its bitrate range fits inside the anchor's — at most 8 alignment rounds | ||
| 644 | - // before the existing panic fires. | ||
| 645 | - const EXTRAP_LIMIT: f64 = 0.20; | ||
| 646 | - let x265_qps = [22, 26, 30, 34]; | ||
| 647 | - let probe_qp = 26; | ||
| 648 | - | ||
| 649 | - // Probe both encoders at QP 26 to measure the bit ratio. | ||
| 650 | - let probe_ours = ours(probe_qp); | ||
| 651 | - let probe_x265 = x265(probe_qp); | ||
| 652 | - // A sample window with nothing in it (a film's black head, a fade) codes | ||
| 653 | - // to a handful of bits and decodes back to the source exactly, so every | ||
| 654 | - // point on both curves sits at the PSNR cap and the BD number is a flat | ||
| 655 | - // +0.000 that looks like a measurement. Refuse it by name. | ||
| 656 | - const FLAT_WINDOW_DB: f64 = 90.0; | ||
| 657 | - assert!( | ||
| 658 | - probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB, | ||
| 659 | - "the sample window is flat — both encoders reach the PSNR cap on it \ | ||
| 660 | - (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \ | ||
| 661 | - or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it", | ||
| 662 | - probe_ours.1, | ||
| 663 | - probe_x265.1, | ||
| 664 | - ); | ||
| 665 | - let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; | ||
| 666 | - eprintln!( | ||
| 667 | - "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", | ||
| 668 | - probe_ours.0 / 1e6, | ||
| 669 | - probe_x265.0 / 1e6, | ||
| 670 | - ); | ||
| 671 | - | ||
| 672 | - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { | ||
| 673 | - v.iter() | ||
| 674 | - .map(|&(b, p, y)| (b, if luma { p } else { y })) | ||
| 675 | - .collect() | ||
| 676 | - }; | ||
| 677 | - | ||
| 678 | - // x265 ladder is fixed; reuse the probe for its QP-26 point. | ||
| 679 | - let theirs: Vec<(f64, f64, f64)> = x265_qps | ||
| 680 | - .iter() | ||
| 681 | - .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) | ||
| 682 | - .collect(); | ||
| 683 | - | ||
| 684 | - let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); | ||
| 685 | - let qps_str = |qs: &[i32; 4]| { | ||
| 686 | - qs.iter() | ||
| 687 | - .map(|q| q.to_string()) | ||
| 688 | - .collect::<Vec<_>>() | ||
| 689 | - .join("/") | ||
| 690 | - }; | ||
| 691 | - | ||
| 692 | - #[allow(unused_assignments)] | ||
| 693 | - let ( | ||
| 694 | - mut bd, | ||
| 695 | - mut bd_yuv, | ||
| 696 | - mut cand_extrap, | ||
| 697 | - mut anc_extrap, | ||
| 698 | - mut cand_extrap_yuv, | ||
| 699 | - mut anc_extrap_yuv, | ||
| 700 | - ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); | ||
| 701 | - let mut mine: Vec<(f64, f64, f64)>; | ||
| 702 | - let mut our_qps: [i32; 4]; | ||
| 703 | - // How wide our QP ladder is against the anchor's, as a fraction of its | ||
| 704 | - // spacing: one encoder can answer a QP step with far more bitrate than the | ||
| 705 | - // other, and a BD number needs both curves over the same range. | ||
| 706 | - let mut spread = 1.0_f64; | ||
| 707 | - | ||
| 708 | - for round in 0..=8u32 { | ||
| 709 | - our_qps = x265_qps.map(|q| { | ||
| 710 | - let centre = f64::from(probe_qp + shift); | ||
| 711 | - let offset = f64::from(q - probe_qp) * spread; | ||
| 712 | - ((centre + offset).round() as i32).clamp(1, 45) | ||
| 713 | - }); | ||
| 714 | - let mut distinct = our_qps; | ||
| 715 | - distinct.sort_unstable(); | ||
| 716 | - let collapsed = distinct.windows(2).any(|w| w[0] == w[1]); | ||
| 717 | - assert!( | ||
| 718 | - !collapsed, | ||
| 719 | - "our QP ladder collapsed to {:?}: the shift has pushed it into the \ | ||
| 720 | - qp floor, so two points share an x and the cubic has no unique fit", | ||
| 721 | - our_qps, | ||
| 722 | - ); | ||
| 723 | - mine = our_qps | ||
| 724 | - .iter() | ||
| 725 | - .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) | ||
| 726 | - .collect(); | ||
| 727 | - for (i, &qp) in our_qps.iter().enumerate() { | ||
| 728 | - let (ob, op, oy) = mine[i]; | ||
| 729 | - eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); | ||
| 730 | - } | ||
| 731 | - for (i, &qp) in x265_qps.iter().enumerate() { | ||
| 732 | - let (xb, xp, xy) = theirs[i]; | ||
| 733 | - eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); | ||
| 734 | - } | ||
| 735 | - (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | ||
| 736 | - (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = | ||
| 737 | - bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | ||
| 738 | - eprintln!( | ||
| 739 | - "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", | ||
| 740 | - qps_str(&our_qps), | ||
| 741 | - qps_str(&x265_qps), | ||
| 742 | - ); | ||
| 743 | - eprintln!( | ||
| 744 | - "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", | ||
| 745 | - qps_str(&our_qps), | ||
| 746 | - qps_str(&x265_qps), | ||
| 747 | - ); | ||
| 748 | - let aligned = cand_extrap <= EXTRAP_LIMIT | ||
| 749 | - && anc_extrap <= EXTRAP_LIMIT | ||
| 750 | - && cand_extrap_yuv <= EXTRAP_LIMIT | ||
| 751 | - && anc_extrap_yuv <= EXTRAP_LIMIT; | ||
| 752 | - if aligned || round == 8 { | ||
| 753 | - break; | ||
| 754 | - } | ||
| 755 | - // Re-estimate the shift from the geometric-mean bit ratio of the two | ||
| 756 | - // full curves, then rebuild the ladder. A single-QP correction is | ||
| 757 | - // ignored: it is within the rounding of the estimate and only makes the | ||
| 758 | - // ladder oscillate between two neighbouring shifts. | ||
| 759 | - let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; | ||
| 760 | - if delta.abs() > 1 { | ||
| 761 | - shift += delta; | ||
| 762 | - eprintln!( | ||
| 763 | - "alignment round {}: shift {delta:+} -> {shift:+} \ | ||
| 764 | - (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", | ||
| 765 | - round + 1, | ||
| 766 | - gm(&mine) / 1e6, | ||
| 767 | - gm(&theirs) / 1e6, | ||
| 768 | - ); | ||
| 769 | - continue; | ||
| 770 | - } | ||
| 771 | - // The rates match and the curves still do not overlap, so our ladder | ||
| 772 | - // spans a much wider bitrate range than the anchor's: their union is | ||
| 773 | - // then mostly outside what x265 measured and the cubic through its four | ||
| 774 | - // points extrapolates over most of it. Draw our ladder in. | ||
| 775 | - spread *= 0.5; | ||
| 776 | - eprintln!( | ||
| 777 | - "alignment round {}: ladder spread -> {spread:.2} of the anchor's", | ||
| 778 | - round + 1 | ||
| 779 | - ); | ||
| 780 | - } | ||
| 781 | - | ||
| 782 | - // A BD number over a range where the two QP ladders do not overlap is not a | ||
| 783 | - // measurement — the cubic is extrapolating, not interpolating. Fail loudly | ||
| 784 | - // with the side that is out of range instead of reporting a meaningless gap. | ||
| 785 | - let out_of_range = |c: f64, a: f64| { | ||
| 786 | - let mut parts = Vec::new(); | ||
| 787 | - if c > EXTRAP_LIMIT { | ||
| 788 | - parts.push(format!("ours {:.0}%", c * 100.0)); | ||
| 789 | - } | ||
| 790 | - if a > EXTRAP_LIMIT { | ||
| 791 | - parts.push(format!("x265 {:.0}%", a * 100.0)); | ||
| 792 | - } | ||
| 793 | - parts | ||
| 794 | - }; | ||
| 795 | - let luma_oor = out_of_range(cand_extrap, anc_extrap); | ||
| 796 | - let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv); | ||
| 797 | - if !luma_oor.is_empty() { | ||
| 798 | - panic!( | ||
| 799 | - "BD-PSNR luma: the two QP ladders do not overlap — {} of the \ | ||
| 800 | - integration range is extrapolated (limit {:.0}%); widen the QP \ | ||
| 801 | - sweep until the curves meet", | ||
| 802 | - luma_oor.join(", "), | ||
| 803 | - EXTRAP_LIMIT * 100.0 | ||
| 804 | - ); | ||
| 805 | - } | ||
| 806 | - if !yuv_oor.is_empty() { | ||
| 807 | - panic!( | ||
| 808 | - "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \ | ||
| 809 | - integration range is extrapolated (limit {:.0}%); widen the QP \ | ||
| 810 | - sweep until the curves meet", | ||
| 811 | - yuv_oor.join(", "), | ||
| 812 | - EXTRAP_LIMIT * 100.0 | ||
| 813 | - ); | ||
| 814 | - } | ||
| 815 | - | ||
| 816 | - // The floor is calibrated on the synthetic clip; a clip of the user's is a | ||
| 817 | - // measurement, not a gate, because its content is not pinned. | ||
| 818 | - if std::env::var_os("EC_H265_CLIP").is_none() { | ||
| 819 | - assert!( | ||
| 820 | - bd > BD_PSNR_VS_X265_FLOOR, | ||
| 821 | - "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ | ||
| 822 | - {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" | ||
| 823 | - ); | ||
| 824 | - } | ||
| 825 | -} | ||
| 826 | - | ||
| 827 | -/// Decode `want` pictures from a media file as tightly packed I420 triples. | ||
| 828 | -/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film | ||
| 829 | -/// heads are titles and fades). | ||
| 830 | -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { | ||
| 831 | - let dims = ec_testkit::ffprobe() | ||
| 832 | - .args([ | ||
| 833 | - "-v", | ||
| 834 | - "error", | ||
| 835 | - "-select_streams", | ||
| 836 | - "v:0", | ||
| 837 | - "-show_entries", | ||
| 838 | - "stream=width,height", | ||
| 839 | - "-of", | ||
| 840 | - "csv=p=0", | ||
| 841 | - ]) | ||
| 842 | - .arg(path) | ||
| 843 | - .output() | ||
| 844 | - .expect("ffprobe"); | ||
| 845 | - assert!( | ||
| 846 | - dims.status.success(), | ||
| 847 | - "ffprobe failed: {}", | ||
| 848 | - String::from_utf8_lossy(&dims.stderr) | ||
| 849 | - ); | ||
| 850 | - let csv = String::from_utf8_lossy(&dims.stdout); | ||
| 851 | - // ffprobe prints one comma-separated line per stream, and recent builds | ||
| 852 | - // end it with a trailing separator, so the fields are taken by position | ||
| 853 | - // rather than by splitting the line in two. | ||
| 854 | - let mut fields = csv.lines().next().unwrap_or_default().split(','); | ||
| 855 | - let (w, h) = (|| { | ||
| 856 | - Some(( | ||
| 857 | - fields.next()?.trim().parse::<usize>().ok()?, | ||
| 858 | - fields.next()?.trim().parse::<usize>().ok()?, | ||
| 859 | - )) | ||
| 860 | - })() | ||
| 861 | - .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}")); | ||
| 862 | - // Pictures to pass over before sampling: the head of a film is titles and | ||
| 863 | - // fades, which are not what a codec is measured on. | ||
| 864 | - let skip: usize = std::env::var("EC_H265_CLIP_SKIP") | ||
| 865 | - .ok() | ||
| 866 | - .and_then(|v| v.parse().ok()) | ||
| 867 | - .unwrap_or(0); | ||
| 868 | - // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing | ||
| 869 | - // afterwards buffers the entire decoded clip in memory: a 1080p feature is | ||
| 870 | - // hundreds of gigabytes of raw I420, which the kernel answers with the OOM | ||
| 871 | - // killer. `select` drops the skipped pictures inside ffmpeg and | ||
| 872 | - // `-frames:v` stops the decode once `want` have come out, so what reaches | ||
| 873 | - // this process is exactly `want` frames. | ||
| 874 | - let raw = ec_testkit::ffmpeg() | ||
| 875 | - .args(["-v", "error", "-i"]) | ||
| 876 | - .arg(path) | ||
| 877 | - .args([ | ||
| 878 | - "-vf", | ||
| 879 | - &format!("select=gte(n\\,{skip})"), | ||
| 880 | - "-fps_mode", | ||
| 881 | - "passthrough", | ||
| 882 | - "-frames:v", | ||
| 883 | - &want.to_string(), | ||
| 884 | - "-f", | ||
| 885 | - "rawvideo", | ||
| 886 | - "-pix_fmt", | ||
| 887 | - "yuv420p", | ||
| 888 | - "pipe:1", | ||
| 889 | - ]) | ||
| 890 | - .output() | ||
| 891 | - .expect("ffmpeg raw extract"); | ||
| 892 | - assert!( | ||
| 893 | - raw.status.success(), | ||
| 894 | - "ffmpeg failed: {}", | ||
| 895 | - String::from_utf8_lossy(&raw.stderr) | ||
| 896 | - ); | ||
| 897 | - let frame = w * h * 3 / 2; | ||
| 898 | - assert!( | ||
| 899 | - raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, | ||
| 900 | - "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", | ||
| 901 | - path.to_string_lossy(), | ||
| 902 | - raw.stdout.len() | ||
| 903 | - ); | ||
| 904 | - let sources: Vec<Planes> = raw | ||
| 905 | - .stdout | ||
| 906 | - .chunks(frame) | ||
| 907 | - .take(want) | ||
| 908 | - .map(|f| { | ||
| 909 | - let (y, rest) = f.split_at(w * h); | ||
| 910 | - let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 911 | - (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 912 | - }) | ||
| 913 | - .collect(); | ||
| 914 | - eprintln!( | ||
| 915 | - "{}: {}x{}, {} pictures (skipped {skip})", | ||
| 916 | - path.to_string_lossy(), | ||
| 917 | - w, | ||
| 918 | - h, | ||
| 919 | - sources.len() | ||
| 920 | - ); | ||
| 921 | - (w, h, sources) | ||
| 922 | -} | ||
crates/ec-h265/tests/it/main.rsmodified+0 -13
| @@ -5,23 +5,10 @@ | |||
| 5 | #![forbid(unsafe_code)] | 5 | #![forbid(unsafe_code)] |
| 6 | 6 | ||
| 7 | mod common; | 7 | mod common; |
| 8 | -mod conformance; | ||
| 9 | -mod conformance_intra; | ||
| 10 | -mod conformance_rext; | ||
| 11 | -mod conformance_rext422; | ||
| 12 | -mod cu_syntax; | ||
| 13 | -mod dec_meta; | ||
| 14 | -mod dec_shell; | ||
| 15 | mod decode; | 8 | mod decode; |
| 16 | -mod dolby_vision_p8; | ||
| 17 | mod enc8_bitstream_hash; | 9 | mod enc8_bitstream_hash; |
| 18 | -mod encode; | ||
| 19 | mod encode_threads; | 10 | mod encode_threads; |
| 20 | mod fuzz_regressions; | 11 | mod fuzz_regressions; |
| 21 | mod main10; | 12 | mod main10; |
| 22 | -mod rate_control; | ||
| 23 | -mod rdoq_cache_hash; | ||
| 24 | -mod real_library; | ||
| 25 | mod refusals; | 13 | mod refusals; |
| 26 | mod rext_generated; | 14 | mod rext_generated; |
| 27 | -mod scaling_lists; | ||
crates/ec-h265/tests/it/rate_control.rsdeleted+0 -207
| @@ -1,207 +0,0 @@ | |||
| 1 | -//! Bitrate control of the sequence encoder: a clip coded at a target lands within | ||
| 2 | -//! 5% of that target, and the output does not depend on the worker count. | ||
| 3 | -//! | ||
| 4 | -//! The clip is a textured pattern that moves a few samples per picture, so the | ||
| 5 | -//! pictures differ in cost and the model has to follow them. The 5% bound is the | ||
| 6 | -//! same one the 60 s measurement is held to (`scripts/hevc-rc.sh`). | ||
| 7 | - | ||
| 8 | -use ec_core::frame::{PixelFormat, Plane, VideoFrame}; | ||
| 9 | -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; | ||
| 10 | - | ||
| 11 | -const W: usize = 320; | ||
| 12 | -const H: usize = 240; | ||
| 13 | -const FPS: f64 = 30.0; | ||
| 14 | -const FRAMES: usize = 150; | ||
| 15 | -const KEYINT: usize = 30; | ||
| 16 | - | ||
| 17 | -fn moving_clip(frames: usize) -> Vec<VideoFrame> { | ||
| 18 | - let (cw, ch) = (W / 2, H / 2); | ||
| 19 | - (0..frames) | ||
| 20 | - .map(|t| { | ||
| 21 | - let mut y = vec![0u8; W * H]; | ||
| 22 | - for r in 0..H { | ||
| 23 | - for c in 0..W { | ||
| 24 | - let (x, yy) = (c + 3 * t, r + t); | ||
| 25 | - let mut v = (x * 7 + yy * 5) as u32; | ||
| 26 | - v ^= (x as u32).wrapping_mul(0x9e37) ^ (yy as u32).wrapping_mul(0x85eb); | ||
| 27 | - y[r * W + c] = (v.wrapping_mul(2_654_435_761) >> 24) as u8; | ||
| 28 | - } | ||
| 29 | - } | ||
| 30 | - let chroma = |scale: usize| -> Vec<u8> { | ||
| 31 | - (0..cw * ch) | ||
| 32 | - .map(|i| { | ||
| 33 | - let (c, r) = (i % cw, i / cw); | ||
| 34 | - ((c * scale + r * 3 + t * 2) % 251) as u8 | ||
| 35 | - }) | ||
| 36 | - .collect() | ||
| 37 | - }; | ||
| 38 | - VideoFrame::try_new( | ||
| 39 | - PixelFormat::I420, | ||
| 40 | - W as u32, | ||
| 41 | - H as u32, | ||
| 42 | - vec![ | ||
| 43 | - Plane::new(y, W), | ||
| 44 | - Plane::new(chroma(5), cw), | ||
| 45 | - Plane::new(chroma(9), cw), | ||
| 46 | - ], | ||
| 47 | - ) | ||
| 48 | - .expect("I420 planes at the stated size") | ||
| 49 | - }) | ||
| 50 | - .collect() | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | -/// Encode the clip at `kbps` with `threads` workers; returns the stream bytes. | ||
| 54 | -fn encode_at(frames: &[VideoFrame], kbps: u32, threads: usize) -> Vec<u8> { | ||
| 55 | - let mut cfg = EncoderConfig::new(W as u32, H as u32); | ||
| 56 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 57 | - cfg.keyint = KEYINT; | ||
| 58 | - cfg.threads = threads; | ||
| 59 | - let enc = Encoder::new(cfg).expect("encoder"); | ||
| 60 | - let coded = enc.encode_sequence(frames).expect("encode"); | ||
| 61 | - coded.iter().flat_map(|p| p.au.iter().copied()).collect() | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -#[test] | ||
| 65 | -fn bitrate_lands_within_five_percent_of_each_target() { | ||
| 66 | - let frames = moving_clip(FRAMES); | ||
| 67 | - for kbps in [1000u32, 2500, 5000] { | ||
| 68 | - let stream = encode_at(&frames, kbps, 1); | ||
| 69 | - let seconds = FRAMES as f64 / FPS; | ||
| 70 | - let achieved = stream.len() as f64 * 8.0 / seconds / 1000.0; | ||
| 71 | - let error = (achieved - f64::from(kbps)) / f64::from(kbps); | ||
| 72 | - eprintln!( | ||
| 73 | - "target {kbps} kbps: achieved {achieved:.1} kbps ({:+.2}%)", | ||
| 74 | - error * 100.0 | ||
| 75 | - ); | ||
| 76 | - assert!( | ||
| 77 | - error.abs() <= 0.05, | ||
| 78 | - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", | ||
| 79 | - error * 100.0 | ||
| 80 | - ); | ||
| 81 | - } | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -/// A flat picture at `luma` (chroma at 128): nothing in it costs more than a skipped block | ||
| 85 | -/// at any QP, so it is the case where the rate cannot be spent. | ||
| 86 | -fn flat_clip(frames: usize, luma: u8) -> Vec<VideoFrame> { | ||
| 87 | - let (cw, ch) = (W / 2, H / 2); | ||
| 88 | - (0..frames) | ||
| 89 | - .map(|_| { | ||
| 90 | - VideoFrame::try_new( | ||
| 91 | - PixelFormat::I420, | ||
| 92 | - W as u32, | ||
| 93 | - H as u32, | ||
| 94 | - vec![ | ||
| 95 | - Plane::new(vec![luma; W * H], W), | ||
| 96 | - Plane::new(vec![128; cw * ch], cw), | ||
| 97 | - Plane::new(vec![128; cw * ch], cw), | ||
| 98 | - ], | ||
| 99 | - ) | ||
| 100 | - .expect("I420 planes at the stated size") | ||
| 101 | - }) | ||
| 102 | - .collect() | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -/// A flat clip at 2000 kbps cannot spend its budget even at QP 0, so the rate model must | ||
| 106 | -/// walk the quantiser down to the HEVC floor and hold it there, rather than stall high. | ||
| 107 | -/// The floor is the codec's, not a rate floor of this encoder: whatever bits remain are the | ||
| 108 | -/// content's own cost at QP 0. | ||
| 109 | -#[test] | ||
| 110 | -fn flat_near_black_descends_to_the_qp_floor() { | ||
| 111 | - let frames = flat_clip(60, 16); | ||
| 112 | - let pics: Vec<EncodedPicture> = encode_pictures(&frames, 2000); | ||
| 113 | - // The first predicted pictures walk the quantiser down from the IDR's QP (at most four | ||
| 114 | - // steps each); from picture 10 on, every predicted picture must sit at QP 0. | ||
| 115 | - let tail: Vec<(usize, i32)> = pics | ||
| 116 | - .iter() | ||
| 117 | - .enumerate() | ||
| 118 | - .filter(|(i, _)| i % KEYINT != 0 && *i >= 10) | ||
| 119 | - .map(|(i, p)| (i, p.qp)) | ||
| 120 | - .collect(); | ||
| 121 | - assert!(!tail.is_empty()); | ||
| 122 | - let stalled: Vec<&(usize, i32)> = tail.iter().filter(|(_, qp)| *qp != 0).collect(); | ||
| 123 | - assert!( | ||
| 124 | - stalled.is_empty(), | ||
| 125 | - "QP did not reach the floor: {stalled:?}" | ||
| 126 | - ); | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -/// Encode `frames` at `kbps` and return the coded pictures, so the test can see each QP. | ||
| 130 | -fn encode_pictures(frames: &[VideoFrame], kbps: u32) -> Vec<EncodedPicture> { | ||
| 131 | - let mut cfg = EncoderConfig::new(W as u32, H as u32); | ||
| 132 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 133 | - cfg.keyint = KEYINT; | ||
| 134 | - cfg.threads = 1; | ||
| 135 | - Encoder::new(cfg) | ||
| 136 | - .expect("encoder") | ||
| 137 | - .encode_sequence(frames) | ||
| 138 | - .expect("encode") | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -#[test] | ||
| 142 | -fn bitrate_output_is_identical_at_any_thread_count() { | ||
| 143 | - let frames = moving_clip(FRAMES); | ||
| 144 | - let one = encode_at(&frames, 2500, 1); | ||
| 145 | - for threads in [2usize, 4] { | ||
| 146 | - assert!( | ||
| 147 | - encode_at(&frames, 2500, threads) == one, | ||
| 148 | - "stream differs at {threads} threads" | ||
| 149 | - ); | ||
| 150 | - } | ||
| 151 | -} | ||
| 152 | - | ||
| 153 | -/// Near-black with temporal noise at 720p: luma 16 plus a deterministic PRNG offset of -2..=2 | ||
| 154 | -/// that differs every picture. Cost against QP is a cliff here (a few hundred bytes per | ||
| 155 | -/// picture above QP ~17, tens of kilobytes a few steps below), so the `2^(QP/6)` model alone | ||
| 156 | -/// dives into the cliff after a run of cheap pictures and the stream overshoots. The cliff | ||
| 157 | -/// only shows at this size, which is why this clip is not 320x240. | ||
| 158 | -fn noisy_black_clip(frames: usize, w: usize, h: usize) -> Vec<VideoFrame> { | ||
| 159 | - let (cw, ch) = (w / 2, h / 2); | ||
| 160 | - let mut state = 0x2545_f491_4f6c_dd1du64; | ||
| 161 | - let mut next = move || { | ||
| 162 | - state ^= state << 13; | ||
| 163 | - state ^= state >> 7; | ||
| 164 | - state ^= state << 17; | ||
| 165 | - (state >> 33) as u32 | ||
| 166 | - }; | ||
| 167 | - (0..frames) | ||
| 168 | - .map(|_| { | ||
| 169 | - let y: Vec<u8> = (0..w * h).map(|_| (14 + next() % 5) as u8).collect(); | ||
| 170 | - VideoFrame::try_new( | ||
| 171 | - PixelFormat::I420, | ||
| 172 | - w as u32, | ||
| 173 | - h as u32, | ||
| 174 | - vec![ | ||
| 175 | - Plane::new(y, w), | ||
| 176 | - Plane::new(vec![128; cw * ch], cw), | ||
| 177 | - Plane::new(vec![128; cw * ch], cw), | ||
| 178 | - ], | ||
| 179 | - ) | ||
| 180 | - .expect("I420 planes at the stated size") | ||
| 181 | - }) | ||
| 182 | - .collect() | ||
| 183 | -} | ||
| 184 | - | ||
| 185 | -#[test] | ||
| 186 | -fn noisy_near_black_lands_within_five_percent() { | ||
| 187 | - let (w, h, frames) = (1280usize, 720usize, noisy_black_clip(90, 1280, 720)); | ||
| 188 | - for kbps in [500u32, 2000] { | ||
| 189 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 190 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 191 | - cfg.keyint = KEYINT; | ||
| 192 | - cfg.threads = 1; | ||
| 193 | - let pics = Encoder::new(cfg) | ||
| 194 | - .expect("encoder") | ||
| 195 | - .encode_sequence(&frames) | ||
| 196 | - .expect("encode"); | ||
| 197 | - let bytes: usize = pics.iter().map(|p| p.au.len()).sum(); | ||
| 198 | - let achieved = bytes as f64 * 8.0 / (frames.len() as f64 / FPS) / 1000.0; | ||
| 199 | - let error = (achieved - f64::from(kbps)) / f64::from(kbps); | ||
| 200 | - eprintln!("target {kbps}: {achieved:.1} kbps ({:+.2}%)", error * 100.0); | ||
| 201 | - assert!( | ||
| 202 | - error.abs() <= 0.05, | ||
| 203 | - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", | ||
| 204 | - error * 100.0 | ||
| 205 | - ); | ||
| 206 | - } | ||
| 207 | -} | ||
crates/ec-h265/tests/it/rdoq_cache_hash.rsdeleted+0 -70
| @@ -1,70 +0,0 @@ | |||
| 1 | -//! lane-h265rdoq r3: the sub-block frozen-prefix cursor must not change a | ||
| 2 | -//! single output byte. Hashes two natural-content encodes (1920x1080 and | ||
| 3 | -//! 416x240) with FNV-1a; the number itself means nothing, only that it is the | ||
| 4 | -//! same before and after this round's change to `rdoq()` (checked by hand: | ||
| 5 | -//! stash `residual.rs`, rerun, compare). | ||
| 6 | - | ||
| 7 | -use crate::common::{fnv1a, natural_frame}; | ||
| 8 | -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; | ||
| 9 | - | ||
| 10 | -fn encode_hash(width: u32, height: u32) -> u64 { | ||
| 11 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 12 | - cfg.rate_control = RateControl::ConstantQp(24); | ||
| 13 | - cfg.threads = 1; | ||
| 14 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 15 | - let mut all = Vec::new(); | ||
| 16 | - for i in 0..3u32 { | ||
| 17 | - let frame = natural_frame(width, height, i * 5); | ||
| 18 | - all.extend(encoder.encode_idr(&frame).expect("encode").au); | ||
| 19 | - } | ||
| 20 | - fnv1a(&all) | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -#[test] | ||
| 24 | -fn rdoq_cache_hash_1920x1080() { | ||
| 25 | - println!("hash 1920x1080 = {:016x}", encode_hash(1920, 1080)); | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -#[test] | ||
| 29 | -fn rdoq_cache_hash_416x240() { | ||
| 30 | - println!("hash 416x240 = {:016x}", encode_hash(416, 240)); | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -/// lane-h265simd: pinned bit-identity gate for the transform's hot path. The | ||
| 34 | -/// value is the same hash the two tests above print, verified by hand | ||
| 35 | -/// (`git stash` the transform.rs change, rerun, compare) to be identical | ||
| 36 | -/// before and after replacing `m32()`'s per-element branch with a | ||
| 37 | -/// compile-time-mirrored flat table in `forward_1d`/`inverse_1d` — this pins | ||
| 38 | -/// that equality so a future change to the hot path is caught if it ever | ||
| 39 | -/// produces a different byte. | ||
| 40 | -/// | ||
| 41 | -/// lane-h265prune: re-pinned after the RQT split trial gained an all-zero-CBF | ||
| 42 | -/// early out (mirrors the CU-quadtree's existing `last_cu_empty` skip one | ||
| 43 | -/// level down at the transform tree): a coding unit whose luma+chroma already | ||
| 44 | -/// quantised to nothing is committed as one leaf transform unit without | ||
| 45 | -/// trying the four-child split first, since splitting a zero-SSD block can | ||
| 46 | -/// only add split_transform_flag and mode-signalling bits. This changes the | ||
| 47 | -/// bitstream on any content where that trial used to flip a leaf to split | ||
| 48 | -/// (BD-gated, not bit-identical — see `EncoderConfig::rqt` and this crate's | ||
| 49 | -/// `bd_psnr_vs_x265`). | ||
| 50 | -/// | ||
| 51 | -/// lane-h265rdoq: re-pinned after RDOQ's trial costing switched from exact | ||
| 52 | -/// per-trial CABAC replay to an estimated per-context fracbits table | ||
| 53 | -/// (`EncoderConfig::rdoq_estimate`, now on by default) — deliberately | ||
| 54 | -/// bit-different, not exact-mode-preserving; see that field's doc comment | ||
| 55 | -/// for the BD/speed numbers that justified flipping the default. | ||
| 56 | -/// | ||
| 57 | -/// lane-h265screen: re-pinned after every committed 4x4 luma block gained a | ||
| 58 | -/// rate-distortion decision on `transform_skip_flag` (`TransformSkip::Rd`, now | ||
| 59 | -/// the default) — deliberately bit-different; see that field's doc comment for | ||
| 60 | -/// the BD numbers per clip. | ||
| 61 | -/// | ||
| 62 | -/// lane-hevcenctools: re-pinned after the sequence parameter set's | ||
| 63 | -/// `sps_temporal_mvp_enabled_flag` went on, which the P pictures' slice headers | ||
| 64 | -/// need. That is one SPS bit; the intra slices are otherwise unchanged, and the | ||
| 65 | -/// 9203-picture conformance check still matches. | ||
| 66 | -#[test] | ||
| 67 | -fn rdoq_cache_hash_is_pinned() { | ||
| 68 | - assert_eq!(encode_hash(416, 240), 0xd501713b57091906); | ||
| 69 | - assert_eq!(encode_hash(1920, 1080), 0x5eb50f5a747ca1c2); | ||
| 70 | -} | ||
crates/ec-h265/tests/it/real_library.rsdeleted+0 -367
| @@ -1,367 +0,0 @@ | |||
| 1 | -//! Every file either decodes bit-exactly, is refused by name (a pixel format or | ||
| 2 | -//! a bit depth outside 4:2:0 8/10-bit, or a decoder refusal that says | ||
| 3 | -//! "unsupported"), or fails. A refusal is reported, not counted as a failure. | ||
| 4 | - | ||
| 5 | -use std::io::Read; | ||
| 6 | -use std::path::{Path, PathBuf}; | ||
| 7 | -use std::process::Stdio; | ||
| 8 | - | ||
| 9 | -use ec_h265::dec::Decoder; | ||
| 10 | -use ec_h265::decode::DecodedPicture; | ||
| 11 | -use ec_h265_syntax::{ConformanceWindow, split_annex_b}; | ||
| 12 | - | ||
| 13 | -/// Pictures compared per file. | ||
| 14 | -const FRAMES: usize = 300; | ||
| 15 | - | ||
| 16 | -/// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits. | ||
| 17 | -const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"]; | ||
| 18 | - | ||
| 19 | -fn scratch(tag: &str) -> PathBuf { | ||
| 20 | - let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); | ||
| 21 | - let dir = base.join(format!("ec-h265-{tag}-{}", std::process::id())); | ||
| 22 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 23 | - dir | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -/// One manifest row: the columns the sweep reads. | ||
| 27 | -struct Entry { | ||
| 28 | - path: PathBuf, | ||
| 29 | - container: String, | ||
| 30 | - width: String, | ||
| 31 | - height: String, | ||
| 32 | - pix_fmt: String, | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -fn hevc_entries() -> Vec<Entry> { | ||
| 36 | - [ | ||
| 37 | - ( | ||
| 38 | - "derived/sintel720-x265-main10.mp4", | ||
| 39 | - "yuv420p10le", | ||
| 40 | - "1280", | ||
| 41 | - "720", | ||
| 42 | - ), | ||
| 43 | - ("open/sintel_trailer-1080p.mp4", "yuv420p", "1920", "1080"), | ||
| 44 | - ] | ||
| 45 | - .into_iter() | ||
| 46 | - .map(|(rel, pix_fmt, width, height)| Entry { | ||
| 47 | - path: ec_testkit::fixture(rel), | ||
| 48 | - container: "mp4".to_string(), | ||
| 49 | - width: width.to_string(), | ||
| 50 | - height: height.to_string(), | ||
| 51 | - pix_fmt: pix_fmt.to_string(), | ||
| 52 | - }) | ||
| 53 | - .collect() | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -/// The samples of a picture cropped to its conformance window, as the bytes of a | ||
| 57 | -/// planar rawvideo frame: one byte per sample at 8 bits, little-endian u16 above. | ||
| 58 | -fn cropped(pic: &DecodedPicture, win: &ConformanceWindow, bps: usize) -> Vec<u8> { | ||
| 59 | - let (l, r, t, b) = ( | ||
| 60 | - win.left as usize, | ||
| 61 | - win.right as usize, | ||
| 62 | - win.top as usize, | ||
| 63 | - win.bottom as usize, | ||
| 64 | - ); | ||
| 65 | - let (w, h) = (pic.width, pic.height); | ||
| 66 | - // Conformance offsets are in chroma units for 4:2:0: luma is twice as large. | ||
| 67 | - let planes = [ | ||
| 68 | - ( | ||
| 69 | - &pic.y, | ||
| 70 | - w, | ||
| 71 | - h, | ||
| 72 | - 2 * l, | ||
| 73 | - w.saturating_sub(2 * r), | ||
| 74 | - 2 * t, | ||
| 75 | - h.saturating_sub(2 * b), | ||
| 76 | - ), | ||
| 77 | - ( | ||
| 78 | - &pic.cb, | ||
| 79 | - w / 2, | ||
| 80 | - h / 2, | ||
| 81 | - l, | ||
| 82 | - (w / 2).saturating_sub(r), | ||
| 83 | - t, | ||
| 84 | - (h / 2).saturating_sub(b), | ||
| 85 | - ), | ||
| 86 | - ( | ||
| 87 | - &pic.cr, | ||
| 88 | - w / 2, | ||
| 89 | - h / 2, | ||
| 90 | - l, | ||
| 91 | - (w / 2).saturating_sub(r), | ||
| 92 | - t, | ||
| 93 | - (h / 2).saturating_sub(b), | ||
| 94 | - ), | ||
| 95 | - ]; | ||
| 96 | - let mut out = Vec::new(); | ||
| 97 | - for (samples, pw, ph, x0, x1, y0, y1) in planes { | ||
| 98 | - for y in y0..y1.min(ph) { | ||
| 99 | - for x in x0..x1.min(pw) { | ||
| 100 | - let s = samples.get(y * pw + x).copied().unwrap_or(0); | ||
| 101 | - if bps == 1 { | ||
| 102 | - out.push(s as u8); | ||
| 103 | - } else { | ||
| 104 | - out.extend_from_slice(&s.to_le_bytes()); | ||
| 105 | - } | ||
| 106 | - } | ||
| 107 | - } | ||
| 108 | - } | ||
| 109 | - out | ||
| 110 | -} | ||
| 111 | - | ||
| 112 | -/// Where byte `offset` of a cropped frame lies: plane name, x and y in that plane. | ||
| 113 | -fn locate(offset: usize, bps: usize, lw: usize, lh: usize) -> (&'static str, usize, usize) { | ||
| 114 | - let s = offset / bps; | ||
| 115 | - let (cw, ch) = (lw / 2, lh / 2); | ||
| 116 | - if s < lw * lh { | ||
| 117 | - ("Y", s % lw, s / lw) | ||
| 118 | - } else if s < lw * lh + cw * ch { | ||
| 119 | - let c = s - lw * lh; | ||
| 120 | - ("Cb", c % cw, c / cw) | ||
| 121 | - } else { | ||
| 122 | - let c = s - lw * lh - cw * ch; | ||
| 123 | - ("Cr", c % cw, c / cw) | ||
| 124 | - } | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -/// Running comparison of decoded frames against the oracle's rawvideo stream. | ||
| 128 | -#[derive(Default)] | ||
| 129 | -struct Compare { | ||
| 130 | - compared: usize, | ||
| 131 | - /// First mismatch: "frame N plane P x= y= (poc)". | ||
| 132 | - first_diff: Option<String>, | ||
| 133 | - differing_frames: usize, | ||
| 134 | - oracle_short: bool, | ||
| 135 | -} | ||
| 136 | - | ||
| 137 | -/// The oracle's stream and the decoder's frames, compared frame by frame. | ||
| 138 | -struct Sweep { | ||
| 139 | - out: std::process::ChildStdout, | ||
| 140 | - child: std::process::Child, | ||
| 141 | - open: bool, | ||
| 142 | - cmp: Compare, | ||
| 143 | - index: usize, | ||
| 144 | - frame_len: usize, | ||
| 145 | - bps: usize, | ||
| 146 | -} | ||
| 147 | - | ||
| 148 | -impl Sweep { | ||
| 149 | - fn take(&mut self, pic: &DecodedPicture, win: &ConformanceWindow, poc: i32) { | ||
| 150 | - let want = cropped(pic, win, self.bps); | ||
| 151 | - let index = self.index; | ||
| 152 | - self.index += 1; | ||
| 153 | - if !self.open { | ||
| 154 | - return; | ||
| 155 | - } | ||
| 156 | - let mut oracle = vec![0u8; want.len()]; | ||
| 157 | - if self.out.read_exact(&mut oracle).is_err() { | ||
| 158 | - self.open = false; | ||
| 159 | - self.cmp.oracle_short = true; | ||
| 160 | - return; | ||
| 161 | - } | ||
| 162 | - self.frame_len = want.len(); | ||
| 163 | - self.cmp.compared += 1; | ||
| 164 | - if want != oracle { | ||
| 165 | - self.cmp.differing_frames += 1; | ||
| 166 | - if self.cmp.first_diff.is_none() { | ||
| 167 | - let lw = pic.width - 2 * (win.left as usize + win.right as usize); | ||
| 168 | - let lh = pic.height - 2 * (win.top as usize + win.bottom as usize); | ||
| 169 | - let at = want | ||
| 170 | - .iter() | ||
| 171 | - .zip(&oracle) | ||
| 172 | - .position(|(a, b)| a != b) | ||
| 173 | - .unwrap_or(0); | ||
| 174 | - let (plane, x, y) = locate(at, self.bps, lw, lh); | ||
| 175 | - self.cmp.first_diff = Some(format!( | ||
| 176 | - "frame {index} plane {plane} x={x} y={y} (poc {poc})" | ||
| 177 | - )); | ||
| 178 | - } | ||
| 179 | - } | ||
| 180 | - } | ||
| 181 | - | ||
| 182 | - /// End of the decoder's output: any frame still in the oracle is missing here. | ||
| 183 | - fn finish(mut self) -> Compare { | ||
| 184 | - if self.open { | ||
| 185 | - let mut probe = vec![0u8; self.frame_len.max(1)]; | ||
| 186 | - if self.frame_len > 0 && self.out.read_exact(&mut probe).is_ok() { | ||
| 187 | - self.cmp.first_diff.get_or_insert(format!( | ||
| 188 | - "decoder produced {} frames, ffmpeg produced more", | ||
| 189 | - self.index | ||
| 190 | - )); | ||
| 191 | - self.cmp.oracle_short = false; | ||
| 192 | - self.cmp.differing_frames += 1; | ||
| 193 | - } | ||
| 194 | - } | ||
| 195 | - let _ = self.child.kill(); | ||
| 196 | - let _ = self.child.wait(); | ||
| 197 | - self.cmp | ||
| 198 | - } | ||
| 199 | -} | ||
| 200 | - | ||
| 201 | -fn short_name(path: &Path) -> String { | ||
| 202 | - path.file_name() | ||
| 203 | - .map(|n| n.to_string_lossy().chars().take(38).collect()) | ||
| 204 | - .unwrap_or_default() | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -/// Decodes one file and compares it with ffmpeg. `Err` is a refusal or an error, | ||
| 208 | -/// with the text the table prints. | ||
| 209 | -fn sweep_file(entry: &Entry, es: &Path, bit_depth: u32) -> Result<Compare, String> { | ||
| 210 | - let bps = if bit_depth > 8 { 2 } else { 1 }; | ||
| 211 | - let mut child = ec_testkit::ffmpeg() | ||
| 212 | - .args(["-v", "error", "-c:v", "hevc", "-i"]) | ||
| 213 | - .arg(es) | ||
| 214 | - .args([ | ||
| 215 | - "-frames:v", | ||
| 216 | - &FRAMES.to_string(), | ||
| 217 | - "-f", | ||
| 218 | - "rawvideo", | ||
| 219 | - "-pix_fmt", | ||
| 220 | - ]) | ||
| 221 | - .arg(&entry.pix_fmt) | ||
| 222 | - .arg("-") | ||
| 223 | - .stdout(Stdio::piped()) | ||
| 224 | - .stderr(Stdio::null()) | ||
| 225 | - .spawn() | ||
| 226 | - .map_err(|e| e.to_string())?; | ||
| 227 | - let out = child.stdout.take().expect("piped stdout"); | ||
| 228 | - let mut sweep = Sweep { | ||
| 229 | - out, | ||
| 230 | - child, | ||
| 231 | - open: true, | ||
| 232 | - cmp: Compare::default(), | ||
| 233 | - index: 0, | ||
| 234 | - frame_len: 0, | ||
| 235 | - bps, | ||
| 236 | - }; | ||
| 237 | - | ||
| 238 | - let data = std::fs::read(es).map_err(|e| e.to_string())?; | ||
| 239 | - let mut dec = Decoder::new(); | ||
| 240 | - let drain = |dec: &mut Decoder, sweep: &mut Sweep| { | ||
| 241 | - while let Some(frame) = dec.next_frame() { | ||
| 242 | - sweep.take(&frame.picture, &frame.window, frame.poc); | ||
| 243 | - } | ||
| 244 | - }; | ||
| 245 | - let result = (|| -> Result<(), String> { | ||
| 246 | - for nal in split_annex_b(&data) { | ||
| 247 | - let mut bytes = nal.header.to_bytes().to_vec(); | ||
| 248 | - bytes.extend_from_slice(nal.payload); | ||
| 249 | - if let Err(e) = dec.push_nal(&bytes) { | ||
| 250 | - return Err(format!("{e}")); | ||
| 251 | - } | ||
| 252 | - drain(&mut dec, &mut sweep); | ||
| 253 | - } | ||
| 254 | - dec.flush().map_err(|e| format!("{e}"))?; | ||
| 255 | - drain(&mut dec, &mut sweep); | ||
| 256 | - Ok(()) | ||
| 257 | - })(); | ||
| 258 | - let cmp = sweep.finish(); | ||
| 259 | - result?; | ||
| 260 | - Ok(cmp) | ||
| 261 | -} | ||
| 262 | - | ||
| 263 | -/// Extracts the first `FRAMES` pictures of the video as Annex B. | ||
| 264 | -fn extract(src: &Path, dst: &Path) -> bool { | ||
| 265 | - ec_testkit::ffmpeg() | ||
| 266 | - .args(["-v", "error", "-y", "-i"]) | ||
| 267 | - .arg(src) | ||
| 268 | - .args([ | ||
| 269 | - "-map", | ||
| 270 | - "0:v:0", | ||
| 271 | - "-c", | ||
| 272 | - "copy", | ||
| 273 | - "-bsf:v", | ||
| 274 | - "hevc_mp4toannexb", | ||
| 275 | - "-frames:v", | ||
| 276 | - &FRAMES.to_string(), | ||
| 277 | - "-f", | ||
| 278 | - "hevc", | ||
| 279 | - ]) | ||
| 280 | - .arg(dst) | ||
| 281 | - .status() | ||
| 282 | - .is_ok_and(|s| s.success()) | ||
| 283 | -} | ||
| 284 | - | ||
| 285 | -#[test] | ||
| 286 | -#[ignore = "slow: decodes and compares two open clips with ffmpeg; run with --ignored."] | ||
| 287 | -fn real_library_hevc_streams_match_ffmpeg() { | ||
| 288 | - let entries = hevc_entries(); | ||
| 289 | - let dir = scratch("real-library-hevc"); | ||
| 290 | - let mut table = String::new(); | ||
| 291 | - let mut decoded = 0usize; | ||
| 292 | - let mut refused = 0usize; | ||
| 293 | - let mut failures = Vec::new(); | ||
| 294 | - | ||
| 295 | - for entry in &entries { | ||
| 296 | - let name = short_name(&entry.path); | ||
| 297 | - let res = format!("{}x{}", entry.width, entry.height); | ||
| 298 | - let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" { | ||
| 299 | - 10 | ||
| 300 | - } else { | ||
| 301 | - 8 | ||
| 302 | - }; | ||
| 303 | - if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) { | ||
| 304 | - refused += 1; | ||
| 305 | - table.push_str(&format!( | ||
| 306 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n", | ||
| 307 | - entry.container, "-", entry.pix_fmt | ||
| 308 | - )); | ||
| 309 | - continue; | ||
| 310 | - } | ||
| 311 | - let es = dir.join("stream.265"); | ||
| 312 | - if !extract(&entry.path, &es) { | ||
| 313 | - failures.push(format!("{name}: extraction failed")); | ||
| 314 | - table.push_str(&format!( | ||
| 315 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n", | ||
| 316 | - entry.container, "-" | ||
| 317 | - )); | ||
| 318 | - continue; | ||
| 319 | - } | ||
| 320 | - match sweep_file(entry, &es, bit_depth) { | ||
| 321 | - Ok(c) if c.differing_frames > 0 => { | ||
| 322 | - failures.push(format!("{name}: {} frames differ", c.differing_frames)); | ||
| 323 | - table.push_str(&format!( | ||
| 324 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n", | ||
| 325 | - entry.container, c.compared, c.differing_frames, c.compared, | ||
| 326 | - c.first_diff.clone().unwrap_or_default() | ||
| 327 | - )); | ||
| 328 | - } | ||
| 329 | - Ok(c) => { | ||
| 330 | - decoded += 1; | ||
| 331 | - table.push_str(&format!( | ||
| 332 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n", | ||
| 333 | - entry.container, | ||
| 334 | - c.compared, | ||
| 335 | - if c.oracle_short { | ||
| 336 | - " (ffmpeg stopped early)" | ||
| 337 | - } else { | ||
| 338 | - "" | ||
| 339 | - } | ||
| 340 | - )); | ||
| 341 | - } | ||
| 342 | - Err(e) if e.contains("unsupported") => { | ||
| 343 | - refused += 1; | ||
| 344 | - table.push_str(&format!( | ||
| 345 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n", | ||
| 346 | - entry.container, "-" | ||
| 347 | - )); | ||
| 348 | - } | ||
| 349 | - Err(e) => { | ||
| 350 | - failures.push(format!("{name}: {e}")); | ||
| 351 | - table.push_str(&format!( | ||
| 352 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n", | ||
| 353 | - entry.container, "-" | ||
| 354 | - )); | ||
| 355 | - } | ||
| 356 | - } | ||
| 357 | - let _ = std::fs::remove_file(&es); | ||
| 358 | - } | ||
| 359 | - let _ = std::fs::remove_dir_all(&dir); | ||
| 360 | - eprintln!("{table}"); | ||
| 361 | - eprintln!( | ||
| 362 | - "real library hevc: {decoded} bit-exact, {refused} refused by name, {} failed", | ||
| 363 | - failures.len() | ||
| 364 | - ); | ||
| 365 | - assert!(failures.is_empty(), "{failures:#?}"); | ||
| 366 | - assert!(decoded >= 1, "no real HEVC file was swept end to end"); | ||
| 367 | -} | ||
crates/ec-h265/tests/it/scaling_lists.rsdeleted+0 -111
| @@ -1,111 +0,0 @@ | |||
| 1 | -//! Scaling-list streams, checked against ffmpeg. | ||
| 2 | -//! | ||
| 3 | -//! The SLIST conformance streams code their own lists in the SPS and PPS. Most of | ||
| 4 | -//! their pictures are B slices, which this decoder does not pixel-decode yet, so the | ||
| 5 | -//! check is on the first picture in output order: an IDR, intra only, decoded with | ||
| 6 | -//! the stream's lists. It must match ffmpeg sample for sample after cropping. | ||
| 7 | - | ||
| 8 | -use ec_h265::Decoder; | ||
| 9 | -use ec_h265::dec::Frame; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -/// The four scaling-list streams the picture-management sweep covers; `str` is | ||
| 13 | -/// the SLIST_D stream. | ||
| 14 | -const STREAMS: [&str; 4] = [ | ||
| 15 | - "SLIST_A_Sony_5/SLIST_A_Sony_5/SLIST_A_Sony_5.bin", | ||
| 16 | - "SLIST_B_Sony_9/SLIST_B_Sony_9/SLIST_B_Sony_9.bin", | ||
| 17 | - "SLIST_C_Sony_4/SLIST_C_Sony_4/SLIST_C_Sony_4.bin", | ||
| 18 | - "SLIST_D_Sony_9/SLIST_D_Sony_9/str.bin", | ||
| 19 | -]; | ||
| 20 | - | ||
| 21 | -fn vectors_dir() -> PathBuf { | ||
| 22 | - ec_testkit::fixture("vectors/hevc-jctvc") | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -/// The first output picture as 4:2:0 bytes cropped to the conformance window. | ||
| 26 | -fn cropped_yuv(frame: &Frame) -> Vec<u8> { | ||
| 27 | - let pic = &frame.picture; | ||
| 28 | - let win = &frame.window; | ||
| 29 | - // Conformance window offsets are in chroma samples for 4:2:0. | ||
| 30 | - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); | ||
| 31 | - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); | ||
| 32 | - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); | ||
| 33 | - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); | ||
| 34 | - let mut out = Vec::new(); | ||
| 35 | - for row in ly0..ly1 { | ||
| 36 | - out.extend( | ||
| 37 | - pic.y[row * pic.width + lx0..row * pic.width + lx1] | ||
| 38 | - .iter() | ||
| 39 | - .map(|&v| v as u8), | ||
| 40 | - ); | ||
| 41 | - } | ||
| 42 | - let cw = pic.width / 2; | ||
| 43 | - for plane in [&pic.cb, &pic.cr] { | ||
| 44 | - for row in cy0..cy1 { | ||
| 45 | - out.extend( | ||
| 46 | - plane[row * cw + cx0..row * cw + cx1] | ||
| 47 | - .iter() | ||
| 48 | - .map(|&v| v as u8), | ||
| 49 | - ); | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - out | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -/// The first frame of `path` as ffmpeg decodes it, in yuv420p. | ||
| 56 | -fn ffmpeg_first_frame(path: &Path, tag: &str) -> Result<Vec<u8>, String> { | ||
| 57 | - let out = std::env::temp_dir().join(format!("ec-h265-scaling-{tag}.yuv")); | ||
| 58 | - let status = ec_testkit::ffmpeg() | ||
| 59 | - .args(["-v", "error", "-y", "-i"]) | ||
| 60 | - .arg(path) | ||
| 61 | - .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 62 | - .arg(&out) | ||
| 63 | - .output() | ||
| 64 | - .map_err(|e| e.to_string())?; | ||
| 65 | - if !status.status.success() { | ||
| 66 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 67 | - } | ||
| 68 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -// Ignored until the intra path decodes the syntax these streams use: the decode | ||
| 72 | -// desyncs at the last CTB of the IDR, and the intra CTU loop has no SAO or | ||
| 73 | -// cu_qp_delta parsing. Run with `--ignored` to see the failure. | ||
| 74 | -#[ignore = "intra path lacks the syntax these streams use (desync at the IDR's last CTB)"] | ||
| 75 | -#[test] | ||
| 76 | -fn first_picture_of_each_scaling_list_stream_matches_ffmpeg() { | ||
| 77 | - let dir = vectors_dir(); | ||
| 78 | - let mut checked = 0usize; | ||
| 79 | - for rel in STREAMS { | ||
| 80 | - let path = dir.join(rel); | ||
| 81 | - let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{rel}: {e}")); | ||
| 82 | - let mut decoder = Decoder::new(); | ||
| 83 | - decoder | ||
| 84 | - .decode_annex_b(&data) | ||
| 85 | - .unwrap_or_else(|e| panic!("{rel}: decode failed: {e}")); | ||
| 86 | - decoder | ||
| 87 | - .flush() | ||
| 88 | - .unwrap_or_else(|e| panic!("{rel}: flush failed: {e}")); | ||
| 89 | - let frame = decoder | ||
| 90 | - .next_frame() | ||
| 91 | - .unwrap_or_else(|| panic!("{rel}: no picture out")); | ||
| 92 | - let ours = cropped_yuv(&frame); | ||
| 93 | - let tag = rel.replace('/', "_"); | ||
| 94 | - let theirs = | ||
| 95 | - ffmpeg_first_frame(&path, &tag).unwrap_or_else(|e| panic!("{rel}: ffmpeg failed: {e}")); | ||
| 96 | - assert_eq!( | ||
| 97 | - ours.len(), | ||
| 98 | - theirs.len(), | ||
| 99 | - "{rel}: picture is {} bytes, ffmpeg's is {}", | ||
| 100 | - ours.len(), | ||
| 101 | - theirs.len() | ||
| 102 | - ); | ||
| 103 | - let differing = ours.iter().zip(&theirs).filter(|(a, b)| a != b).count(); | ||
| 104 | - assert_eq!( | ||
| 105 | - differing, 0, | ||
| 106 | - "{rel}: {differing} samples differ from ffmpeg in the first picture" | ||
| 107 | - ); | ||
| 108 | - checked += 1; | ||
| 109 | - } | ||
| 110 | - eprintln!("scaling-list check: {checked} first pictures bit-exact against ffmpeg"); | ||
| 111 | -} | ||