| 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 j in col..5 { |
| 212 | a[col][j] /= div; |
| 213 | } |
| 214 | for row in 0..4 { |
| 215 | if row == col { |
| 216 | continue; |
| 217 | } |
| 218 | let f = a[row][col]; |
| 219 | for j in col..5 { |
| 220 | a[row][j] -= f * a[col][j]; |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | [a[0][4], a[1][4], a[2][4], a[3][4]] |
| 225 | } |
| 226 | |
| 227 | fn cubic_integral(c: [f64; 4], x: f64) -> f64 { |
| 228 | c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 |
| 229 | } |
| 230 | |
| 231 | fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { |
| 232 | let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); |
| 233 | let ys_candidate = std::array::from_fn(|i| candidate[i].1); |
| 234 | let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); |
| 235 | let ys_anchor = std::array::from_fn(|i| anchor[i].1); |
| 236 | let lo = xs_candidate |
| 237 | .iter() |
| 238 | .copied() |
| 239 | .fold(f64::INFINITY, f64::min) |
| 240 | .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); |
| 241 | let hi = xs_candidate |
| 242 | .iter() |
| 243 | .copied() |
| 244 | .fold(f64::NEG_INFINITY, f64::max) |
| 245 | .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); |
| 246 | assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); |
| 247 | let c_candidate = cubic_fit(xs_candidate, ys_candidate); |
| 248 | let c_anchor = cubic_fit(xs_anchor, ys_anchor); |
| 249 | (cubic_integral(c_candidate, hi) |
| 250 | - cubic_integral(c_candidate, lo) |
| 251 | - cubic_integral(c_anchor, hi) |
| 252 | + cubic_integral(c_anchor, lo)) |
| 253 | / (hi - lo) |
| 254 | } |
| 255 | |
| 256 | |
| 257 | |
| 258 | #[test] |
| 259 | fn reconstruction_matches_the_decoder() { |
| 260 | let mut t8x8_mbs = (0, 0); |
| 261 | for (w, h) in [(176, 144), (208, 122), (64, 48)] { |
| 262 | let mut clip = Clip::new(w, h); |
| 263 | for qp in [12, 24, 33, 44] { |
| 264 | for (threads, preset, cabac, t8x8) in [ |
| 265 | (1usize, Preset::Fast, true, false), |
| 266 | (4, Preset::Balanced, true, false), |
| 267 | (1, Preset::Fast, false, false), |
| 268 | (3, Preset::Balanced, false, false), |
| 269 | (2, Preset::Balanced, true, true), |
| 270 | (2, Preset::Balanced, false, true), |
| 271 | ] { |
| 272 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 273 | cfg.qp = qp; |
| 274 | cfg.gop_size = 5; |
| 275 | cfg.threads = threads; |
| 276 | cfg.preset = preset; |
| 277 | cfg.cabac = cabac; |
| 278 | cfg.transform_8x8 = t8x8; |
| 279 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 280 | let mut stream = Vec::new(); |
| 281 | let mut recons = Vec::new(); |
| 282 | for t in 0..8 { |
| 283 | clip.render(t); |
| 284 | let picture = enc.encode(&clip.view()).expect("encode"); |
| 285 | stream.extend_from_slice(&picture.au); |
| 286 | recons.push(enc.reconstruction().expect("a reconstruction")); |
| 287 | } |
| 288 | if t8x8 { |
| 289 | let (intra, inter) = enc.transform_8x8_mbs(); |
| 290 | t8x8_mbs.0 += intra; |
| 291 | t8x8_mbs.1 += inter; |
| 292 | } |
| 293 | let decoded = decode_all(&stream); |
| 294 | assert_eq!( |
| 295 | decoded.len(), |
| 296 | recons.len(), |
| 297 | "{w}x{h} qp {qp}: picture count" |
| 298 | ); |
| 299 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 300 | assert_eq!( |
| 301 | dec.0, rec.0, |
| 302 | "{w}x{h} qp {qp} t{threads}: luma of picture {i}" |
| 303 | ); |
| 304 | assert_eq!( |
| 305 | dec.1, rec.1, |
| 306 | "{w}x{h} qp {qp} t{threads}: Cb of picture {i}" |
| 307 | ); |
| 308 | assert_eq!( |
| 309 | dec.2, rec.2, |
| 310 | "{w}x{h} qp {qp} t{threads}: Cr of picture {i}" |
| 311 | ); |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | assert!( |
| 318 | t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, |
| 319 | "8x8 MBs across the sweep: intra {} inter {}", |
| 320 | t8x8_mbs.0, |
| 321 | t8x8_mbs.1 |
| 322 | ); |
| 323 | } |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | #[test] |
| 329 | fn quality_follows_the_quantiser() { |
| 330 | let (w, h) = (176, 144); |
| 331 | let mut clip = Clip::new(w, h); |
| 332 | let mut last = 0.0; |
| 333 | for qp in [40, 30, 20, 10] { |
| 334 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 335 | cfg.qp = qp; |
| 336 | cfg.gop_size = 4; |
| 337 | cfg.threads = 1; |
| 338 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 339 | let mut total = 0.0; |
| 340 | for t in 0..6 { |
| 341 | clip.render(t); |
| 342 | enc.encode(&clip.view()).expect("encode"); |
| 343 | let (y, _, _) = enc.reconstruction().unwrap(); |
| 344 | total += psnr(&clip.y, &y); |
| 345 | } |
| 346 | let avg = total / 6.0; |
| 347 | assert!( |
| 348 | avg > last, |
| 349 | "qp {qp}: PSNR {avg:.2} did not improve on {last:.2}" |
| 350 | ); |
| 351 | if qp == 10 { |
| 352 | assert!(avg > 45.0, "qp 10 should be near lossless, got {avg:.2}"); |
| 353 | } |
| 354 | last = avg; |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | |
| 359 | |
| 360 | #[test] |
| 361 | fn rate_control_hits_its_target() { |
| 362 | let (w, h) = (352, 288); |
| 363 | let mut clip = Clip::new(w, h); |
| 364 | let bitrate = 1_500_000u32; |
| 365 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 366 | cfg.bitrate = bitrate; |
| 367 | cfg.framerate = 25.0; |
| 368 | cfg.gop_size = 25; |
| 369 | cfg.threads = 2; |
| 370 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 371 | let mut bits = 0u64; |
| 372 | let frames = 50; |
| 373 | let mut keys = 0; |
| 374 | for t in 0..frames { |
| 375 | clip.render(t); |
| 376 | let p = enc.encode(&clip.view()).expect("encode"); |
| 377 | bits += p.au.len() as u64 * 8; |
| 378 | keys += u32::from(p.key_frame); |
| 379 | } |
| 380 | assert_eq!(keys, 2, "one IDR per GOP"); |
| 381 | let actual = bits as f64 / (frames as f64 / 25.0); |
| 382 | let ratio = actual / f64::from(bitrate); |
| 383 | assert!( |
| 384 | (0.7..1.35).contains(&ratio), |
| 385 | "bitrate {actual:.0} against target {bitrate} (ratio {ratio:.2})" |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | |
| 390 | |
| 391 | #[test] |
| 392 | fn all_intra_when_the_gop_is_one() { |
| 393 | let (w, h) = (64, 64); |
| 394 | let mut clip = Clip::new(w, h); |
| 395 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 396 | cfg.gop_size = 1; |
| 397 | cfg.qp = 26; |
| 398 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 399 | let mut stream = Vec::new(); |
| 400 | for t in 0..4 { |
| 401 | clip.render(t); |
| 402 | let p = enc.encode(&clip.view()).expect("encode"); |
| 403 | assert!(p.key_frame, "picture {t} is not a key frame"); |
| 404 | stream.extend_from_slice(&p.au); |
| 405 | } |
| 406 | assert_eq!(decode_all(&stream).len(), 4); |
| 407 | } |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | fn have_ffmpeg() -> bool { |
| 415 | std::process::Command::new("ffmpeg") |
| 416 | .arg("-version") |
| 417 | .stdout(std::process::Stdio::null()) |
| 418 | .stderr(std::process::Stdio::null()) |
| 419 | .status() |
| 420 | .is_ok_and(|s| s.success()) |
| 421 | } |
| 422 | |
| 423 | |
| 424 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { |
| 425 | let dir = std::env::temp_dir().join(format!("ec-h264-enc-{}", std::process::id())); |
| 426 | std::fs::create_dir_all(&dir).ok()?; |
| 427 | let path = dir.join(format!("s{}.264", stream.len())); |
| 428 | std::fs::write(&path, stream).ok()?; |
| 429 | let mut cmd = std::process::Command::new("ffmpeg"); |
| 430 | cmd.args(["-v", "error"]); |
| 431 | cmd.args(extra); |
| 432 | cmd.arg("-i").arg(&path); |
| 433 | cmd.args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]); |
| 434 | let out = cmd.output().ok()?; |
| 435 | let _ = std::fs::remove_file(&path); |
| 436 | if !out.status.success() { |
| 437 | eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); |
| 438 | return None; |
| 439 | } |
| 440 | let frame = w * h * 3 / 2; |
| 441 | if frame == 0 || out.stdout.len() % frame != 0 { |
| 442 | eprintln!( |
| 443 | "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", |
| 444 | out.stdout.len() |
| 445 | ); |
| 446 | return None; |
| 447 | } |
| 448 | Some( |
| 449 | out.stdout |
| 450 | .chunks(frame) |
| 451 | .map(|f| { |
| 452 | let (y, rest) = f.split_at(w * h); |
| 453 | let (u, v) = rest.split_at(w / 2 * h / 2); |
| 454 | (y.to_vec(), u.to_vec(), v.to_vec()) |
| 455 | }) |
| 456 | .collect(), |
| 457 | ) |
| 458 | } |
| 459 | |
| 460 | |
| 461 | fn encode_clip( |
| 462 | w: usize, |
| 463 | h: usize, |
| 464 | frames: usize, |
| 465 | configure: impl FnOnce(&mut EncoderConfig), |
| 466 | ) -> (Vec<u8>, Vec<Planes>, (u64, u64)) { |
| 467 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 468 | cfg.gop_size = 10; |
| 469 | cfg.threads = 3; |
| 470 | configure(&mut cfg); |
| 471 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 472 | let mut clip = Clip::new(w, h); |
| 473 | let mut stream = Vec::new(); |
| 474 | let mut recons = Vec::new(); |
| 475 | for t in 0..frames { |
| 476 | clip.render(t); |
| 477 | stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); |
| 478 | recons.push(enc.reconstruction().expect("reconstruction")); |
| 479 | } |
| 480 | (stream, recons, enc.transform_8x8_mbs()) |
| 481 | } |
| 482 | |
| 483 | |
| 484 | |
| 485 | |
| 486 | #[test] |
| 487 | fn eight_by_eight_gains_on_flat_and_text() { |
| 488 | let (w, h) = (320, 240); |
| 489 | let render = |t: usize, clip: &mut Clip| { |
| 490 | |
| 491 | let sx = |x: usize| x * 2 + t; |
| 492 | for y in 0..h { |
| 493 | for x in 0..w { |
| 494 | let (px, py) = (sx(x) as f64 / 2.0, y as f64); |
| 495 | |
| 496 | |
| 497 | let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; |
| 498 | |
| 499 | |
| 500 | |
| 501 | let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; |
| 502 | let shade = shade + tri(px) * tri(py) / 1.5; |
| 503 | |
| 504 | let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24); |
| 505 | let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7; |
| 506 | let stem = (2..5).contains(&cx); |
| 507 | let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; |
| 508 | let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; |
| 509 | let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); |
| 510 | clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; |
| 511 | } |
| 512 | } |
| 513 | clip.u.fill(128); |
| 514 | clip.v.fill(128); |
| 515 | }; |
| 516 | let run = |t8x8: bool, qp: i32, cabac: bool| { |
| 517 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 518 | cfg.qp = qp; |
| 519 | cfg.gop_size = 10; |
| 520 | cfg.transform_8x8 = t8x8; |
| 521 | cfg.cabac = cabac; |
| 522 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 523 | let mut clip = Clip::new(w, h); |
| 524 | let (mut bits, mut sum_psnr) = (0usize, 0.0); |
| 525 | let mut share = 0.0; |
| 526 | for t in 0..10 { |
| 527 | render(t, &mut clip); |
| 528 | bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; |
| 529 | let rec = enc.reconstruction().expect("reconstruction"); |
| 530 | sum_psnr += psnr(&clip.y, &rec.0); |
| 531 | } |
| 532 | if t8x8 { |
| 533 | let (i, p) = enc.transform_8x8_mbs(); |
| 534 | eprintln!("8x8 MBs: intra {i} inter {p}"); |
| 535 | share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); |
| 536 | } |
| 537 | (bits as f64, sum_psnr / 10.0, share) |
| 538 | }; |
| 539 | let qps = [22, 26, 30, 34]; |
| 540 | let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); |
| 541 | let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); |
| 542 | let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 543 | let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 544 | let bd = bd_psnr_delta(&on_curve, &off_curve); |
| 545 | let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64; |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | |
| 552 | |
| 553 | const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.230; |
| 554 | eprintln!( |
| 555 | "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", |
| 556 | share * 100.0 |
| 557 | ); |
| 558 | assert!(share > 0.0, "no 8x8 macroblocks were coded"); |
| 559 | assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); |
| 560 | assert!( |
| 561 | bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, |
| 562 | "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" |
| 563 | ); |
| 564 | } |
| 565 | |
| 566 | |
| 567 | |
| 568 | #[test] |
| 569 | fn ffmpeg_decodes_bit_exactly() { |
| 570 | if !have_ffmpeg() { |
| 571 | eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH"); |
| 572 | return; |
| 573 | } |
| 574 | let mut t8x8_mbs = (0, 0); |
| 575 | for (w, h) in [(176, 144), (322, 242)] { |
| 576 | for qp in [10, 20, 28, 37, 47] { |
| 577 | let cavlc = qp % 2 == 0; |
| 578 | let t8x8 = qp % 3 == 1; |
| 579 | let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { |
| 580 | cfg.qp = qp; |
| 581 | cfg.cabac = !cavlc; |
| 582 | cfg.transform_8x8 = t8x8; |
| 583 | }); |
| 584 | t8x8_mbs.0 += intra; |
| 585 | t8x8_mbs.1 += inter; |
| 586 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 587 | assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count"); |
| 588 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 589 | assert_eq!(dec.0, rec.0, "{w}x{h} qp {qp}: luma of frame {i}"); |
| 590 | assert_eq!(dec.1, rec.1, "{w}x{h} qp {qp}: Cb of frame {i}"); |
| 591 | assert_eq!(dec.2, rec.2, "{w}x{h} qp {qp}: Cr of frame {i}"); |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | assert!( |
| 596 | t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, |
| 597 | "8x8 MBs across the sweep: intra {} inter {}", |
| 598 | t8x8_mbs.0, |
| 599 | t8x8_mbs.1 |
| 600 | ); |
| 601 | } |
| 602 | |
| 603 | |
| 604 | #[test] |
| 605 | fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { |
| 606 | if !have_ffmpeg() { |
| 607 | eprintln!("SKIP ffmpeg_decodes_a_cbr_stream_bit_exactly: no ffmpeg on PATH"); |
| 608 | return; |
| 609 | } |
| 610 | let (w, h) = (352, 288); |
| 611 | let (stream, recons, _) = encode_clip(w, h, 12, |cfg| { |
| 612 | cfg.bitrate = 2_000_000; |
| 613 | cfg.framerate = 25.0; |
| 614 | }); |
| 615 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 616 | assert_eq!(decoded.len(), recons.len()); |
| 617 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 618 | assert_eq!(dec.0, rec.0, "luma of frame {i}"); |
| 619 | assert_eq!( |
| 620 | (dec.1.clone(), dec.2.clone()), |
| 621 | (rec.1.clone(), rec.2.clone()), |
| 622 | "chroma of frame {i}" |
| 623 | ); |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 630 | #[test] |
| 631 | fn vaapi_decodes_our_stream() { |
| 632 | if !have_ffmpeg() || !std::path::Path::new("/dev/dri/renderD128").exists() { |
| 633 | eprintln!("SKIP vaapi_decodes_our_stream: no ffmpeg or no render node"); |
| 634 | return; |
| 635 | } |
| 636 | let (w, h) = (352, 288); |
| 637 | let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { |
| 638 | cfg.qp = 26; |
| 639 | cfg.transform_8x8 = true; |
| 640 | }); |
| 641 | assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream"); |
| 642 | let Some(decoded) = ffmpeg_decode( |
| 643 | &stream, |
| 644 | w, |
| 645 | h, |
| 646 | &[ |
| 647 | "-hwaccel", |
| 648 | "vaapi", |
| 649 | "-hwaccel_device", |
| 650 | "/dev/dri/renderD128", |
| 651 | ], |
| 652 | ) else { |
| 653 | eprintln!("SKIP vaapi_decodes_our_stream: VA-API decode unavailable here"); |
| 654 | return; |
| 655 | }; |
| 656 | assert_eq!(decoded.len(), recons.len(), "VA-API frame count"); |
| 657 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 658 | let p = psnr(&dec.0, &rec.0); |
| 659 | assert!(p > 60.0, "VA-API luma of frame {i} differs: PSNR {p:.1} dB"); |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | #[test] |
| 672 | fn real_library_frames_encode_and_decode_exactly() { |
| 673 | use ec_core::registry::{Decoder as _, Demuxer as _}; |
| 674 | |
| 675 | if !have_ffmpeg() { |
| 676 | eprintln!("SKIP real_library_frames: no ffmpeg on PATH"); |
| 677 | return; |
| 678 | } |
| 679 | let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 680 | .join("../../fixtures/real-library-manifest.tsv"); |
| 681 | let Ok(text) = std::fs::read_to_string(&manifest) else { |
| 682 | eprintln!("SKIP real_library_frames: {} missing", manifest.display()); |
| 683 | return; |
| 684 | }; |
| 685 | |
| 686 | let mut source = None; |
| 687 | for line in text.lines().skip(1) { |
| 688 | let f: Vec<&str> = line.split('\t').collect(); |
| 689 | if f.len() < 7 || f[2] != "h264" || f[5] != "yuv420p" { |
| 690 | continue; |
| 691 | } |
| 692 | let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else { |
| 693 | continue; |
| 694 | }; |
| 695 | if w < 1280 || h < 720 || !w.is_multiple_of(2) || !h.is_multiple_of(2) { |
| 696 | continue; |
| 697 | } |
| 698 | if !f[1].contains("mp4") || !std::path::Path::new(f[0]).exists() { |
| 699 | continue; |
| 700 | } |
| 701 | source = Some((f[0].to_string(), w, h)); |
| 702 | break; |
| 703 | } |
| 704 | let Some((path, w, h)) = source else { |
| 705 | eprintln!("SKIP real_library_frames: no H.264 4:2:0 mp4 in the manifest"); |
| 706 | return; |
| 707 | }; |
| 708 | |
| 709 | |
| 710 | let file = std::fs::File::open(&path).expect("source opens"); |
| 711 | let mut demux = |
| 712 | ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); |
| 713 | let (index, params) = demux |
| 714 | .streams() |
| 715 | .iter() |
| 716 | .find(|s| s.params.codec == ec_core::registry::CodecId::H264) |
| 717 | .map(|s| (s.index, s.params.clone())) |
| 718 | .expect("an H.264 track"); |
| 719 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); |
| 720 | let mut sources: Vec<Planes> = Vec::new(); |
| 721 | while sources.len() < 12 { |
| 722 | let Ok(packet) = demux.next_packet() else { |
| 723 | break; |
| 724 | }; |
| 725 | if packet.stream != index { |
| 726 | continue; |
| 727 | } |
| 728 | dec.send_packet(&packet).expect("decode"); |
| 729 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 730 | if sources.len() < 12 { |
| 731 | sources.push(planes_of(&f)); |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | assert!( |
| 736 | sources.len() >= 6, |
| 737 | "only {} pictures decoded from the library file", |
| 738 | sources.len() |
| 739 | ); |
| 740 | |
| 741 | let bitrate = 8_000_000u32; |
| 742 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 743 | cfg.bitrate = bitrate; |
| 744 | cfg.framerate = 25.0; |
| 745 | cfg.gop_size = 25; |
| 746 | cfg.threads = 0; |
| 747 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 748 | let mut stream = Vec::new(); |
| 749 | let mut recons = Vec::new(); |
| 750 | let mut bits = 0u64; |
| 751 | for (y, u, v) in &sources { |
| 752 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 753 | let p = enc.encode(&view).expect("encode"); |
| 754 | bits += p.au.len() as u64 * 8; |
| 755 | stream.extend_from_slice(&p.au); |
| 756 | recons.push(enc.reconstruction().expect("reconstruction")); |
| 757 | } |
| 758 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 759 | assert_eq!(decoded.len(), recons.len(), "picture count"); |
| 760 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 761 | assert_eq!(dec.0, rec.0, "luma of picture {i} from the library clip"); |
| 762 | assert_eq!(dec.1, rec.1, "Cb of picture {i}"); |
| 763 | assert_eq!(dec.2, rec.2, "Cr of picture {i}"); |
| 764 | } |
| 765 | let quality: f64 = sources |
| 766 | .iter() |
| 767 | .zip(&recons) |
| 768 | .map(|((y, ..), (ry, ..))| psnr(y, ry)) |
| 769 | .sum::<f64>() |
| 770 | / sources.len() as f64; |
| 771 | let rate = bits as f64 / (sources.len() as f64 / 25.0); |
| 772 | eprintln!( |
| 773 | "library clip {w}x{h}: {} pictures, {:.0} kbit/s asked {:.0}, luma PSNR {quality:.2} dB", |
| 774 | sources.len(), |
| 775 | rate / 1000.0, |
| 776 | f64::from(bitrate) / 1000.0 |
| 777 | ); |
| 778 | assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); |
| 779 | } |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { |
| 785 | use ec_core::registry::{Decoder as _, Demuxer as _}; |
| 786 | |
| 787 | let file = std::fs::File::open(path).expect("source opens"); |
| 788 | let mut demux = |
| 789 | ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); |
| 790 | let (index, params) = demux |
| 791 | .streams() |
| 792 | .iter() |
| 793 | .find(|s| s.params.codec == ec_core::registry::CodecId::H264) |
| 794 | .map(|s| (s.index, s.params.clone())) |
| 795 | .expect("an H.264 track"); |
| 796 | let video = match ¶ms.media { |
| 797 | ec_core::registry::MediaParameters::Video(v) => v, |
| 798 | _ => panic!("the H.264 track carries no video parameters"), |
| 799 | }; |
| 800 | let (w, h) = (video.width as usize, video.height as usize); |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | |
| 807 | let stride = match std::env::var("EC_H264_CLIP_STRIDE").as_deref() { |
| 808 | Ok("fps") => video |
| 809 | .frame_rate |
| 810 | .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)), |
| 811 | Ok(n) => n.parse().unwrap_or(1usize).max(1), |
| 812 | Err(_) => 1, |
| 813 | }; |
| 814 | let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); |
| 815 | |
| 816 | |
| 817 | let skip: usize = std::env::var("EC_H264_CLIP_SKIP") |
| 818 | .ok() |
| 819 | .and_then(|v| v.parse().ok()) |
| 820 | .unwrap_or(0); |
| 821 | let mut sources: Vec<Planes> = Vec::new(); |
| 822 | let mut seen = 0usize; |
| 823 | while sources.len() < want { |
| 824 | let Ok(packet) = demux.next_packet() else { |
| 825 | break; |
| 826 | }; |
| 827 | if packet.stream != index { |
| 828 | continue; |
| 829 | } |
| 830 | dec.send_packet(&packet).expect("decode"); |
| 831 | while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { |
| 832 | if seen >= skip && sources.len() < want && (seen - skip).is_multiple_of(stride) { |
| 833 | sources.push(planes_of(&f)); |
| 834 | } |
| 835 | seen += 1; |
| 836 | } |
| 837 | } |
| 838 | assert!( |
| 839 | sources.len() >= 10, |
| 840 | "only {} pictures decoded from {}", |
| 841 | sources.len(), |
| 842 | path.to_string_lossy() |
| 843 | ); |
| 844 | eprintln!( |
| 845 | "{}: {}x{}, {} pictures, every {stride}th of {seen}", |
| 846 | path.to_string_lossy(), |
| 847 | w, |
| 848 | h, |
| 849 | sources.len() |
| 850 | ); |
| 851 | (w, h, sources) |
| 852 | } |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | #[test] |
| 863 | #[ignore = "set EC_H264_CLIP to a media file of yours"] |
| 864 | fn real_clip_t8x8_bd_psnr() { |
| 865 | let Some(path) = std::env::var_os("EC_H264_CLIP") else { |
| 866 | panic!("EC_H264_CLIP must name a media file"); |
| 867 | }; |
| 868 | let (w, h, sources) = clip_sources(&path, 30); |
| 869 | |
| 870 | let run = |t8x8: bool, qp: i32| { |
| 871 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 872 | cfg.qp = qp; |
| 873 | cfg.gop_size = 10; |
| 874 | cfg.cabac = true; |
| 875 | cfg.transform_8x8 = t8x8; |
| 876 | cfg.framerate = 1.0; |
| 877 | cfg.threads = 0; |
| 878 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 879 | let (mut bits, mut sum_psnr) = (0usize, 0.0); |
| 880 | for (y, u, v) in &sources { |
| 881 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 882 | bits += enc.encode(&view).expect("encode").au.len() * 8; |
| 883 | let rec = enc.reconstruction().expect("reconstruction"); |
| 884 | sum_psnr += psnr(y, &rec.0); |
| 885 | } |
| 886 | let (i8x8, p8x8) = enc.transform_8x8_mbs(); |
| 887 | let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; |
| 888 | (bits as f64, sum_psnr / sources.len() as f64, share) |
| 889 | }; |
| 890 | let qps = [22, 26, 30, 34]; |
| 891 | let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); |
| 892 | let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); |
| 893 | for (i, &qp) in qps.iter().enumerate() { |
| 894 | let (ob, op, _) = off[i]; |
| 895 | let (nb, np, share) = on[i]; |
| 896 | eprintln!( |
| 897 | "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", |
| 898 | share * 100.0 |
| 899 | ); |
| 900 | } |
| 901 | let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 902 | let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); |
| 903 | let bd = bd_psnr_delta(&on_curve, &off_curve); |
| 904 | let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64; |
| 905 | eprintln!( |
| 906 | "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", |
| 907 | share * 100.0 |
| 908 | ); |
| 909 | } |
| 910 | |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | |
| 921 | |
| 922 | |
| 923 | |
| 924 | |
| 925 | |
| 926 | |
| 927 | |
| 928 | |
| 929 | |
| 930 | |
| 931 | |
| 932 | |
| 933 | |
| 934 | |
| 935 | |
| 936 | const BD_PSNR_VS_X264_FLOOR: f64 = -4.15; |
| 937 | |
| 938 | fn have_x264() -> bool { |
| 939 | std::process::Command::new("ffmpeg") |
| 940 | .args(["-v", "error", "-hide_banner", "-encoders"]) |
| 941 | .output() |
| 942 | .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx264")) |
| 943 | } |
| 944 | |
| 945 | |
| 946 | |
| 947 | |
| 948 | |
| 949 | |
| 950 | fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> { |
| 951 | let dir = std::env::temp_dir().join(format!("ec-h264-x264-{}", std::process::id())); |
| 952 | std::fs::create_dir_all(&dir).ok()?; |
| 953 | let raw = dir.join(format!("in-q{qp}.yuv")); |
| 954 | let out = dir.join(format!("out-q{qp}.264")); |
| 955 | let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); |
| 956 | for (y, u, v) in sources { |
| 957 | buf.extend_from_slice(y); |
| 958 | buf.extend_from_slice(u); |
| 959 | buf.extend_from_slice(v); |
| 960 | } |
| 961 | std::fs::write(&raw, &buf).ok()?; |
| 962 | let status = std::process::Command::new("ffmpeg") |
| 963 | .args(["-v", "error", "-y"]) |
| 964 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 965 | .args(["-s", &format!("{w}x{h}"), "-r", "1"]) |
| 966 | .arg("-i") |
| 967 | .arg(&raw) |
| 968 | .args(["-c:v", "libx264", "-preset", "medium"]) |
| 969 | .args(["-profile:v", "main", "-qp", &qp.to_string()]) |
| 970 | .args(["-g", &gop.to_string(), "-bf", "0", "-refs", "1"]) |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | .args([ |
| 979 | "-x264-params", |
| 980 | &format!( |
| 981 | "scenecut=0:aq-mode=0:psy=0:8x8dct=0:ipratio=1.0:pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}", |
| 982 | match std::env::var("EC_H264_X264_PARAMS") { |
| 983 | |
| 984 | |
| 985 | |
| 986 | |
| 987 | |
| 988 | Ok(extra) if !extra.trim().trim_matches(':').is_empty() => |
| 989 | format!(":{}", extra.trim().trim_matches(':')), |
| 990 | _ => String::new(), |
| 991 | } |
| 992 | ), |
| 993 | ]) |
| 994 | .args(["-f", "h264"]) |
| 995 | .arg(&out) |
| 996 | .output() |
| 997 | .ok()?; |
| 998 | let _ = std::fs::remove_file(&raw); |
| 999 | if !status.status.success() { |
| 1000 | eprintln!("x264 failed: {}", String::from_utf8_lossy(&status.stderr)); |
| 1001 | return None; |
| 1002 | } |
| 1003 | let stream = std::fs::read(&out).ok()?; |
| 1004 | let _ = std::fs::remove_file(&out); |
| 1005 | Some(stream) |
| 1006 | } |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | |
| 1016 | |
| 1017 | |
| 1018 | |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | |
| 1029 | |
| 1030 | |
| 1031 | |
| 1032 | |
| 1033 | |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn bd_psnr_vs_x264() { |
| 1037 | if !have_ffmpeg() || !have_x264() { |
| 1038 | eprintln!( |
| 1039 | "SKIP bd_psnr_vs_x264: no ffmpeg with libx264 on PATH. \ |
| 1040 | Install one, then: cargo test --release -p ec-h264 --test encode \ |
| 1041 | bd_psnr_vs_x264 -- --nocapture" |
| 1042 | ); |
| 1043 | return; |
| 1044 | } |
| 1045 | let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { |
| 1046 | Some(path) => clip_sources(&path, 24), |
| 1047 | None => { |
| 1048 | let (w, h, frames) = (352, 288, 24); |
| 1049 | let mut clip = Clip::new(w, h); |
| 1050 | let mut sources = Vec::with_capacity(frames); |
| 1051 | for t in 0..frames { |
| 1052 | clip.render_smooth(t); |
| 1053 | sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); |
| 1054 | } |
| 1055 | eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); |
| 1056 | (w, h, sources) |
| 1057 | } |
| 1058 | }; |
| 1059 | |
| 1060 | let gop: u32 = std::env::var("EC_H264_GOP") |
| 1061 | .ok() |
| 1062 | .and_then(|v| v.parse().ok()) |
| 1063 | .unwrap_or(10); |
| 1064 | let ours = |qp: i32| { |
| 1065 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1066 | cfg.qp = qp; |
| 1067 | cfg.gop_size = gop; |
| 1068 | if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { |
| 1069 | cfg.preset = ec_h264::Preset::Balanced; |
| 1070 | } |
| 1071 | cfg.cabac = true; |
| 1072 | cfg.framerate = 1.0; |
| 1073 | cfg.threads = 0; |
| 1074 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1075 | let (mut stream, mut sum_recon) = (Vec::new(), 0.0); |
| 1076 | for (y, u, v) in &sources { |
| 1077 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 1078 | stream.extend_from_slice(&enc.encode(&view).expect("encode").au); |
| 1079 | sum_recon += psnr(y, &enc.reconstruction().expect("reconstruction").0); |
| 1080 | } |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 1086 | assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); |
| 1087 | let sum: f64 = sources |
| 1088 | .iter() |
| 1089 | .zip(&decoded) |
| 1090 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 1091 | .sum(); |
| 1092 | let sum_yuv: f64 = sources |
| 1093 | .iter() |
| 1094 | .zip(&decoded) |
| 1095 | .map(|(s, d)| psnr_yuv(s, d)) |
| 1096 | .sum(); |
| 1097 | let (sum_u, sum_v) = ( |
| 1098 | sources |
| 1099 | .iter() |
| 1100 | .zip(&decoded) |
| 1101 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 1102 | .sum::<f64>(), |
| 1103 | sources |
| 1104 | .iter() |
| 1105 | .zip(&decoded) |
| 1106 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 1107 | .sum::<f64>(), |
| 1108 | ); |
| 1109 | eprintln!( |
| 1110 | " ours qp {qp}: u {:.2} dB v {:.2} dB", |
| 1111 | sum_u / sources.len() as f64, |
| 1112 | sum_v / sources.len() as f64 |
| 1113 | ); |
| 1114 | let (decoded_psnr, recon_psnr) = |
| 1115 | (sum / sources.len() as f64, sum_recon / sources.len() as f64); |
| 1116 | assert!( |
| 1117 | (decoded_psnr - recon_psnr).abs() < 0.05, |
| 1118 | "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ |
| 1119 | stream decodes to {decoded_psnr:.2} dB" |
| 1120 | ); |
| 1121 | ( |
| 1122 | (stream.len() * 8) as f64, |
| 1123 | decoded_psnr, |
| 1124 | sum_yuv / sources.len() as f64, |
| 1125 | ) |
| 1126 | }; |
| 1127 | let x264 = |qp: i32| { |
| 1128 | let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); |
| 1129 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes x264's own stream"); |
| 1130 | assert_eq!( |
| 1131 | decoded.len(), |
| 1132 | sources.len(), |
| 1133 | "x264 returned {} pictures for {} sources", |
| 1134 | decoded.len(), |
| 1135 | sources.len() |
| 1136 | ); |
| 1137 | let sum: f64 = sources |
| 1138 | .iter() |
| 1139 | .zip(&decoded) |
| 1140 | .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) |
| 1141 | .sum(); |
| 1142 | let sum_yuv: f64 = sources |
| 1143 | .iter() |
| 1144 | .zip(&decoded) |
| 1145 | .map(|(s, d)| psnr_yuv(s, d)) |
| 1146 | .sum(); |
| 1147 | let n = sources.len() as f64; |
| 1148 | eprintln!( |
| 1149 | " x264 qp {qp}: u {:.2} dB v {:.2} dB", |
| 1150 | sources |
| 1151 | .iter() |
| 1152 | .zip(&decoded) |
| 1153 | .map(|(s, d)| psnr(&s.1, &d.1)) |
| 1154 | .sum::<f64>() |
| 1155 | / n, |
| 1156 | sources |
| 1157 | .iter() |
| 1158 | .zip(&decoded) |
| 1159 | .map(|(s, d)| psnr(&s.2, &d.2)) |
| 1160 | .sum::<f64>() |
| 1161 | / n |
| 1162 | ); |
| 1163 | ((stream.len() * 8) as f64, sum / n, sum_yuv / n) |
| 1164 | }; |
| 1165 | |
| 1166 | let qps = [22, 26, 30, 34]; |
| 1167 | let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); |
| 1168 | let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); |
| 1169 | for (i, &qp) in qps.iter().enumerate() { |
| 1170 | let (ob, op, oy) = mine[i]; |
| 1171 | let (xb, xp, xy) = theirs[i]; |
| 1172 | eprintln!( |
| 1173 | "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ |
| 1174 | ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", |
| 1175 | (ob / xb - 1.0) * 100.0, |
| 1176 | op - xp, |
| 1177 | oy - xy |
| 1178 | ); |
| 1179 | } |
| 1180 | let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { |
| 1181 | v.iter() |
| 1182 | .map(|&(b, p, y)| (b, if luma { p } else { y })) |
| 1183 | .collect() |
| 1184 | }; |
| 1185 | let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); |
| 1186 | let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); |
| 1187 | eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); |
| 1188 | eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); |
| 1189 | |
| 1190 | |
| 1191 | |
| 1192 | if std::env::var_os("EC_H264_CLIP").is_none() && gop == 10 { |
| 1193 | assert!( |
| 1194 | bd > BD_PSNR_VS_X264_FLOOR, |
| 1195 | "BD-PSNR against x264 fell to {bd:+.3} dB, past the \ |
| 1196 | {BD_PSNR_VS_X264_FLOOR:+.3} dB floor" |
| 1197 | ); |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | |
| 1202 | |
| 1203 | |
| 1204 | |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | #[test] |
| 1210 | fn bit_account_vs_x264() { |
| 1211 | if !have_ffmpeg() || !have_x264() { |
| 1212 | eprintln!("SKIP bit_account_vs_x264: no ffmpeg with libx264 on PATH"); |
| 1213 | return; |
| 1214 | } |
| 1215 | let (w, h, sources) = match std::env::var_os("EC_H264_CLIP") { |
| 1216 | Some(path) => clip_sources(&path, 12), |
| 1217 | None => { |
| 1218 | let (w, h, frames) = (352, 288, 12); |
| 1219 | let mut clip = Clip::new(w, h); |
| 1220 | let mut sources = Vec::with_capacity(frames); |
| 1221 | for t in 0..frames { |
| 1222 | clip.render_smooth(t); |
| 1223 | sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); |
| 1224 | } |
| 1225 | eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); |
| 1226 | (w, h, sources) |
| 1227 | } |
| 1228 | }; |
| 1229 | let gop: u32 = 10; |
| 1230 | let account = |stream: &[u8]| { |
| 1231 | let mut dec = Decoder::new(); |
| 1232 | dec.set_output_order(OutputOrder::Decode); |
| 1233 | for nal in ec_h264_syntax::AnnexBIter::new(stream) { |
| 1234 | if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { |
| 1235 | dec.end_picture().expect("end of picture"); |
| 1236 | dec.push_nal(nal).expect("decoder accepts the NAL"); |
| 1237 | } |
| 1238 | while dec.next_frame().is_some() {} |
| 1239 | } |
| 1240 | dec.flush().expect("flush"); |
| 1241 | while dec.next_frame().is_some() {} |
| 1242 | (dec.bit_account(), dec.mb_shapes()) |
| 1243 | }; |
| 1244 | for qp in [26, 34] { |
| 1245 | let mut cfg = EncoderConfig::new(w as u32, h as u32); |
| 1246 | cfg.qp = qp; |
| 1247 | cfg.gop_size = gop; |
| 1248 | cfg.cabac = true; |
| 1249 | cfg.framerate = 1.0; |
| 1250 | cfg.threads = 0; |
| 1251 | if std::env::var_os("EC_H264_PRESET_BALANCED").is_some() { |
| 1252 | cfg.preset = ec_h264::Preset::Balanced; |
| 1253 | } |
| 1254 | let mut enc = Encoder::new(cfg).expect("encoder"); |
| 1255 | let mut ours = Vec::new(); |
| 1256 | for (y, u, v) in &sources { |
| 1257 | let view = PictureView::i420(w as u32, h as u32, y, u, v); |
| 1258 | ours.extend_from_slice(&enc.encode(&view).expect("encode").au); |
| 1259 | } |
| 1260 | let theirs = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); |
| 1261 | let ((a, sa), (b, sb)) = (account(&ours), account(&theirs)); |
| 1262 | eprintln!( |
| 1263 | "qp {qp}: {} pictures, ours {} bytes, x264 {} bytes", |
| 1264 | sources.len(), |
| 1265 | ours.len(), |
| 1266 | theirs.len() |
| 1267 | ); |
| 1268 | let row = |name: &str, ours: u64, theirs: u64| { |
| 1269 | let (o, t) = (ours as f64 / 256.0, theirs as f64 / 256.0); |
| 1270 | let delta = if t > 0.0 { |
| 1271 | format!("{:+.1}%", (o - t) / t * 100.0) |
| 1272 | } else { |
| 1273 | "--".to_string() |
| 1274 | }; |
| 1275 | eprintln!(" {name:<16} ours {o:>12.0} bits | x264 {t:>12.0} bits {delta:>8}"); |
| 1276 | }; |
| 1277 | row("skip", a.skip, b.skip); |
| 1278 | row("mb_type", a.mb_type, b.mb_type); |
| 1279 | row("mv", a.mv, b.mv); |
| 1280 | row("ref_idx", a.ref_idx, b.ref_idx); |
| 1281 | row("cbp+qp", a.cbp_qp, b.cbp_qp); |
| 1282 | row("intra modes", a.intra_mode, b.intra_mode); |
| 1283 | row("residual luma", a.residual_luma, b.residual_luma); |
| 1284 | row("residual chroma", a.residual_chroma, b.residual_chroma); |
| 1285 | row("total accounted", a.total(), b.total()); |
| 1286 | let mix = |n: &str, s: &ec_h264::MbShapes| { |
| 1287 | eprintln!( |
| 1288 | " {n:<16} skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", |
| 1289 | s.skip, s.p16x16, s.p16x8, s.p8x16, s.p8x8, s.intra |
| 1290 | ); |
| 1291 | }; |
| 1292 | mix("shapes ours", &sa); |
| 1293 | mix("shapes x264", &sb); |
| 1294 | } |
| 1295 | } |
| 1296 | |
| 1297 | |
| 1298 | |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | #[test] |
| 1303 | fn balanced_partitions_decode_bit_exactly() { |
| 1304 | if !have_ffmpeg() { |
| 1305 | eprintln!("SKIP balanced_partitions_decode_bit_exactly: no ffmpeg on PATH"); |
| 1306 | return; |
| 1307 | } |
| 1308 | let (w, h) = (176, 144); |
| 1309 | let mut shapes = ec_h264::MbShapes::default(); |
| 1310 | for qp in [16, 26, 36] { |
| 1311 | let cavlc = qp == 26; |
| 1312 | let (stream, recons, _) = encode_clip(w, h, 8, |cfg| { |
| 1313 | cfg.qp = qp; |
| 1314 | cfg.cabac = !cavlc; |
| 1315 | cfg.preset = ec_h264::Preset::Balanced; |
| 1316 | }); |
| 1317 | let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); |
| 1318 | assert_eq!(decoded.len(), recons.len(), "qp {qp}: frame count"); |
| 1319 | for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { |
| 1320 | assert_eq!(dec.0, rec.0, "qp {qp}: luma of frame {i}"); |
| 1321 | assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); |
| 1322 | assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); |
| 1323 | } |
| 1324 | let mut dec = Decoder::new(); |
| 1325 | dec.set_output_order(OutputOrder::Decode); |
| 1326 | for nal in ec_h264_syntax::AnnexBIter::new(&stream) { |
| 1327 | if dec.push_nal(nal).expect("decoder accepts the NAL") == NalOutcome::PictureBoundary { |
| 1328 | dec.end_picture().expect("end of picture"); |
| 1329 | dec.push_nal(nal).expect("decoder accepts the NAL"); |
| 1330 | } |
| 1331 | while dec.next_frame().is_some() {} |
| 1332 | } |
| 1333 | dec.flush().expect("flush"); |
| 1334 | while dec.next_frame().is_some() {} |
| 1335 | shapes.add_public(&dec.mb_shapes()); |
| 1336 | } |
| 1337 | eprintln!( |
| 1338 | "balanced shapes: skip {} 16x16 {} 16x8 {} 8x16 {} 8x8 {} intra {}", |
| 1339 | shapes.skip, shapes.p16x16, shapes.p16x8, shapes.p8x16, shapes.p8x8, shapes.intra |
| 1340 | ); |
| 1341 | assert!( |
| 1342 | shapes.p16x8 + shapes.p8x16 > 0 && shapes.p8x8 > 0, |
| 1343 | "the sweep has to code every shape, or it proves nothing about them" |
| 1344 | ); |
| 1345 | } |