| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use ec_h264::{Decoder, Encoder, EncoderConfig, NalOutcome, OutputOrder, PictureView, Preset}; |
| 11 | |
| 12 | |
| 13 | type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); |
| 14 | |
| 15 | |
| 16 | |
| 17 | struct Clip { |
| 18 | w: usize, |
| 19 | h: usize, |
| 20 | y: Vec<u8>, |
| 21 | u: Vec<u8>, |
| 22 | v: Vec<u8>, |
| 23 | } |
| 24 | |
| 25 | impl Clip { |
| 26 | fn new(w: usize, h: usize) -> Clip { |
| 27 | Clip { |
| 28 | w, |
| 29 | h, |
| 30 | y: vec![0; w * h], |
| 31 | u: vec![0; w / 2 * h / 2], |
| 32 | v: vec![0; w / 2 * h / 2], |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | |
| 37 | |
| 38 | fn render(&mut self, t: usize) { |
| 39 | let (w, h) = (self.w, self.h); |
| 40 | for y in 0..h { |
| 41 | for x in 0..w { |
| 42 | let grad = ((x + y * 2 + t * 3) % 256) as u8; |
| 43 | let noise = ((x * 37 + y * 17 + t * 11) % 23) as u8; |
| 44 | let box_x = (t * 5) % (w.saturating_sub(40).max(1)); |
| 45 | let inside = x >= box_x && x < box_x + 40 && y >= h / 4 && y < h / 4 + 30; |
| 46 | self.y[y * w + x] = if inside { |
| 47 | 200u8.saturating_sub(noise) |
| 48 | } else { |
| 49 | grad / 2 + noise |
| 50 | }; |
| 51 | } |
| 52 | } |
| 53 | for y in 0..h / 2 { |
| 54 | for x in 0..w / 2 { |
| 55 | self.u[y * (w / 2) + x] = (100 + ((x + t) % 40)) as u8; |
| 56 | self.v[y * (w / 2) + x] = (140 + ((y + t * 2) % 30)) as u8; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | fn render_smooth(&mut self, t: usize) { |
| 68 | let (w, h) = (self.w, self.h); |
| 69 | let ft = t as f64; |
| 70 | for y in 0..h { |
| 71 | for x in 0..w { |
| 72 | let (fx, fy) = (x as f64, y as f64); |
| 73 | |
| 74 | |
| 75 | let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; |
| 76 | |
| 77 | let texture = if y > h / 3 && y < 2 * h / 3 { |
| 78 | 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) |
| 79 | } else { |
| 80 | 0.0 |
| 81 | }; |
| 82 | let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); |
| 83 | let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; |
| 84 | let v = if inside { |
| 85 | 196.0 - texture * 0.5 |
| 86 | } else { |
| 87 | 40.0 + (ramp % 90.0).abs() + texture |
| 88 | }; |
| 89 | self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; |
| 90 | } |
| 91 | } |
| 92 | for y in 0..h / 2 { |
| 93 | for x in 0..w / 2 { |
| 94 | let (fx, fy) = (x as f64, y as f64); |
| 95 | self.u[y * (w / 2) + x] = |
| 96 | (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; |
| 97 | self.v[y * (w / 2) + x] = |
| 98 | (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | fn view(&self) -> PictureView<'_> { |
| 104 | PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | |
| 109 | |
| 110 | fn decode_all(stream: &[u8]) -> Vec<Planes> { |
| 111 | let mut dec = Decoder::new(); |
| 112 | dec.set_output_order(OutputOrder::Decode); |
| 113 | let mut out = Vec::new(); |
| 114 | for nal in ec_h264_syntax::AnnexBIter::new(stream) { |
| 115 | if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { |
| 116 | dec.end_picture().expect("end of picture"); |
| 117 | dec.push_nal(nal).expect("decoder accepts the NAL"); |
| 118 | } |
| 119 | while let Some(frame) = dec.next_frame() { |
| 120 | out.push(planes_of(&frame)); |
| 121 | } |
| 122 | } |
| 123 | dec.flush().expect("flush"); |
| 124 | while let Some(frame) = dec.next_frame() { |
| 125 | out.push(planes_of(&frame)); |
| 126 | } |
| 127 | out |
| 128 | } |
| 129 | |
| 130 | fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { |
| 131 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 132 | let mut planes = Vec::new(); |
| 133 | for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] |
| 134 | .into_iter() |
| 135 | .enumerate() |
| 136 | { |
| 137 | let plane = &frame.planes[i]; |
| 138 | let mut out = Vec::with_capacity(pw * ph); |
| 139 | for row in 0..ph { |
| 140 | out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); |
| 141 | } |
| 142 | planes.push(out); |
| 143 | } |
| 144 | let v = planes.pop().unwrap(); |
| 145 | let u = planes.pop().unwrap(); |
| 146 | let y = planes.pop().unwrap(); |
| 147 | (y, u, v) |
| 148 | } |
| 149 | |
| 150 | |
| 151 | fn plane_mse(a: &[u8], b: &[u8]) -> f64 { |
| 152 | a.iter() |
| 153 | .zip(b) |
| 154 | .map(|(&x, &y)| { |
| 155 | let d = f64::from(x) - f64::from(y); |
| 156 | d * d |
| 157 | }) |
| 158 | .sum::<f64>() |
| 159 | / a.len() as f64 |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | fn psnr_yuv(a: &(Vec<u8>, Vec<u8>, Vec<u8>), b: &(Vec<u8>, Vec<u8>, Vec<u8>)) -> f64 { |
| 168 | let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); |
| 169 | let sse = |
| 170 | plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; |
| 171 | let mse = sse / (n_y + 2.0 * n_c); |
| 172 | if mse == 0.0 { |
| 173 | 99.0 |
| 174 | } else { |
| 175 | 10.0 * (255.0 * 255.0 / mse).log10() |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 180 | let mse: f64 = a |
| 181 | .iter() |
| 182 | .zip(b) |
| 183 | .map(|(&x, &y)| { |
| 184 | let d = f64::from(x) - f64::from(y); |
| 185 | d * d |
| 186 | }) |
| 187 | .sum::<f64>() |
| 188 | / a.len() as f64; |
| 189 | if mse == 0.0 { |
| 190 | 99.0 |
| 191 | } else { |
| 192 | 10.0 * (255.0 * 255.0 / mse).log10() |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { |
| 197 | let mut a = [[0.0; 5]; 4]; |
| 198 | for i in 0..4 { |
| 199 | a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; |
| 200 | } |
| 201 | for col in 0..4 { |
| 202 | let mut pivot = col; |
| 203 | for row in col + 1..4 { |
| 204 | if a[row][col].abs() > a[pivot][col].abs() { |
| 205 | pivot = row; |
| 206 | } |
| 207 | } |
| 208 | a.swap(col, pivot); |
| 209 | let div = a[col][col]; |
| 210 | assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); |
| 211 | for v in a[col][col..].iter_mut() { |
| 212 | *v /= div; |
| 213 | } |
| 214 | for row in 0..4 { |
| 215 | if row == col { |
| 216 | continue; |
| 217 | } |
| 218 | let f = a[row][col]; |
| 219 | let pivot_row = a[col]; |
| 220 | for (dst, src) in a[row][col..].iter_mut().zip(&pivot_row[col..]) { |
| 221 | *dst -= f * src; |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | [a[0][4], a[1][4], a[2][4], a[3][4]] |
| 226 | } |
| 227 | |
| 228 | fn cubic_integral(c: [f64; 4], x: f64) -> f64 { |
| 229 | c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 |
| 230 | } |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | fn refuse_flat_window(psnrs: impl IntoIterator<Item = f64>, skip_var: &str) { |
| 237 | const FLAT_WINDOW_DB: f64 = 90.0; |
| 238 | let ps: Vec<f64> = psnrs.into_iter().collect(); |
| 239 | assert!( |
| 240 | ps.iter().any(|&p| p < FLAT_WINDOW_DB), |
| 241 | "the sample window is flat — every point reaches the PSNR cap ({ps:?}); \ |
| 242 | this is a black head or a fade, not content: pass {skip_var} to sample \ |
| 243 | past it" |
| 244 | ); |
| 245 | } |
| 246 | |
| 247 | fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { |
| 248 | let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); |
| 249 | let ys_candidate = std::array::from_fn(|i| candidate[i].1); |
| 250 | let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); |
| 251 | let ys_anchor = std::array::from_fn(|i| anchor[i].1); |
| 252 | let lo = xs_candidate |
| 253 | .iter() |
| 254 | .copied() |
| 255 | .fold(f64::INFINITY, f64::min) |
| 256 | .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); |
| 257 | let hi = xs_candidate |
| 258 | .iter() |
| 259 | .copied() |
| 260 | .fold(f64::NEG_INFINITY, f64::max) |
| 261 | .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); |
| 262 | assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); |
| 263 | let c_candidate = cubic_fit(xs_candidate, ys_candidate); |
| 264 | let c_anchor = cubic_fit(xs_anchor, ys_anchor); |
| 265 | (cubic_integral(c_candidate, hi) |
| 266 | - cubic_integral(c_candidate, lo) |
| 267 | - cubic_integral(c_anchor, hi) |
| 268 | + cubic_integral(c_anchor, lo)) |
| 269 | / (hi - lo) |
| 270 | } |
| 271 | |
| 272 | |
| 273 | |
| 274 | #[test] |
| 275 | fn reconstruction_matches_the_decoder() { |
| 276 | let mut t8x8_mbs = (0, 0); |
| 277 | for (w, h) in [(176, 144), (208, 122), (64, 48)] { |
| 278 | let mut clip = Clip::new(w, h); |
| 279 | for qp in [12, 24, 33, 44] { |
| 280 | for (threads, preset, cabac, t8x8) in [ |
| 281 | (1usize, Preset::Fast, true, false), |
| 282 | (4, Preset::Balanced, true, false), |
| 283 | (1, Preset::Fast, false, false), |
| 284 | (3, Preset::Balanced, false, false), |
| 285 | (2, Preset::Balanced, true, true), |
| 286 | (2, Preset::Balanced, false, true), |
| 287 | ] { |
| 288 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 289 | cfg.qp = qp; |
| 290 | cfg.gop_size = 5; |
| 291 | cfg.threads = threads; |
| 292 | cfg.preset = preset; |
| 293 | cfg.cabac = cabac; |
| 294 | cfg.transform_8x8 = t8x8; |
| 295 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 296 | let mut stream = Vec::new(); |
| 297 | let mut recons = Vec::new(); |
| 298 | for t in 0..8 { |
| 299 | clip.render(t); |
| 300 | let picture = enc.encode(&clip.view()).expect("encode"); |
| 301 | stream.extend_from_slice(&picture.au); |
| 302 | recons.push(enc.reconstruction().expect("a reconstruction")); |
| 303 | } |
| 304 | if t8x8 { |
| 305 | let (intra, inter) = enc.transform_8x8_mbs(); |
| 306 | t8x8_mbs.0 += intra; |
| 307 | t8x8_mbs.1 += inter; |
| 308 | } |
| 309 | let decoded = decode_all(&stream); |
| 310 | assert_eq!( |
| 311 | decoded.len(), |
| 312 | recons.len(), |
| 313 | "{w}x{h} qp {qp}: picture count" |
| 314 | ); |
| 315 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 316 | assert_eq!( |
| 317 | dec.0, rec.0, |
| 318 | "{w}x{h} qp {qp} t{threads}: luma of picture {i}" |
| 319 | ); |
| 320 | assert_eq!( |
| 321 | dec.1, rec.1, |
| 322 | "{w}x{h} qp {qp} t{threads}: Cb of picture {i}" |
| 323 | ); |
| 324 | assert_eq!( |
| 325 | dec.2, rec.2, |
| 326 | "{w}x{h} qp {qp} t{threads}: Cr of picture {i}" |
| 327 | ); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | assert!( |
| 334 | t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, |
| 335 | "8x8 MBs across the sweep: intra {} inter {}", |
| 336 | t8x8_mbs.0, |
| 337 | t8x8_mbs.1 |
| 338 | ); |
| 339 | } |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | #[test] |
| 345 | fn quality_follows_the_quantiser() { |
| 346 | let (w, h) = (176, 144); |
| 347 | let mut clip = Clip::new(w, h); |
| 348 | let mut last = 0.0; |
| 349 | for qp in [40, 30, 20, 10] { |
| 350 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 351 | cfg.qp = qp; |
| 352 | cfg.gop_size = 4; |
| 353 | cfg.threads = 1; |
| 354 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 355 | let mut total = 0.0; |
| 356 | for t in 0..6 { |
| 357 | clip.render(t); |
| 358 | enc.encode(&clip.view()).expect("encode"); |
| 359 | let (y, _, _) = enc.reconstruction().unwrap(); |
| 360 | total += psnr(&clip.y, &y); |
| 361 | } |
| 362 | let avg = total / 6.0; |
| 363 | assert!( |
| 364 | avg > last, |
| 365 | "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}" |
| 366 | ); |
| 367 | if qp == 10 { |
| 368 | assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}"); |
| 369 | } |
| 370 | last = avg; |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | |
| 375 | |
| 376 | #[test] |
| 377 | fn rate_control_hits_its_target() { |
| 378 | let (w, h) = (352, 288); |
| 379 | let mut clip = Clip::new(w, h); |
| 380 | let bitrate = 1_500_000u32; |
| 381 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 382 | cfg.bitrate = bitrate; |
| 383 | cfg.framerate = 25.0; |
| 384 | cfg.gop_size = 25; |
| 385 | cfg.threads = 2; |
| 386 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 387 | let mut bits = 0u64; |
| 388 | let frames = 50; |
| 389 | let mut keys = 0; |
| 390 | for t in 0..frames { |
| 391 | clip.render(t); |
| 392 | let p = enc.encode(&clip.view()).expect("encode"); |
| 393 | bits += p.au.len() as u64 * 8; |
| 394 | keys += u32::from(p.key_frame); |
| 395 | } |
| 396 | assert_eq!(keys, 2, "one IDR per GOP"); |
| 397 | let actual = bits as f64 / (frames as f64 / 25.0); |
| 398 | let ratio = actual / f64::from(bitrate); |
| 399 | assert!( |
| 400 | (0.7..1.35).contains(&ratio), |
| 401 | "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})" |
| 402 | ); |
| 403 | } |
| 404 | |
| 405 | |
| 406 | |
| 407 | #[test] |
| 408 | fn all_intra_when_the_gop_is_one() { |
| 409 | let (w, h) = (64, 64); |
| 410 | let mut clip = Clip::new(w, h); |
| 411 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 412 | cfg.gop_size = 1; |
| 413 | cfg.qp = 26; |
| 414 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 415 | let mut stream = Vec::new(); |
| 416 | for t in 0..4 { |
| 417 | clip.render(t); |
| 418 | let p = enc.encode(&clip.view()).expect("encode"); |
| 419 | assert!(p.key_frame, "picture {t} is not a key frame"); |
| 420 | stream.extend_from_slice(&p.au); |
| 421 | } |
| 422 | assert_eq!(decode_all(&stream).len(), 4); |
| 423 | } |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | fn pin_loud(site: &str, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { |
| 451 | let expected = bytes.len(); |
| 452 | if let Err(e) = std::fs::write(path, bytes) { |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | let on_disk = std::fs::metadata(path) |
| 458 | .map(|m| m.len() as usize) |
| 459 | .unwrap_or(0); |
| 460 | return Err(short_line( |
| 461 | site, |
| 462 | path, |
| 463 | on_disk, |
| 464 | expected, |
| 465 | &format!("the write failed: {e}"), |
| 466 | )); |
| 467 | } |
| 468 | match std::fs::metadata(path) { |
| 469 | Ok(m) if m.len() as usize == expected => Ok(()), |
| 470 | Ok(m) => Err(short_line( |
| 471 | site, |
| 472 | path, |
| 473 | m.len() as usize, |
| 474 | expected, |
| 475 | "the write reported success and the file on disk is still not that long (no OS error)", |
| 476 | )), |
| 477 | Err(e) => Err(short_line( |
| 478 | site, |
| 479 | path, |
| 480 | 0, |
| 481 | expected, |
| 482 | &format!("the written file could not be stat'ed: {e}"), |
| 483 | )), |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | |
| 488 | |
| 489 | fn short_line( |
| 490 | site: &str, |
| 491 | path: &std::path::Path, |
| 492 | on_disk: usize, |
| 493 | expected: usize, |
| 494 | why: &str, |
| 495 | ) -> String { |
| 496 | format!( |
| 497 | "ec-h264 encode pin SHORT [{}] {}: file holds {on_disk} of {expected} bytes: {why}", |
| 498 | site, |
| 499 | path.display() |
| 500 | ) |
| 501 | } |
| 502 | |
| 503 | |
| 504 | |
| 505 | |
| 506 | fn pin_or_bail(site: &str, path: &std::path::Path, bytes: &[u8]) -> Option<()> { |
| 507 | pin_loud(site, path, bytes) |
| 508 | .map_err(|why| eprintln!("{why}")) |
| 509 | .ok() |
| 510 | } |
| 511 | |
| 512 | #[cfg(unix)] |
| 513 | #[test] |
| 514 | fn pin_loud_reds_on_an_ok_but_short_write() { |
| 515 | |
| 516 | |
| 517 | |
| 518 | |
| 519 | let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-{}", std::process::id())); |
| 520 | std::fs::create_dir_all(&dir).expect("scratch dir"); |
| 521 | let path = dir.join("ok-but-short.264"); |
| 522 | let _ = std::fs::remove_file(&path); |
| 523 | std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); |
| 524 | let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); |
| 525 | assert!(why.contains(&path.display().to_string()), "{why}"); |
| 526 | assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); |
| 527 | std::fs::remove_file(&path).ok(); |
| 528 | |
| 529 | |
| 530 | let good = dir.join("whole.264"); |
| 531 | let bytes = vec![7u8; 1234]; |
| 532 | pin_loud("control", &good, &bytes).expect("a whole write is not short"); |
| 533 | assert_eq!(std::fs::read(&good).expect("read back"), bytes); |
| 534 | std::fs::remove_file(&good).ok(); |
| 535 | std::fs::remove_dir_all(&dir).ok(); |
| 536 | } |
| 537 | |
| 538 | #[cfg(unix)] |
| 539 | #[test] |
| 540 | fn pin_loud_reports_what_landed_under_a_size_cap() { |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | use std::process::Command; |
| 546 | let Ok(exe) = std::env::current_exe() else { |
| 547 | return; |
| 548 | }; |
| 549 | |
| 550 | |
| 551 | let script = format!( |
| 552 | "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", |
| 553 | exe.display() |
| 554 | ); |
| 555 | let out = Command::new("sh") |
| 556 | .args(["-c", &script]) |
| 557 | .env("EC_PINLOUD_CHILD", "1") |
| 558 | .output() |
| 559 | .expect("run the capped child"); |
| 560 | let text = format!( |
| 561 | "{}{}", |
| 562 | String::from_utf8_lossy(&out.stdout), |
| 563 | String::from_utf8_lossy(&out.stderr) |
| 564 | ); |
| 565 | assert!(!out.status.success(), "the capped write must fail: {text}"); |
| 566 | assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); |
| 567 | assert!( |
| 568 | text.contains("EFBIG") || text.contains("File too large"), |
| 569 | "{text}" |
| 570 | ); |
| 571 | } |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | #[test] |
| 577 | fn pin_loud_cap_child() { |
| 578 | if std::env::var_os("EC_PINLOUD_CHILD").is_none() { |
| 579 | return; |
| 580 | } |
| 581 | let dir = std::env::temp_dir().join(format!("ec-h264-pinloud-cap-{}", std::process::id())); |
| 582 | std::fs::create_dir_all(&dir).expect("scratch dir"); |
| 583 | let path = dir.join("capped.264"); |
| 584 | let why = |
| 585 | pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); |
| 586 | std::fs::remove_file(&path).ok(); |
| 587 | std::fs::remove_dir_all(&dir).ok(); |
| 588 | panic!("{why}"); |
| 589 | } |
| 590 | |
| 591 | |
| 592 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { |
| 593 | |
| 594 | |
| 595 | |
| 596 | static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 597 | let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id())); |
| 598 | std::fs::create_dir_all(&dir).ok()?; |
| 599 | let path = dir.join(format!( |
| 600 | "s{}-{}.264", |
| 601 | stream.len(), |
| 602 | SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 603 | )); |
| 604 | pin_or_bail("ffmpeg_decode", &path, stream)?; |
| 605 | let mut cmd = ec_testkit::ffmpeg(); |
| 606 | cmd.args(["-v", "error"]); |
| 607 | cmd.args(extra); |
| 608 | cmd.arg("-i").arg(&path); |
| 609 | cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]); |
| 610 | let out = cmd.output().ok()?; |
| 611 | let _ = std::fs::remove_file(&path); |
| 612 | if !out.status.success() { |
| 613 | eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); |
| 614 | return None; |
| 615 | } |
| 616 | let frame = w * h * 3 / 2; |
| 617 | if frame == 0 || out.stdout.len() % frame != 0 { |
| 618 | eprintln!( |
| 619 | "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", |
| 620 | out.stdout.len() |
| 621 | ); |
| 622 | return None; |
| 623 | } |
| 624 | Some( |
| 625 | out.stdout |
| 626 | .chunks(frame) |
| 627 | .map(|f| { |
| 628 | let (y, rest) = f.split_at(w * h); |
| 629 | let (u, v) = rest.split_at(w / 2 * h / 2); |
| 630 | (y.to_vec(), u.to_vec(), v.to_vec()) |
| 631 | }) |
| 632 | .collect(), |
| 633 | ) |
| 634 | } |
| 635 | |
| 636 | |
| 637 | fn encode_clip( |
| 638 | w: usize, |
| 639 | h: usize, |
| 640 | frames: usize, |
| 641 | configure: impl FnOnce(&mut EncoderConfig), |
| 642 | ) -> (Vec<u8>, Vec<Planes>, (u64, u64)) { |
| 643 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 644 | cfg.gop_size = 10; |
| 645 | cfg.threads = 3; |
| 646 | configure(&mut cfg); |
| 647 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 648 | let mut clip = Clip::new(w, h); |
| 649 | let mut stream = Vec::new(); |
| 650 | let mut recons = Vec::new(); |
| 651 | for t in 0..frames { |
| 652 | clip.render(t); |
| 653 | stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); |
| 654 | recons.push(enc.reconstruction().expect("reconstruction")); |
| 655 | } |
| 656 | (stream, recons, enc.transform_8x8_mbs()) |
| 657 | } |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | #[test] |
| 663 | fn eight_by_eight_gains_on_flat_and_text() { |
| 664 | let (w, h) = (320, 240); |
| 665 | let render = |t: usize, clip: &mut Clip| { |
| 666 | |
| 667 | let sx = |x: usize| x * 2 + t; |
| 668 | for y in 0..h { |
| 669 | for x in 0..w { |
| 670 | let (px, py) = (sx(x) as f64 / 2.0, y as f64); |
| 671 | |
| 672 | |
| 673 | let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; |
| 674 | |
| 675 | |
| 676 | |
| 677 | let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; |
| 678 | let shade = shade + tri(px) * tri(py) / 1.5; |
| 679 | |
| 680 | let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24); |
| 681 | let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7; |
| 682 | let stem = (2..5).contains(&cx); |
| 683 | let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; |
| 684 | let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; |
| 685 | let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); |
| 686 | clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; |
| 687 | } |
| 688 | } |
| 689 | clip.u.fill(128); |
| 690 | clip.v.fill(128); |
| 691 | }; |
| 692 | let run = |t8x8: bool, qp: i32, cabac: bool| { |
| 693 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 694 | cfg.qp = qp; |
| 695 | cfg.gop_size = 10; |
| 696 | cfg.transform_8x8 = t8x8; |
| 697 | cfg.cabac = cabac; |
| 698 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 699 | let mut clip = Clip::new(w, h); |
| 700 | let (mut bits, mut sum_psnr) = (0usize, 0.0); |
| 701 | let mut share = 0.0; |
| 702 | for t in 0..10 { |
| 703 | render(t, &mut clip); |
| 704 | bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; |
| 705 | let rec = enc.reconstruction().expect("reconstruction"); |
| 706 | sum_psnr += psnr(&clip.y, &rec.0); |
| 707 | } |
| 708 | if t8x8 { |
| 709 | let (i, p) = enc.transform_8x8_mbs(); |
| 710 | eprintln!("8x8 MBs: intra {i} inter {p}"); |
| 711 | share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); |
| 712 | } |
| 713 | (bits as f64, sum_psnr / 10.0, share) |
| 714 | }; |
| 715 | let qps = [22, 26, 30, 34]; |
| 716 | let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); |
| 717 | let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); |
| 718 | refuse_flat_window(off.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); |
| 719 | let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 720 | let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 721 | let bd = bd_psnr_delta(&on_curve, &off_curve); |
| 722 | let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64; |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230; |
| 731 | eprintln!( |
| 732 | "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", |
| 733 | share * 100.0 |
| 734 | ); |
| 735 | assert!(share > 0.0, "no 8x8 macroblocks were coded"); |
| 736 | assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); |
| 737 | assert!( |
| 738 | bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, |
| 739 | "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" |
| 740 | ); |
| 741 | } |
| 742 | |
| 743 | |
| 744 | |
| 745 | #[test] |
| 746 | fn ffmpeg_decodes_bit_exactly() { |
| 747 | let mut t8x8_mbs = (0, 0); |
| 748 | for (w, h) in [(176, 144), (322, 242)] { |
| 749 | for qp in [10, 20, 28, 37, 47] { |
| 750 | let cavlc = qp % 2 == 0; |
| 751 | let t8x8 = qp % 3 == 1; |
| 752 | let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { |
| 753 | cfg.qp = qp; |
| 754 | cfg.cabac = !cavlc; |
| 755 | cfg.transform_8x8 = t8x8; |
| 756 | }); |
| 757 | t8x8_mbs.0 += intra; |
| 758 | t8x8_mbs.1 += inter; |
| 759 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 760 | assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count"); |
| 761 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 762 | assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}"); |
| 763 | assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}"); |
| 764 | assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}"); |
| 765 | } |
| 766 | } |
| 767 | } |
| 768 | assert!( |
| 769 | t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, |
| 770 | "8x8 MBs across the sweep: intra {} inter {}", |
| 771 | t8x8_mbs.0, |
| 772 | t8x8_mbs.1 |
| 773 | ); |
| 774 | } |
| 775 | |
| 776 | |
| 777 | #[test] |
| 778 | fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { |
| 779 | let (w, h) = (352, 288); |
| 780 | let (stream, recons, _) = encode_clip(w, h, 12, |cfg| { |
| 781 | cfg.bitrate = 2_000_000; |
| 782 | cfg.framerate = 25.0; |
| 783 | }); |
| 784 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 785 | assert_eq!(decoded.len(), recons.len()); |
| 786 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 787 | assert_eq!(dec.0, rec.0, "luma of frame {i}"); |
| 788 | assert_eq!( |
| 789 | (dec.1.clone(), dec.2.clone()), |
| 790 | (rec.1.clone(), rec.2.clone()), |
| 791 | "chroma of frame {i}" |
| 792 | ); |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | #[test] |
| 800 | fn vaapi_decodes_our_stream() { |
| 801 | if !std::path::Path::new("/dev/dri/renderD128").exists() { |
| 802 | eprintln!("SKIP vaapi_decodes_our_stream: no render node"); |
| 803 | return; |
| 804 | } |
| 805 | let (w, h) = (352, 288); |
| 806 | let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { |
| 807 | cfg.qp = 26; |
| 808 | cfg.transform_8x8 = true; |
| 809 | }); |
| 810 | assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream"); |
| 811 | let Some(decoded) = ffmpeg_decode( |
| 812 | &stream, |
| 813 | w, |
| 814 | h, |
| 815 | &[ |
| 816 | "-hwaccel", |
| 817 | "vaapi", |
| 818 | "-hwaccel_device", |
| 819 | "/dev/dri/renderD128", |
| 820 | ], |
| 821 | ) else { |
| 822 | eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here"); |
| 823 | return; |
| 824 | }; |
| 825 | assert_eq!(decoded.len(), recons.len(), "VA-API frame count"); |
| 826 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 827 | let p = psnr(&dec.0, &rec.0); |
| 828 | assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB"); |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | |
| 837 | |
| 838 | |
| 839 | |
| 840 | #[test] |
| 841 | fn real_library_frames_encode_and_decode_exactly() { |
| 842 | use ec_core::registry::Decoder as _; |
| 843 | |
| 844 | let path = ec_testkit::fixture("open/sintel_trailer-720p.mp4"); |
| 845 | let (w, h) = (1280, 720); |
| 846 | |
| 847 | let (params, mut demux, index) = open_h264_source(path.as_os_str()); |
| 848 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); |
| 849 | let mut sources: Vec<Planes> = Vec::new(); |
| 850 | while sources.len() < 12 { |
| 851 | let Ok(packet) = demux.next_packet() else { |
| 852 | break; |
| 853 | }; |
| 854 | if packet.stream != index { |
| 855 | continue; |
| 856 | } |
| 857 | dec.send_packet(&packet).expect("decode"); |
| 858 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 859 | if sources.len() < 12 { |
| 860 | sources.push(planes_of(&f)); |
| 861 | } |
| 862 | } |
| 863 | } |
| 864 | assert!( |
| 865 | sources.len() >= 6, |
| 866 | "only {} pictures decoded from the library file", |
| 867 | sources.len() |
| 868 | ); |
| 869 | |
| 870 | let bitrate = 8_000_000u32; |
| 871 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 872 | cfg.bitrate = bitrate; |
| 873 | cfg.framerate = 25.0; |
| 874 | cfg.gop_size = 25; |
| 875 | cfg.threads = 0; |
| 876 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 877 | let mut stream = Vec::new(); |
| 878 | let mut recons = Vec::new(); |
| 879 | let mut bits = 0u64; |
| 880 | for (y, u, v) in &sources { |
| 881 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 882 | let p = enc.encode(&view).expect("encode"); |
| 883 | bits += p.au.len() as u64 * 8; |
| 884 | stream.extend_from_slice(&p.au); |
| 885 | recons.push(enc.reconstruction().expect("reconstruction")); |
| 886 | } |
| 887 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 888 | assert_eq!(decoded.len(), recons.len(), "picture count"); |
| 889 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 890 | assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip"); |
| 891 | assert_eq!(dec.1, rec.1, "Cb of picture {i}"); |
| 892 | assert_eq!(dec.2, rec.2, "Cr of picture {i}"); |
| 893 | } |
| 894 | let quality: f64 = sources |
| 895 | .iter() |
| 896 | .zip(&recons) |
| 897 | .map(|((y, ..), (ry, ..))| psnr(y, ry)) |
| 898 | .sum::<f64>() |
| 899 | / sources.len() as f64; |
| 900 | let rate = bits as f64 / (sources.len() as f64 / 25.0); |
| 901 | eprintln!( |
| 902 | "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB", |
| 903 | sources.len(), |
| 904 | rate / 1000.0, |
| 905 | f64::from(bitrate) / 1000.0 |
| 906 | ); |
| 907 | assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); |
| 908 | } |
| 909 | |
| 910 | |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | fn open_h264_source( |
| 918 | path: &std::ffi::OsStr, |
| 919 | ) -> ( |
| 920 | ec_core::registry::CodecParameters, |
| 921 | Box<dyn ec_core::registry::Demuxer>, |
| 922 | u32, |
| 923 | ) { |
| 924 | use std::io::{Read, Seek, SeekFrom}; |
| 925 | |
| 926 | let file = std::fs::File::open(path).expect("source opens"); |
| 927 | let mut reader = std::io::BufReader::new(file); |
| 928 | |
| 929 | |
| 930 | |
| 931 | |
| 932 | let mut head = [0u8; 12]; |
| 933 | let n = reader.read(&mut head).expect("read container head"); |
| 934 | reader.seek(SeekFrom::Start(0)).expect("rewind"); |
| 935 | |
| 936 | let demux: Box<dyn ec_core::registry::Demuxer> = if ec_matroska::is_matroska(&head[..n]) { |
| 937 | Box::new(ec_matroska::MatroskaDemuxer::new(reader).expect("ec-matroska opens the file")) |
| 938 | } else if n >= 8 && &head[4..8] == b"ftyp" { |
| 939 | Box::new(ec_mp4::Mp4Demuxer::new(reader).expect("ec-mp4 opens the file")) |
| 940 | } else { |
| 941 | panic!( |
| 942 | "{}: not an MP4 or Matroska container", |
| 943 | path.to_string_lossy() |
| 944 | ) |
| 945 | }; |
| 946 | |
| 947 | let streams = demux.streams(); |
| 948 | if let Some((params, index)) = streams |
| 949 | .iter() |
| 950 | .find(|s| s.params.codec == ec_core::registry::CodecId::H264) |
| 951 | .map(|s| (s.params.clone(), s.index)) |
| 952 | { |
| 953 | return (params, demux, index); |
| 954 | } |
| 955 | |
| 956 | |
| 957 | if let Some(codec) = streams |
| 958 | .iter() |
| 959 | .find(|s| matches!(s.params.media, ec_core::registry::MediaParameters::Video(_))) |
| 960 | .map(|s| s.params.codec) |
| 961 | { |
| 962 | panic!( |
| 963 | "{}: video track is {:?}, not H.264 — this gate measures H.264 only", |
| 964 | path.to_string_lossy(), |
| 965 | codec |
| 966 | ); |
| 967 | } |
| 968 | panic!("{}: no video track found", path.to_string_lossy()); |
| 969 | } |
| 970 | |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { |
| 976 | use ec_core::registry::Decoder as _; |
| 977 | |
| 978 | let (params, mut demux, index) = open_h264_source(path); |
| 979 | let video = match ¶ms.media { |
| 980 | ec_core::registry::MediaParameters::Video(v) => v, |
| 981 | _ => panic!("the H.264 track carries no video parameters"), |
| 982 | }; |
| 983 | let (w, h) = (video.width as usize, video.height as usize); |
| 984 | |
| 985 | |
| 986 | |
| 987 | |
| 988 | |
| 989 | |
| 990 | let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { |
| 991 | Ok("fps") => video |
| 992 | .frame_rate |
| 993 | .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), |
| 994 | Ok(n) => n.parse().unwrap_or(1usize).max(1), |
| 995 | Err(_) => 1, |
| 996 | }; |
| 997 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); |
| 998 | |
| 999 | |
| 1000 | let skip: usize = std::env::var("EC_H264_CLIP_SKIP") |
| 1001 | .ok() |
| 1002 | .and_then(|v| v.parse().ok()) |
| 1003 | .unwrap_or(0); |
| 1004 | let mut sources: Vec<Planes> = Vec::new(); |
| 1005 | let mut seen = 0usize; |
| 1006 | while sources.len() < want { |
| 1007 | let Ok(packet) = demux.next_packet() else { |
| 1008 | break; |
| 1009 | }; |
| 1010 | if packet.stream != index { |
| 1011 | continue; |
| 1012 | } |
| 1013 | dec.send_packet(&packet).expect("decode"); |
| 1014 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 1015 | if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { |
| 1016 | sources.push(planes_of(&f)); |
| 1017 | } |
| 1018 | seen += 1; |
| 1019 | } |
| 1020 | } |
| 1021 | assert!( |
| 1022 | sources.len() >= 10, |
| 1023 | "only {} pictures decoded from {}", |
| 1024 | sources.len(), |
| 1025 | path.to_string_lossy() |
| 1026 | ); |
| 1027 | eprintln!( |
| 1028 | "{}: {}x{}, {} pictures, every {stride}th of {seen}", |
| 1029 | path.to_string_lossy(), |
| 1030 | w, |
| 1031 | h, |
| 1032 | sources.len() |
| 1033 | ); |
| 1034 | (w, h, sources) |
| 1035 | } |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | |
| 1044 | |
| 1045 | #[test] |
| 1046 | #[ignore = "slow measurement on the open 480p trailer"] |
| 1047 | fn real_clip_t8x8_bd_psnr() { |
| 1048 | let path = ec_testkit::fixture("open/sintel_trailer-480p.mp4"); |
| 1049 | let (w, h, sources) = clip_sources(path.as_os_str(), 30); |
| 1050 | |
| 1051 | let run = |t8x8: bool, qp: i32| { |
| 1052 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1053 | cfg.qp = qp; |
| 1054 | cfg.gop_size = 10; |
| 1055 | cfg.cabac = true; |
| 1056 | cfg.transform_8x8 = t8x8; |
| 1057 | cfg.framerate = 1.0; |
| 1058 | cfg.threads = 0; |
| 1059 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1060 | let (mut bits, mut sum_psnr) = (0usize, 0.0); |
| 1061 | for (y, u, v) in &sources { |
| 1062 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 1063 | bits += enc.encode(&view).expect("encode").au.len() * 8; |
| 1064 | let rec = enc.reconstruction().expect("reconstruction"); |
| 1065 | sum_psnr += psnr(y, &rec.0); |
| 1066 | } |
| 1067 | let (i8x8, p8x8) = enc.transform_8x8_mbs(); |
| 1068 | let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; |
| 1069 | (bits as f64, sum_psnr / sources.len() as f64, share) |
| 1070 | }; |
| 1071 | let qps = [22, 26, 30, 34]; |
| 1072 | let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); |
| 1073 | let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); |
| 1074 | for (i, &qp) in qps.iter().enumerate() { |
| 1075 | let (ob, op, _) = off[i]; |
| 1076 | let (nb, np, share) = on[i]; |
| 1077 | eprintln!( |
| 1078 | "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", |
| 1079 | share * 100.0 |
| 1080 | ); |
| 1081 | } |
| 1082 | let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 1083 | let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 1084 | let bd = bd_psnr_delta(&on_curve, &off_curve); |
| 1085 | let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64; |
| 1086 | eprintln!( |
| 1087 | "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", |
| 1088 | share * 100.0 |
| 1089 | ); |
| 1090 | } |
| 1091 | |
| 1092 | |
| 1093 | |
| 1094 | |
| 1095 | |
| 1096 | |
| 1097 | |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | |
| 1102 | |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | |
| 1107 | |
| 1108 | |
| 1109 | |
| 1110 | |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | |
| 1116 | |
| 1117 | const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; |
| 1118 | |
| 1119 | fn have_x264() -> bool { |
| 1120 | ec_testkit::ffmpeg() |
| 1121 | .args(["-v", "error", "-hide_banner", "-encoders"]) |
| 1122 | .output() |
| 1123 | .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) |
| 1124 | } |
| 1125 | |
| 1126 | |
| 1127 | |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> { |
| 1132 | |
| 1133 | |
| 1134 | |
| 1135 | static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 1136 | let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1137 | let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); |
| 1138 | std::fs::create_dir_all(&dir).ok()?; |
| 1139 | let raw = dir.join(format!("in-q{qp}-{seq}.yuv")); |
| 1140 | let out = dir.join(format!("out-q{qp}-{seq}.264")); |
| 1141 | let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); |
| 1142 | for (y, u, v) in sources { |
| 1143 | buf.extend_from_slice(y); |
| 1144 | buf.extend_from_slice(u); |
| 1145 | buf.extend_from_slice(v); |
| 1146 | } |
| 1147 | pin_or_bail("x264_encode_qp", &raw, &buf)?; |
| 1148 | let status = ec_testkit::ffmpeg() |
| 1149 | .args(["-v", "error", "-y"]) |
| 1150 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 1151 | .args(["-s", &format!("{w}x{h}"), "-r", "1"]) |
| 1152 | .arg("-i") |
| 1153 | .arg(&raw) |
| 1154 | |
| 1155 | |
| 1156 | .args([ |
| 1157 | "-c:v", |
| 1158 | "libx264", |
| 1159 | "-preset", |
| 1160 | &std::env::var("EC_H264_X264_PRESET").unwrap_or_else(|_| "medium".into()), |
| 1161 | ]) |
| 1162 | .args(["-profile:v", "main", "-qp", &qp.to_string()]) |
| 1163 | .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"]) |
| 1164 | |
| 1165 | |
| 1166 | |
| 1167 | |
| 1168 | |
| 1169 | |
| 1170 | |
| 1171 | .args([ |
| 1172 | "-x264-params", |
| 1173 | &format!( |
| 1174 | "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", |
| 1175 | match std::env::var("EC_H264_X264_PARAMS") { |
| 1176 | |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | |
| 1181 | Ok(extra) if !extra.trim().trim_matches(':').is_empty() => |
| 1182 | format!(":{}", extra.trim().trim_matches(':')), |
| 1183 | _ => String::new(), |
| 1184 | } |
| 1185 | ), |
| 1186 | ]) |
| 1187 | .args(["-f", "h264"]) |
| 1188 | .arg(&out) |
| 1189 | .output() |
| 1190 | .ok()?; |
| 1191 | let _ = std::fs::remove_file(&raw); |
| 1192 | if !status.status.success() { |
| 1193 | eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); |
| 1194 | return None; |
| 1195 | } |
| 1196 | let stream = std::fs::read(&out).ok()?; |
| 1197 | let _ = std::fs::remove_file(&out); |
| 1198 | Some(stream) |
| 1199 | } |
| 1200 | |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | |
| 1212 | |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | |
| 1217 | |
| 1218 | |
| 1219 | |
| 1220 | |
| 1221 | |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | |
| 1227 | |
| 1228 | #[test] |
| 1229 | fn bd_psnr_vs_x264() { |
| 1230 | assert!(have_x264(), "the pinned ffmpeg has no libx264"); |
| 1231 | let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { |
| 1232 | Some(path) => clip_sources(&path, 24), |
| 1233 | None => { |
| 1234 | let (w, h, frames) = (352, 288, 24); |
| 1235 | let mut clip = Clip::new(w, h); |
| 1236 | let mut sources = Vec::with_capacity(frames); |
| 1237 | for t in 0..frames { |
| 1238 | clip.render_smooth(t); |
| 1239 | sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); |
| 1240 | } |
| 1241 | eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); |
| 1242 | (w, h, sources) |
| 1243 | } |
| 1244 | }; |
| 1245 | |
| 1246 | let gop: u32 = std::env::var("EC_H264_GOP") |
| 1247 | .ok() |
| 1248 | .and_then(|v| v.parse().ok()) |
| 1249 | .unwrap_or(10); |
| 1250 | let ours = |qp: i32| { |
| 1251 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1252 | cfg.qp = qp; |
| 1253 | cfg.gop_size = gop; |
| 1254 | if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { |
| 1255 | cfg.preset = ec_h264::Preset::Balanced; |
| 1256 | } |
| 1257 | cfg.cabac = true; |
| 1258 | cfg.framerate = 1.0; |
| 1259 | cfg.threads = 0; |
| 1260 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1261 | let (mut stream, mut sum_recon) = (Vec::new(), 0.0); |
| 1262 | for (y, u, v) in &sources { |
| 1263 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 1264 | stream.extend_from_slice(&enc.encode(&view).expect("encode").au); |
| 1265 | sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); |
| 1266 | } |
| 1267 | |
| 1268 | |
| 1269 | |
| 1270 | |
| 1271 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 1272 | assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); |
| 1273 | let sum: f64 = sources |
| 1274 | .iter() |
| 1275 | .zip(&decoded) |
| 1276 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 1277 | .sum(); |
| 1278 | let sum_yuv: f64 = sources |
| 1279 | .iter() |
| 1280 | .zip(&decoded) |
| 1281 | .map(|(s, d)| psnr_yuv(s, d)) |
| 1282 | .sum(); |
| 1283 | let (sum_u, sum_v) = ( |
| 1284 | sources |
| 1285 | .iter() |
| 1286 | .zip(&decoded) |
| 1287 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 1288 | .sum::<f64>(), |
| 1289 | sources |
| 1290 | .iter() |
| 1291 | .zip(&decoded) |
| 1292 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 1293 | .sum::<f64>(), |
| 1294 | ); |
| 1295 | eprintln!( |
| 1296 | " ours qp {qp}: u {:.2} dB v {:.2} dB", |
| 1297 | sum_u / sources.len() as f64, |
| 1298 | sum_v / sources.len() as f64 |
| 1299 | ); |
| 1300 | let (decoded_psnr, recon_psnr) = |
| 1301 | (sum / sources.len() as f64, sum_recon / sources.len() as f64); |
| 1302 | assert!( |
| 1303 | (decoded_psnr - recon_psnr).abs() < 0.05, |
| 1304 | "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ |
| 1305 | stream decodes to {decoded_psnr:.2} dB" |
| 1306 | ); |
| 1307 | ( |
| 1308 | (stream.len() * 8) as f64, |
| 1309 | decoded_psnr, |
| 1310 | sum_yuv / sources.len() as f64, |
| 1311 | ) |
| 1312 | }; |
| 1313 | let x264 = |qp: i32| { |
| 1314 | let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); |
| 1315 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); |
| 1316 | assert_eq!( |
| 1317 | decoded.len(), |
| 1318 | sources.len(), |
| 1319 | "x264 returned {} pictures for {} sources", |
| 1320 | decoded.len(), |
| 1321 | sources.len() |
| 1322 | ); |
| 1323 | let sum: f64 = sources |
| 1324 | .iter() |
| 1325 | .zip(&decoded) |
| 1326 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 1327 | .sum(); |
| 1328 | let sum_yuv: f64 = sources |
| 1329 | .iter() |
| 1330 | .zip(&decoded) |
| 1331 | .map(|(s, d)| psnr_yuv(s, d)) |
| 1332 | .sum(); |
| 1333 | let n = sources.len() as f64; |
| 1334 | eprintln!( |
| 1335 | " x264 qp {qp}: u {:.2} dB v {:.2} dB", |
| 1336 | sources |
| 1337 | .iter() |
| 1338 | .zip(&decoded) |
| 1339 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 1340 | .sum::<f64>() |
| 1341 | / n, |
| 1342 | sources |
| 1343 | .iter() |
| 1344 | .zip(&decoded) |
| 1345 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 1346 | .sum::<f64>() |
| 1347 | / n |
| 1348 | ); |
| 1349 | ((stream.len() * 8) as f64, sum / n, sum_yuv / n) |
| 1350 | }; |
| 1351 | |
| 1352 | let qps = [22, 26, 30, 34]; |
| 1353 | let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); |
| 1354 | let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); |
| 1355 | for (i, &qp) in qps.iter().enumerate() { |
| 1356 | let (ob, op, oy) = mine[i]; |
| 1357 | let (xb, xp, xy) = theirs[i]; |
| 1358 | eprintln!( |
| 1359 | "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ |
| 1360 | ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", |
| 1361 | (ob / xb - 1.0) * 100.0, |
| 1362 | op - xp, |
| 1363 | oy - xy |
| 1364 | ); |
| 1365 | } |
| 1366 | refuse_flat_window(theirs.iter().map(|&(_, p, _)| p), "EC_H264_CLIP_SKIP"); |
| 1367 | let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { |
| 1368 | v.iter() |
| 1369 | .map(|&(b, p, y)| (b, if luma { p } else { y })) |
| 1370 | .collect() |
| 1371 | }; |
| 1372 | let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); |
| 1373 | let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); |
| 1374 | eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); |
| 1375 | eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); |
| 1376 | |
| 1377 | |
| 1378 | |
| 1379 | if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 { |
| 1380 | assert!( |
| 1381 | bd > BD_PSNR_VS_X264_FLOOR, |
| 1382 | "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ |
| 1383 | {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" |
| 1384 | ); |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | |
| 1389 | |
| 1390 | |
| 1391 | |
| 1392 | |
| 1393 | |
| 1394 | |
| 1395 | |
| 1396 | #[test] |
| 1397 | fn bit_account_vs_x264() { |
| 1398 | assert!(have_x264(), "the pinned ffmpeg has no libx264"); |
| 1399 | let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { |
| 1400 | Some(path) => clip_sources(&path, 12), |
| 1401 | None => { |
| 1402 | let (w, h, frames) = (352, 288, 12); |
| 1403 | let mut clip = Clip::new(w, h); |
| 1404 | let mut sources = Vec::with_capacity(frames); |
| 1405 | for t in 0..frames { |
| 1406 | clip.render_smooth(t); |
| 1407 | sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); |
| 1408 | } |
| 1409 | eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); |
| 1410 | (w, h, sources) |
| 1411 | } |
| 1412 | }; |
| 1413 | let gop: u32 = 10; |
| 1414 | let account = |stream: &[u8]| { |
| 1415 | let mut dec = Decoder::new(); |
| 1416 | dec.set_output_order(OutputOrder::Decode); |
| 1417 | for nal in ec_h264_syntax::AnnexBIter::new(stream) { |
| 1418 | if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { |
| 1419 | dec.end_picture().expect("end of picture"); |
| 1420 | dec.push_nal(nal).expect("decoder accepts the NAL"); |
| 1421 | } |
| 1422 | while dec.next_frame().is_some() {} |
| 1423 | } |
| 1424 | dec.flush().expect("flush"); |
| 1425 | while dec.next_frame().is_some() {} |
| 1426 | (dec.bit_account(), dec.mb_shapes()) |
| 1427 | }; |
| 1428 | for qp in [26, 34] { |
| 1429 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1430 | cfg.qp = qp; |
| 1431 | cfg.gop_size = gop; |
| 1432 | cfg.cabac = true; |
| 1433 | cfg.framerate = 1.0; |
| 1434 | cfg.threads = 0; |
| 1435 | if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { |
| 1436 | cfg.preset = ec_h264::Preset::Balanced; |
| 1437 | } |
| 1438 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1439 | let mut ours = Vec::new(); |
| 1440 | for (y, u, v) in &sources { |
| 1441 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 1442 | ours.extend_from_slice(&enc.encode(&view).expect("encode").au); |
| 1443 | } |
| 1444 | let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); |
| 1445 | let ((a, sa), (b, sb)) = (account(&ours), account(&theirs)); |
| 1446 | eprintln!( |
| 1447 | "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes", |
| 1448 | sources.len(), |
| 1449 | ours.len(), |
| 1450 | theirs.len() |
| 1451 | ); |
| 1452 | let row = |name: &str, ours: u64, theirs: u64| { |
| 1453 | let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0); |
| 1454 | let delta = if t > 0.0 { |
| 1455 | format!("{:+.1}%", (o - t) / t * 100.0) |
| 1456 | } else { |
| 1457 | "--".to_string() |
| 1458 | }; |
| 1459 | eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}"); |
| 1460 | }; |
| 1461 | row("skip", a.skip, b.skip); |
| 1462 | row("mb_type", a.mb_type, b.mb_type); |
| 1463 | row("mv", a.mv, b.mv); |
| 1464 | row("ref_idx", a.ref_idx, b.ref_idx); |
| 1465 | row("cbp+qp", a.cbp_qp, b.cbp_qp); |
| 1466 | row("intra modes", a.intra_mode, b.intra_mode); |
| 1467 | row("residual luma", a.residual_luma, b.residual_luma); |
| 1468 | row("residual chroma", a.residual_chroma, b.residual_chroma); |
| 1469 | row("total accounted", a.total(), b.total()); |
| 1470 | let mix = |n: &str, s: &ec_h264::MbShapes| { |
| 1471 | eprintln!( |
| 1472 | " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", |
| 1473 | s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra |
| 1474 | ); |
| 1475 | }; |
| 1476 | mix("shapes ours", &sa); |
| 1477 | mix("shapes x264", &sb); |
| 1478 | } |
| 1479 | } |
| 1480 | |
| 1481 | |
| 1482 | |
| 1483 | |
| 1484 | |
| 1485 | |
| 1486 | #[test] |
| 1487 | fn balanced_partitions_decode_bit_exactly() { |
| 1488 | let (w, h) = (176, 144); |
| 1489 | let mut shapes = ec_h264::MbShapes::default(); |
| 1490 | for qp in [16, 26, 36] { |
| 1491 | let cavlc = qp == 26; |
| 1492 | let (stream, recons, _) = encode_clip(w, h, 8, |cfg| { |
| 1493 | cfg.qp = qp; |
| 1494 | cfg.cabac = !cavlc; |
| 1495 | cfg.preset = ec_h264::Preset::Balanced; |
| 1496 | }); |
| 1497 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 1498 | assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count"); |
| 1499 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 1500 | assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}"); |
| 1501 | assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); |
| 1502 | assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); |
| 1503 | } |
| 1504 | let mut dec = Decoder::new(); |
| 1505 | dec.set_output_order(OutputOrder::Decode); |
| 1506 | for nal in ec_h264_syntax::AnnexBIter::new(&stream) { |
| 1507 | if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { |
| 1508 | dec.end_picture().expect("end of picture"); |
| 1509 | dec.push_nal(nal).expect("decoder accepts the NAL"); |
| 1510 | } |
| 1511 | while dec.next_frame().is_some() {} |
| 1512 | } |
| 1513 | dec.flush().expect("flush"); |
| 1514 | while dec.next_frame().is_some() {} |
| 1515 | shapes.add_public(&dec.mb_shapes()); |
| 1516 | } |
| 1517 | eprintln!( |
| 1518 | "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", |
| 1519 | shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra |
| 1520 | ); |
| 1521 | assert!( |
| 1522 | shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0, |
| 1523 | "the sweep has to code every shape, or it proves nothing about them" |
| 1524 | ); |
| 1525 | } |
| 1526 | |
| 1527 | #[test] |
| 1528 | fn force_keyframe_restarts_the_gop() { |
| 1529 | let (w, h) = (64, 64); |
| 1530 | let mut clip = Clip::new(w, h); |
| 1531 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1532 | cfg.gop_size = 4; |
| 1533 | cfg.threads = 1; |
| 1534 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1535 | let mut stream = Vec::new(); |
| 1536 | let keys: Vec<bool> = (0..8) |
| 1537 | .map(|t| { |
| 1538 | clip.render(t); |
| 1539 | let pic = enc.encode_with(&clip.view(), t == 2).expect("encode"); |
| 1540 | stream.extend_from_slice(&pic.au); |
| 1541 | pic.key_frame |
| 1542 | }) |
| 1543 | .collect(); |
| 1544 | assert_eq!(keys, [true, false, true, false, false, false, true, false]); |
| 1545 | assert_eq!(decode_all(&stream).len(), 8); |
| 1546 | } |