| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 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 | use std::process::Command; |
| 12 | |
| 13 | fn scratch_dir() -> PathBuf { |
| 14 | let dir = std::env::temp_dir().join("ec-h265-tests"); |
| 15 | std::fs::create_dir_all(&dir).expect("scratch dir"); |
| 16 | dir |
| 17 | } |
| 18 | |
| 19 | fn have_ffmpeg() -> bool { |
| 20 | Command::new("ffmpeg") |
| 21 | .arg("-version") |
| 22 | .output() |
| 23 | .map(|o| o.status.success()) |
| 24 | .unwrap_or(false) |
| 25 | } |
| 26 | |
| 27 | |
| 28 | fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> { |
| 29 | let out = path.with_extension("yuv"); |
| 30 | let status = Command::new("ffmpeg") |
| 31 | .args(["-v", "error", "-y", "-i"]) |
| 32 | .arg(path) |
| 33 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 34 | .arg(&out) |
| 35 | .output() |
| 36 | .map_err(|e| e.to_string())?; |
| 37 | if !status.status.success() { |
| 38 | return Err(String::from_utf8_lossy(&status.stderr).to_string()); |
| 39 | } |
| 40 | let stderr = String::from_utf8_lossy(&status.stderr).to_string(); |
| 41 | if !stderr.trim().is_empty() { |
| 42 | return Err(format!("ffmpeg complained: {stderr}")); |
| 43 | } |
| 44 | std::fs::read(&out).map_err(|e| e.to_string()) |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { |
| 56 | let path = scratch_dir().join(format!("{name}.265")); |
| 57 | pin_or_panic("write_au", &path, &picture.au); |
| 58 | path |
| 59 | } |
| 60 | |
| 61 | fn planes_of(frame: &VideoFrame) -> Vec<u8> { |
| 62 | let mut out = Vec::new(); |
| 63 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 64 | for (i, plane) in frame.planes.iter().enumerate() { |
| 65 | let (pw, ph) = if i == 0 { |
| 66 | (w, h) |
| 67 | } else { |
| 68 | (w.div_ceil(2), h.div_ceil(2)) |
| 69 | }; |
| 70 | for row in 0..ph { |
| 71 | out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); |
| 72 | } |
| 73 | } |
| 74 | out |
| 75 | } |
| 76 | |
| 77 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 78 | assert_eq!(a.len(), b.len()); |
| 79 | let mse: f64 = a |
| 80 | .iter() |
| 81 | .zip(b) |
| 82 | .map(|(x, y)| { |
| 83 | let d = f64::from(*x) - f64::from(*y); |
| 84 | d * d |
| 85 | }) |
| 86 | .sum::<f64>() |
| 87 | / a.len() as f64; |
| 88 | if mse == 0.0 { |
| 89 | 99.0 |
| 90 | } else { |
| 91 | 10.0 * (255.0 * 255.0 / mse).log10() |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | |
| 96 | fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) { |
| 97 | encode_with(width, height, qp, ctb, false, false) |
| 98 | } |
| 99 | |
| 100 | fn encode_with( |
| 101 | width: u32, |
| 102 | height: u32, |
| 103 | qp: i32, |
| 104 | ctb: Option<usize>, |
| 105 | chroma_mode_search: bool, |
| 106 | intra_nxn: bool, |
| 107 | ) -> (VideoFrame, EncodedPicture) { |
| 108 | let mut cfg = EncoderConfig::new(width, height); |
| 109 | cfg.chroma_mode_search = chroma_mode_search; |
| 110 | cfg.intra_nxn = intra_nxn; |
| 111 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 112 | if let Some(ctb) = ctb { |
| 113 | cfg.ctb_size = ctb; |
| 114 | } |
| 115 | cfg.keep_recon = true; |
| 116 | cfg.picture_hash = true; |
| 117 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 118 | let frame = test_frame(width, height, 0); |
| 119 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 120 | (frame, coded) |
| 121 | } |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | fn encode_natural( |
| 127 | width: u32, |
| 128 | height: u32, |
| 129 | qp: i32, |
| 130 | intra_nxn: bool, |
| 131 | ) -> (VideoFrame, EncodedPicture) { |
| 132 | let mut cfg = EncoderConfig::new(width, height); |
| 133 | cfg.intra_nxn = intra_nxn; |
| 134 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 135 | cfg.keep_recon = true; |
| 136 | cfg.picture_hash = true; |
| 137 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 138 | let frame = natural_frame(width, height, 0); |
| 139 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 140 | (frame, coded) |
| 141 | } |
| 142 | |
| 143 | |
| 144 | |
| 145 | |
| 146 | |
| 147 | |
| 148 | #[test] |
| 149 | fn chroma_mode_search_decodes_bit_exactly() { |
| 150 | if !have_ffmpeg() { |
| 151 | eprintln!("skipping: ffmpeg not installed"); |
| 152 | return; |
| 153 | } |
| 154 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 155 | let (source, coded) = encode_with(w, h, 27, None, true, false); |
| 156 | let (_, derived) = encode_with(w, h, 27, None, false, false); |
| 157 | let name = format!("chroma-rd-{w}x{h}"); |
| 158 | assert_ne!( |
| 159 | coded.au, derived.au, |
| 160 | "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" |
| 161 | ); |
| 162 | let path = write_au(&name, &coded); |
| 163 | let decoded = match ffmpeg_decode(&path) { |
| 164 | Ok(bytes) => bytes, |
| 165 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 166 | }; |
| 167 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 168 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 169 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 170 | if mismatches != 0 { |
| 171 | |
| 172 | |
| 173 | let luma = (w * h) as usize; |
| 174 | let chroma = luma / 4; |
| 175 | let first = decoded |
| 176 | .iter() |
| 177 | .zip(&recon) |
| 178 | .position(|(a, b)| a != b) |
| 179 | .unwrap(); |
| 180 | let count = |range: std::ops::Range<usize>| { |
| 181 | decoded[range.clone()] |
| 182 | .iter() |
| 183 | .zip(&recon[range]) |
| 184 | .filter(|(a, b)| a != b) |
| 185 | .count() |
| 186 | }; |
| 187 | let mut map = String::new(); |
| 188 | for by in (0..h as usize).step_by(16) { |
| 189 | for bx in (0..w as usize).step_by(16) { |
| 190 | let mut c = 0; |
| 191 | for row in by..by + 16 { |
| 192 | for col in bx..bx + 16 { |
| 193 | let i = row * w as usize + col; |
| 194 | if decoded[i] != recon[i] { |
| 195 | c += 1; |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | map.push_str(&format!("{c:4}")); |
| 200 | } |
| 201 | map.push('\n'); |
| 202 | } |
| 203 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 204 | panic!( |
| 205 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 206 | ({}, {})", |
| 207 | count(0..luma), |
| 208 | count(luma..luma + chroma), |
| 209 | count(luma + chroma..luma + 2 * chroma), |
| 210 | first % w as usize, |
| 211 | first / w as usize, |
| 212 | ); |
| 213 | } |
| 214 | let quality = psnr(&planes_of(&source), &recon); |
| 215 | assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | #[test] |
| 226 | fn intra_nxn_decodes_bit_exactly() { |
| 227 | if !have_ffmpeg() { |
| 228 | eprintln!("skipping: ffmpeg not installed"); |
| 229 | return; |
| 230 | } |
| 231 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 232 | let (source, coded) = encode_natural(w, h, 22, true); |
| 233 | let (_, square) = encode_natural(w, h, 22, false); |
| 234 | let name = format!("intra-nxn-{w}x{h}"); |
| 235 | assert_ne!( |
| 236 | coded.au, square.au, |
| 237 | "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" |
| 238 | ); |
| 239 | let path = write_au(&name, &coded); |
| 240 | let decoded = match ffmpeg_decode(&path) { |
| 241 | Ok(bytes) => bytes, |
| 242 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 243 | }; |
| 244 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 245 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 246 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 247 | if mismatches != 0 { |
| 248 | |
| 249 | |
| 250 | let luma = (w * h) as usize; |
| 251 | let chroma = luma / 4; |
| 252 | let first = decoded |
| 253 | .iter() |
| 254 | .zip(&recon) |
| 255 | .position(|(a, b)| a != b) |
| 256 | .unwrap(); |
| 257 | let count = |range: std::ops::Range<usize>| { |
| 258 | decoded[range.clone()] |
| 259 | .iter() |
| 260 | .zip(&recon[range]) |
| 261 | .filter(|(a, b)| a != b) |
| 262 | .count() |
| 263 | }; |
| 264 | let mut map = String::new(); |
| 265 | for by in (0..h as usize).step_by(16) { |
| 266 | for bx in (0..w as usize).step_by(16) { |
| 267 | let mut c = 0; |
| 268 | for row in by..by + 16 { |
| 269 | for col in bx..bx + 16 { |
| 270 | let i = row * w as usize + col; |
| 271 | if decoded[i] != recon[i] { |
| 272 | c += 1; |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | map.push_str(&format!("{c:4}")); |
| 277 | } |
| 278 | map.push('\n'); |
| 279 | } |
| 280 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 281 | panic!( |
| 282 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 283 | ({}, {})", |
| 284 | count(0..luma), |
| 285 | count(luma..luma + chroma), |
| 286 | count(luma + chroma..luma + 2 * chroma), |
| 287 | first % w as usize, |
| 288 | first / w as usize, |
| 289 | ); |
| 290 | } |
| 291 | let quality = psnr(&planes_of(&source), &recon); |
| 292 | assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | #[test] |
| 307 | fn sign_hiding_decodes_bit_exactly() { |
| 308 | if !have_ffmpeg() { |
| 309 | eprintln!("skipping: ffmpeg not installed"); |
| 310 | return; |
| 311 | } |
| 312 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 313 | let (source, coded) = encode_sdh(w, h, 22, true); |
| 314 | let (_, plain) = encode_sdh(w, h, 22, false); |
| 315 | let name = format!("sign-hiding-{w}x{h}"); |
| 316 | assert_ne!( |
| 317 | coded.au, plain.au, |
| 318 | "{name}: no sub-block ever qualified, so this decode proves nothing" |
| 319 | ); |
| 320 | let path = write_au(&name, &coded); |
| 321 | let decoded = match ffmpeg_decode(&path) { |
| 322 | Ok(bytes) => bytes, |
| 323 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 324 | }; |
| 325 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 326 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 327 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 328 | if mismatches != 0 { |
| 329 | |
| 330 | |
| 331 | let luma = (w * h) as usize; |
| 332 | let chroma = luma / 4; |
| 333 | let first = decoded |
| 334 | .iter() |
| 335 | .zip(&recon) |
| 336 | .position(|(a, b)| a != b) |
| 337 | .unwrap(); |
| 338 | let count = |range: std::ops::Range<usize>| { |
| 339 | decoded[range.clone()] |
| 340 | .iter() |
| 341 | .zip(&recon[range]) |
| 342 | .filter(|(a, b)| a != b) |
| 343 | .count() |
| 344 | }; |
| 345 | let mut map = String::new(); |
| 346 | for by in (0..h as usize).step_by(16) { |
| 347 | for bx in (0..w as usize).step_by(16) { |
| 348 | let mut c = 0; |
| 349 | for row in by..by + 16 { |
| 350 | for col in bx..bx + 16 { |
| 351 | let i = row * w as usize + col; |
| 352 | if decoded[i] != recon[i] { |
| 353 | c += 1; |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | map.push_str(&format!("{c:4}")); |
| 358 | } |
| 359 | map.push('\n'); |
| 360 | } |
| 361 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 362 | panic!( |
| 363 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 364 | ({}, {})", |
| 365 | count(0..luma), |
| 366 | count(luma..luma + chroma), |
| 367 | count(luma + chroma..luma + 2 * chroma), |
| 368 | first % w as usize, |
| 369 | first / w as usize, |
| 370 | ); |
| 371 | } |
| 372 | let quality = psnr(&planes_of(&source), &recon); |
| 373 | assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | |
| 378 | |
| 379 | fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { |
| 380 | let mut cfg = EncoderConfig::new(width, height); |
| 381 | cfg.sign_hiding = sign_hiding; |
| 382 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 383 | cfg.keep_recon = true; |
| 384 | cfg.picture_hash = true; |
| 385 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 386 | let frame = natural_frame(width, height, 0); |
| 387 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 388 | (frame, coded) |
| 389 | } |
| 390 | |
| 391 | |
| 392 | |
| 393 | fn encode_tskip( |
| 394 | width: u32, |
| 395 | height: u32, |
| 396 | qp: i32, |
| 397 | tskip: TransformSkip, |
| 398 | ) -> (VideoFrame, EncodedPicture) { |
| 399 | let mut cfg = EncoderConfig::new(width, height); |
| 400 | cfg.transform_skip = tskip; |
| 401 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 402 | cfg.keep_recon = true; |
| 403 | cfg.picture_hash = true; |
| 404 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 405 | let frame = natural_frame(width, height, 0); |
| 406 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 407 | (frame, coded) |
| 408 | } |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | #[test] |
| 416 | fn transform_skip_decodes_bit_exactly() { |
| 417 | if !have_ffmpeg() { |
| 418 | eprintln!("skipping: ffmpeg not installed"); |
| 419 | return; |
| 420 | } |
| 421 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 422 | let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4); |
| 423 | let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off); |
| 424 | let name = format!("transform-skip-{w}x{h}"); |
| 425 | assert_ne!( |
| 426 | coded.au, plain.au, |
| 427 | "{name}: no TU ever skipped, so this decode proves nothing" |
| 428 | ); |
| 429 | let path = write_au(&name, &coded); |
| 430 | let decoded = match ffmpeg_decode(&path) { |
| 431 | Ok(bytes) => bytes, |
| 432 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 433 | }; |
| 434 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 435 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 436 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 437 | if mismatches != 0 { |
| 438 | |
| 439 | |
| 440 | let luma = (w * h) as usize; |
| 441 | let chroma = luma / 4; |
| 442 | let first = decoded |
| 443 | .iter() |
| 444 | .zip(&recon) |
| 445 | .position(|(a, b)| a != b) |
| 446 | .unwrap(); |
| 447 | let count = |range: std::ops::Range<usize>| { |
| 448 | decoded[range.clone()] |
| 449 | .iter() |
| 450 | .zip(&recon[range]) |
| 451 | .filter(|(a, b)| a != b) |
| 452 | .count() |
| 453 | }; |
| 454 | let mut map = String::new(); |
| 455 | for by in (0..h as usize).step_by(16) { |
| 456 | for bx in (0..w as usize).step_by(16) { |
| 457 | let mut c = 0; |
| 458 | for row in by..by + 16 { |
| 459 | for col in bx..bx + 16 { |
| 460 | let i = row * w as usize + col; |
| 461 | if decoded[i] != recon[i] { |
| 462 | c += 1; |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | map.push_str(&format!("{c:4}")); |
| 467 | } |
| 468 | map.push('\n'); |
| 469 | } |
| 470 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 471 | panic!( |
| 472 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 473 | ({}, {})", |
| 474 | count(0..luma), |
| 475 | count(luma..luma + chroma), |
| 476 | count(luma + chroma..luma + 2 * chroma), |
| 477 | first % w as usize, |
| 478 | first / w as usize, |
| 479 | ); |
| 480 | } |
| 481 | let quality = psnr(&planes_of(&source), &recon); |
| 482 | assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); |
| 483 | } |
| 484 | } |
| 485 | #[test] |
| 486 | fn ffmpeg_decodes_bit_exactly_at_every_shape() { |
| 487 | if !have_ffmpeg() { |
| 488 | eprintln!("skipping: ffmpeg not installed"); |
| 489 | return; |
| 490 | } |
| 491 | |
| 492 | |
| 493 | |
| 494 | |
| 495 | for &(w, h, ctb) in &[ |
| 496 | (64u32, 64u32, None), |
| 497 | (130, 66, None), |
| 498 | (1916, 1080, None), |
| 499 | (352, 288, None), |
| 500 | (1916, 1080, Some(64)), |
| 501 | (130, 66, Some(64)), |
| 502 | ] { |
| 503 | let (source, coded) = encode(w, h, 27, ctb); |
| 504 | let name = format!( |
| 505 | "shape-{w}x{h}-ctb{}", |
| 506 | ctb.map_or("default".to_string(), |c| c.to_string()) |
| 507 | ); |
| 508 | let path = write_au(&name, &coded); |
| 509 | let decoded = match ffmpeg_decode(&path) { |
| 510 | Ok(bytes) => bytes, |
| 511 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 512 | }; |
| 513 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 514 | assert_eq!( |
| 515 | decoded.len(), |
| 516 | recon.len(), |
| 517 | "{name}: decoded {} bytes, reconstruction {} bytes", |
| 518 | decoded.len(), |
| 519 | recon.len() |
| 520 | ); |
| 521 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 522 | if mismatches != 0 { |
| 523 | |
| 524 | |
| 525 | let luma = (w * h) as usize; |
| 526 | let chroma = luma / 4; |
| 527 | let first = decoded |
| 528 | .iter() |
| 529 | .zip(&recon) |
| 530 | .position(|(a, b)| a != b) |
| 531 | .unwrap(); |
| 532 | let count = |range: std::ops::Range<usize>| { |
| 533 | decoded[range.clone()] |
| 534 | .iter() |
| 535 | .zip(&recon[range]) |
| 536 | .filter(|(a, b)| a != b) |
| 537 | .count() |
| 538 | }; |
| 539 | let mut map = String::new(); |
| 540 | for by in (0..h as usize).step_by(16) { |
| 541 | for bx in (0..w as usize).step_by(16) { |
| 542 | let mut c = 0; |
| 543 | for row in by..by + 16 { |
| 544 | for col in bx..bx + 16 { |
| 545 | let i = row * w as usize + col; |
| 546 | if decoded[i] != recon[i] { |
| 547 | c += 1; |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | map.push_str(&format!("{c:4}")); |
| 552 | } |
| 553 | map.push('\n'); |
| 554 | } |
| 555 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 556 | panic!( |
| 557 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 558 | ({}, {})", |
| 559 | count(0..luma), |
| 560 | count(luma..luma + chroma), |
| 561 | count(luma + chroma..luma + 2 * chroma), |
| 562 | first % w as usize, |
| 563 | first / w as usize, |
| 564 | ); |
| 565 | } |
| 566 | |
| 567 | let quality = psnr(&planes_of(&source), &recon); |
| 568 | assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | #[test] |
| 579 | fn cu64_decodes_bit_exactly() { |
| 580 | if !have_ffmpeg() { |
| 581 | eprintln!("skipping: ffmpeg not installed"); |
| 582 | return; |
| 583 | } |
| 584 | |
| 585 | |
| 586 | |
| 587 | for &(w, h, qp, fires) in &[ |
| 588 | (352u32, 288u32, 32i32, true), |
| 589 | (256, 256, 37, true), |
| 590 | (130, 66, 32, false), |
| 591 | ] { |
| 592 | let (source, off) = encode_cu64(w, h, qp, false); |
| 593 | let (_, on) = encode_cu64(w, h, qp, true); |
| 594 | let name = format!("cu64-{w}x{h}-qp{qp}"); |
| 595 | if fires { |
| 596 | assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); |
| 597 | } |
| 598 | |
| 599 | let path = write_au(&name, &on); |
| 600 | let decoded = match ffmpeg_decode(&path) { |
| 601 | Ok(bytes) => bytes, |
| 602 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 603 | }; |
| 604 | let recon = planes_of(on.recon.as_ref().expect("recon kept")); |
| 605 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 606 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 607 | if mismatches != 0 { |
| 608 | let first = decoded |
| 609 | .iter() |
| 610 | .zip(&recon) |
| 611 | .position(|(a, b)| a != b) |
| 612 | .unwrap(); |
| 613 | let luma = (w * h) as usize; |
| 614 | panic!( |
| 615 | "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", |
| 616 | first % w as usize, |
| 617 | first / w as usize, |
| 618 | decoded[..luma] |
| 619 | .iter() |
| 620 | .zip(&recon[..luma]) |
| 621 | .filter(|(a, b)| a != b) |
| 622 | .count(), |
| 623 | ); |
| 624 | } |
| 625 | let quality = psnr(&planes_of(&source), &recon); |
| 626 | assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { |
| 631 | let mut cfg = EncoderConfig::new(width, height); |
| 632 | cfg.ctb_size = 64; |
| 633 | cfg.cu64 = cu64; |
| 634 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 635 | cfg.keep_recon = true; |
| 636 | cfg.picture_hash = true; |
| 637 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 638 | let frame = natural_frame(width, height, 0); |
| 639 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 640 | (frame, coded) |
| 641 | } |
| 642 | |
| 643 | |
| 644 | |
| 645 | #[test] |
| 646 | fn the_default_tree_costs_almost_nothing_against_64() { |
| 647 | let source = natural_frame(1920, 1080, 0); |
| 648 | let mut coded = Vec::new(); |
| 649 | for ctb in [32usize, 64] { |
| 650 | let mut cfg = EncoderConfig::new(1920, 1080); |
| 651 | cfg.rate_control = RateControl::ConstantQp(27); |
| 652 | cfg.ctb_size = ctb; |
| 653 | cfg.keep_recon = true; |
| 654 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 655 | let picture = encoder.encode_idr(&source).expect("encode"); |
| 656 | let quality = psnr( |
| 657 | &planes_of(&source), |
| 658 | &planes_of(picture.recon.as_ref().unwrap()), |
| 659 | ); |
| 660 | coded.push((picture.au.len(), quality)); |
| 661 | } |
| 662 | let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); |
| 663 | println!( |
| 664 | "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ |
| 665 | ({:+.1}% bits, {:+.2} dB)", |
| 666 | (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, |
| 667 | psnr32 - psnr64 |
| 668 | ); |
| 669 | assert!( |
| 670 | |
| 671 | |
| 672 | (bits32 as f64) < bits64 as f64 * 1.03, |
| 673 | "CTB 32 spent {bits32} bytes against 64's {bits64}" |
| 674 | ); |
| 675 | assert!( |
| 676 | (psnr32 - psnr64).abs() < 0.1, |
| 677 | "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" |
| 678 | ); |
| 679 | } |
| 680 | |
| 681 | #[test] |
| 682 | fn ffmpeg_verifies_the_decoded_picture_hash() { |
| 683 | |
| 684 | |
| 685 | |
| 686 | |
| 687 | if !have_ffmpeg() { |
| 688 | eprintln!("skipping: ffmpeg not installed"); |
| 689 | return; |
| 690 | } |
| 691 | let (_, coded) = encode(352, 288, 30, None); |
| 692 | let path = write_au("hash-352x288", &coded); |
| 693 | let output = Command::new("ffmpeg") |
| 694 | .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) |
| 695 | .arg(&path) |
| 696 | .args(["-f", "null", "-"]) |
| 697 | .output() |
| 698 | .expect("run ffmpeg"); |
| 699 | let log = String::from_utf8_lossy(&output.stderr).to_string(); |
| 700 | let checks: Vec<&str> = log |
| 701 | .lines() |
| 702 | .filter(|line| line.contains("Verifying checksum")) |
| 703 | .collect(); |
| 704 | assert!(!checks.is_empty(), "ffmpeg checked no picture hash: {log}"); |
| 705 | for line in checks { |
| 706 | assert_eq!(line.matches("correct").count(), 3, "hash mismatch: {line}"); |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn vaapi_hardware_decodes_the_stream() { |
| 712 | |
| 713 | |
| 714 | |
| 715 | if !have_ffmpeg() || !Path::new("/dev/dri/renderD128").exists() { |
| 716 | eprintln!("skipping: no ffmpeg or no VA-API render node"); |
| 717 | return; |
| 718 | } |
| 719 | let (_, coded) = encode(1920, 1080, 27, None); |
| 720 | let path = write_au("vaapi-1080p", &coded); |
| 721 | let output = Command::new("ffmpeg") |
| 722 | .args([ |
| 723 | "-v", |
| 724 | "error", |
| 725 | "-hwaccel", |
| 726 | "vaapi", |
| 727 | "-hwaccel_device", |
| 728 | "/dev/dri/renderD128", |
| 729 | "-i", |
| 730 | ]) |
| 731 | .arg(&path) |
| 732 | .args(["-f", "null", "-"]) |
| 733 | .output() |
| 734 | .expect("run ffmpeg"); |
| 735 | let stderr = String::from_utf8_lossy(&output.stderr).to_string(); |
| 736 | if stderr.contains("Failed to initialise VAAPI") |
| 737 | || stderr.contains("No VA display found") |
| 738 | || stderr.contains("Device creation failed") |
| 739 | { |
| 740 | eprintln!("skipping: VA-API unavailable here ({})", stderr.trim()); |
| 741 | return; |
| 742 | } |
| 743 | assert!( |
| 744 | output.status.success() && stderr.trim().is_empty(), |
| 745 | "VA-API decode failed: {stderr}" |
| 746 | ); |
| 747 | } |
| 748 | |
| 749 | #[test] |
| 750 | fn quality_rises_as_qp_falls() { |
| 751 | let mut previous = 0.0; |
| 752 | for &qp in &[40i32, 32, 27, 22] { |
| 753 | let (source, coded) = encode(256, 144, qp, None); |
| 754 | let recon = planes_of(coded.recon.as_ref().expect("recon")); |
| 755 | let quality = psnr(&planes_of(&source), &recon); |
| 756 | assert!( |
| 757 | quality > previous, |
| 758 | "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" |
| 759 | ); |
| 760 | previous = quality; |
| 761 | } |
| 762 | assert!( |
| 763 | previous > 40.0, |
| 764 | "QP 22 should clear 40 dB, got {previous:.2}" |
| 765 | ); |
| 766 | } |
| 767 | |
| 768 | #[test] |
| 769 | fn threads_do_not_change_the_bitstream() { |
| 770 | let mut cfg = EncoderConfig::new(320, 192); |
| 771 | cfg.rate_control = RateControl::ConstantQp(30); |
| 772 | cfg.threads = 1; |
| 773 | let single = Encoder::new(cfg.clone()).unwrap(); |
| 774 | cfg.threads = 8; |
| 775 | let many = Encoder::new(cfg).unwrap(); |
| 776 | let frame = test_frame(320, 192, 3); |
| 777 | let a = single.encode_idr(&frame).unwrap(); |
| 778 | let b = many.encode_idr(&frame).unwrap(); |
| 779 | assert_eq!(a.au, b.au, "wavefront changed the bitstream"); |
| 780 | } |
| 781 | |
| 782 | #[test] |
| 783 | fn a_bit_target_lands_near_its_target() { |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | let mut previous = 0usize; |
| 789 | for target in [400_000u64, 1_200_000, 3_000_000] { |
| 790 | let mut cfg = EncoderConfig::new(640, 360); |
| 791 | cfg.rate_control = RateControl::TargetBits(target); |
| 792 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 793 | let frame = test_frame(640, 360, 5); |
| 794 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 795 | let bits = coded.au.len() * 8; |
| 796 | assert!( |
| 797 | bits > previous, |
| 798 | "target {target}: {bits} bits did not grow with the target" |
| 799 | ); |
| 800 | previous = bits; |
| 801 | let ratio = bits as f64 / target as f64; |
| 802 | assert!( |
| 803 | (0.4..2.5).contains(&ratio), |
| 804 | "target {target}: got {bits} bits (x{ratio:.2}) at QP {}", |
| 805 | coded.qp |
| 806 | ); |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | #[test] |
| 811 | fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { |
| 812 | let cfg = EncoderConfig::new(128, 96); |
| 813 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 814 | let frames: Vec<VideoFrame> = (0..3).map(|i| test_frame(128, 96, i * 11)).collect(); |
| 815 | let coded = encoder.encode_batch(frames.iter()).expect("batch encode"); |
| 816 | assert_eq!(coded.len(), 3); |
| 817 | for picture in &coded { |
| 818 | |
| 819 | let nals = ec_h265_syntax::split_annex_b(&picture.au); |
| 820 | let types: Vec<_> = nals.iter().map(|n| n.header.nal_type).collect(); |
| 821 | assert_eq!( |
| 822 | &types[..4], |
| 823 | &[ |
| 824 | ec_h265_syntax::NalUnitType::Vps, |
| 825 | ec_h265_syntax::NalUnitType::Sps, |
| 826 | ec_h265_syntax::NalUnitType::Pps, |
| 827 | ec_h265_syntax::NalUnitType::IdrWRadl, |
| 828 | ], |
| 829 | "access unit is not self-contained" |
| 830 | ); |
| 831 | } |
| 832 | |
| 833 | assert_ne!(coded[0].au, coded[1].au); |
| 834 | } |
| 835 | |
| 836 | |
| 837 | |
| 838 | |
| 839 | #[test] |
| 840 | fn rdoq_decodes_bit_exactly() { |
| 841 | if !have_ffmpeg() { |
| 842 | eprintln!("skipping: ffmpeg not installed"); |
| 843 | return; |
| 844 | } |
| 845 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 846 | let (source, coded) = encode_rdoq(w, h, 27, true); |
| 847 | let (_, plain) = encode_rdoq(w, h, 27, false); |
| 848 | let name = format!("rdoq-{w}x{h}"); |
| 849 | assert_ne!( |
| 850 | coded.au, plain.au, |
| 851 | "{name}: the level search changed no byte, so it is not running" |
| 852 | ); |
| 853 | let path = write_au(&name, &coded); |
| 854 | let decoded = match ffmpeg_decode(&path) { |
| 855 | Ok(bytes) => bytes, |
| 856 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 857 | }; |
| 858 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 859 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 860 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 861 | if mismatches != 0 { |
| 862 | |
| 863 | |
| 864 | let luma = (w * h) as usize; |
| 865 | let chroma = luma / 4; |
| 866 | let first = decoded |
| 867 | .iter() |
| 868 | .zip(&recon) |
| 869 | .position(|(a, b)| a != b) |
| 870 | .unwrap(); |
| 871 | let count = |range: std::ops::Range<usize>| { |
| 872 | decoded[range.clone()] |
| 873 | .iter() |
| 874 | .zip(&recon[range]) |
| 875 | .filter(|(a, b)| a != b) |
| 876 | .count() |
| 877 | }; |
| 878 | let mut map = String::new(); |
| 879 | for by in (0..h as usize).step_by(16) { |
| 880 | for bx in (0..w as usize).step_by(16) { |
| 881 | let mut c = 0; |
| 882 | for row in by..by + 16 { |
| 883 | for col in bx..bx + 16 { |
| 884 | let i = row * w as usize + col; |
| 885 | if decoded[i] != recon[i] { |
| 886 | c += 1; |
| 887 | } |
| 888 | } |
| 889 | } |
| 890 | map.push_str(&format!("{c:4}")); |
| 891 | } |
| 892 | map.push('\n'); |
| 893 | } |
| 894 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 895 | panic!( |
| 896 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 897 | ({}, {})", |
| 898 | count(0..luma), |
| 899 | count(luma..luma + chroma), |
| 900 | count(luma + chroma..luma + 2 * chroma), |
| 901 | first % w as usize, |
| 902 | first / w as usize, |
| 903 | ); |
| 904 | } |
| 905 | let quality = psnr(&planes_of(&source), &recon); |
| 906 | assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | |
| 911 | |
| 912 | fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { |
| 913 | let mut cfg = EncoderConfig::new(width, height); |
| 914 | cfg.rdoq = rdoq; |
| 915 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 916 | cfg.keep_recon = true; |
| 917 | cfg.picture_hash = true; |
| 918 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 919 | let frame = natural_frame(width, height, 0); |
| 920 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 921 | (frame, coded) |
| 922 | } |
| 923 | |
| 924 | |
| 925 | |
| 926 | #[test] |
| 927 | fn rqt_decodes_bit_exactly() { |
| 928 | if !have_ffmpeg() { |
| 929 | eprintln!("skipping: ffmpeg not installed"); |
| 930 | return; |
| 931 | } |
| 932 | for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { |
| 933 | let (source, coded) = encode_rqt(w, h, 27, true); |
| 934 | let (_, plain) = encode_rqt(w, h, 27, false); |
| 935 | let name = format!("rqt-{w}x{h}"); |
| 936 | assert_ne!( |
| 937 | coded.au, plain.au, |
| 938 | "{name}: RQT changed no byte, so the split path is not running" |
| 939 | ); |
| 940 | let path = write_au(&name, &coded); |
| 941 | let decoded = match ffmpeg_decode(&path) { |
| 942 | Ok(bytes) => bytes, |
| 943 | Err(e) => panic!("{name}: ffmpeg failed: {e}"), |
| 944 | }; |
| 945 | let recon = planes_of(coded.recon.as_ref().expect("recon kept")); |
| 946 | assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); |
| 947 | let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); |
| 948 | if mismatches != 0 { |
| 949 | |
| 950 | |
| 951 | let luma = (w * h) as usize; |
| 952 | let chroma = luma / 4; |
| 953 | let first = decoded |
| 954 | .iter() |
| 955 | .zip(&recon) |
| 956 | .position(|(a, b)| a != b) |
| 957 | .unwrap(); |
| 958 | let count = |range: std::ops::Range<usize>| { |
| 959 | decoded[range.clone()] |
| 960 | .iter() |
| 961 | .zip(&recon[range]) |
| 962 | .filter(|(a, b)| a != b) |
| 963 | .count() |
| 964 | }; |
| 965 | let mut map = String::new(); |
| 966 | for by in (0..h as usize).step_by(16) { |
| 967 | for bx in (0..w as usize).step_by(16) { |
| 968 | let mut c = 0; |
| 969 | for row in by..by + 16 { |
| 970 | for col in bx..bx + 16 { |
| 971 | let i = row * w as usize + col; |
| 972 | if decoded[i] != recon[i] { |
| 973 | c += 1; |
| 974 | } |
| 975 | } |
| 976 | } |
| 977 | map.push_str(&format!("{c:4}")); |
| 978 | } |
| 979 | map.push('\n'); |
| 980 | } |
| 981 | eprintln!("luma 16x16 mismatch map:\n{map}"); |
| 982 | panic!( |
| 983 | "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ |
| 984 | ({}, {})", |
| 985 | count(0..luma), |
| 986 | count(luma..luma + chroma), |
| 987 | count(luma + chroma..luma + 2 * chroma), |
| 988 | first % w as usize, |
| 989 | first / w as usize, |
| 990 | ); |
| 991 | } |
| 992 | let quality = psnr(&planes_of(&source), &recon); |
| 993 | assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | |
| 998 | |
| 999 | fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { |
| 1000 | let mut cfg = EncoderConfig::new(width, height); |
| 1001 | cfg.rqt = rqt; |
| 1002 | cfg.rate_control = RateControl::ConstantQp(qp); |
| 1003 | cfg.keep_recon = true; |
| 1004 | cfg.picture_hash = true; |
| 1005 | let encoder = Encoder::new(cfg).expect("encoder"); |
| 1006 | let frame = natural_frame(width, height, 0); |
| 1007 | let coded = encoder.encode_idr(&frame).expect("encode"); |
| 1008 | (frame, coded) |
| 1009 | } |