Merge branch 'simplify/u6' into simplify/w1b
Browse files at this commit21 changed files +307 -2593
- Cargo.lock +0 -1
- crates/ec-h264/Cargo.toml +0 -9
- crates/ec-h264/examples/bench_encode.rs +0 -36
- crates/ec-h264/examples/h264_clip_encode.rs +0 -107
- crates/ec-h264/src/cabac.rs +14 -210
- crates/ec-h264/src/decoder.rs +1 -101
- crates/ec-h264/src/enc/cabac_enc.rs +0 -38
- crates/ec-h264/src/enc/mb.rs +128 -189
- crates/ec-h264/src/enc/mod.rs +5 -242
- crates/ec-h264/src/enc/timing.rs +0 -81
- crates/ec-h264/src/lib.rs +3 -6
- crates/ec-h264/src/tables.rs +1 -4
- crates/ec-h264/tests/conformance.rs +18 -309
- crates/ec-h264/tests/it/common.rs +46 -25
- crates/ec-h264/tests/it/encode.rs +1 -918
- crates/ec-h264/tests/it/high10.rs +5 -64
- crates/ec-h264/tests/it/high422.rs +21 -48
- crates/ec-h264/tests/it/high444.rs +39 -43
- crates/ec-h264/tests/it/main.rs +0 -4
- crates/ec-h264/tests/it/mbaff_x264.rs +25 -73
- crates/ec-h264/tests/it/no_panic.rs +0 -85
Cargo.lockmodified+0 -1
| @@ -548,7 +548,6 @@ dependencies = [ | ||
| 548 | 548 | "ec-matroska", |
| 549 | 549 | "ec-mp4", |
| 550 | 550 | "ec-testkit", |
| 551 | - "tracking-allocator", | |
| 552 | 551 | "wide", |
| 553 | 552 | ] |
| 554 | 553 |
crates/ec-h264/Cargo.tomlmodified+0 -9
| @@ -6,12 +6,6 @@ edition.workspace = true | ||
| 6 | 6 | license.workspace = true |
| 7 | 7 | authors.workspace = true |
| 8 | 8 | |
| 9 | -[features] | |
| 10 | -# Internal-only RD experiment switches, compiled only by the measurement harness. | |
| 11 | -rd-ablation = [] | |
| 12 | -# Per-stage timing counters in the macroblock coder (measurement builds only). | |
| 13 | -enc-profile = [] | |
| 14 | - | |
| 15 | 9 | [dependencies] |
| 16 | 10 | ec-core = { workspace = true } |
| 17 | 11 | ec-h264-syntax = { workspace = true } |
| @@ -19,10 +13,7 @@ wide = { workspace = true } | ||
| 19 | 13 | |
| 20 | 14 | [dev-dependencies] |
| 21 | 15 | ec-testkit.workspace = true |
| 22 | -# The conformance harness walks Annex B itself to drive push_nal. | |
| 23 | -ec-h264-syntax = { workspace = true } | |
| 24 | 16 | # ... and demuxes an MP4 directly where ffmpeg's own Annex B extraction of it |
| 25 | 17 | # produces a stream ffmpeg then cannot decode. |
| 26 | 18 | ec-mp4 = { workspace = true } |
| 27 | 19 | ec-matroska = { workspace = true } |
| 28 | -tracking-allocator = "0.4.0" |
crates/ec-h264/examples/bench_encode.rsdeleted+0 -36
| @@ -1,36 +0,0 @@ | ||
| 1 | -//! Throwaway profiling harness for lane-h264perf: repeats the bench's own | |
| 2 | -//! 640x360x30-frame encode loop N times so a perf sample has enough hits to | |
| 3 | -//! be useful. Not wired into any product surface; delete before merge if | |
| 4 | -//! still present. | |
| 5 | -use ec_h264::{Encoder, EncoderConfig, PictureView}; | |
| 6 | -use std::time::Instant; | |
| 7 | - | |
| 8 | -fn main() { | |
| 9 | - let path = std::env::args().nth(1).expect("path to raw yuv420p"); | |
| 10 | - let reps: u32 = std::env::args() | |
| 11 | - .nth(2) | |
| 12 | - .and_then(|s| s.parse().ok()) | |
| 13 | - .unwrap_or(20); | |
| 14 | - let (w, h) = (640u32, 360u32); | |
| 15 | - let data = std::fs::read(&path).expect("read raw yuv"); | |
| 16 | - let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; | |
| 17 | - let n = data.len() / frame_len; | |
| 18 | - let start = Instant::now(); | |
| 19 | - for _ in 0..reps { | |
| 20 | - let mut cfg = EncoderConfig::new(w, h); | |
| 21 | - cfg.threads = 1; | |
| 22 | - let mut enc = Encoder::new(cfg).expect("h264 encoder"); | |
| 23 | - for frame in data.chunks_exact(frame_len).take(n) { | |
| 24 | - let (y, rest) = frame.split_at((w * h) as usize); | |
| 25 | - let (u, v) = rest.split_at(rest.len() / 2); | |
| 26 | - let view = PictureView::i420(w, h, y, u, v); | |
| 27 | - enc.encode(&view).expect("h264 encode"); | |
| 28 | - } | |
| 29 | - } | |
| 30 | - let wall = start.elapsed(); | |
| 31 | - eprintln!( | |
| 32 | - "{reps} reps x {n} frames in {:.3}s ({:.2} ms/rep)", | |
| 33 | - wall.as_secs_f64(), | |
| 34 | - wall.as_secs_f64() * 1000.0 / f64::from(reps) | |
| 35 | - ); | |
| 36 | -} |
crates/ec-h264/examples/h264_clip_encode.rsdeleted+0 -107
| @@ -1,107 +0,0 @@ | ||
| 1 | -//! Encode a raw I420 clip and write the bitstream and the encoder's own | |
| 2 | -//! reconstruction, for the ffmpeg recon-match and rate-control checks in | |
| 3 | -//! `scripts/h264-lane-check.sh`. Not a product surface. | |
| 4 | -//! | |
| 5 | -//! Usage: h264_clip_encode <in.yuv|-> <width> <height> <fps> <bitrate|0> <qp> <threads> <out-prefix|none> | |
| 6 | -//! | |
| 7 | -//! `-` reads raw I420 from stdin, so a 60 s 1080p clip never has to exist on | |
| 8 | -//! disk. Writes `<out-prefix>.h264` (Annex B), and `<out-prefix>.recon.yuv` | |
| 9 | -//! (every reconstructed picture, display order, I420 at the coded size) unless | |
| 10 | -//! the prefix is `none`. Prints frames, bytes and the wall time spent inside | |
| 11 | -//! `encode` on stdout. | |
| 12 | -use ec_h264::{Encoder, EncoderConfig, PictureView}; | |
| 13 | -use std::io::Write; | |
| 14 | -use std::time::Instant; | |
| 15 | - | |
| 16 | -fn main() { | |
| 17 | - let args: Vec<String> = std::env::args().collect(); | |
| 18 | - if args.len() != 9 { | |
| 19 | - eprintln!( | |
| 20 | - "usage: h264_clip_encode <in.yuv|-> <w> <h> <fps> <bitrate> <qp> <threads> <out-prefix|none>" | |
| 21 | - ); | |
| 22 | - std::process::exit(2); | |
| 23 | - } | |
| 24 | - let parse = |i: usize| -> f64 { args[i].parse().expect("numeric argument") }; | |
| 25 | - let (w, h) = (parse(2) as u32, parse(3) as u32); | |
| 26 | - let fps = parse(4) as f32; | |
| 27 | - let bitrate = parse(5) as u32; | |
| 28 | - let qp = parse(6) as i32; | |
| 29 | - let threads = parse(7) as usize; | |
| 30 | - let prefix = &args[8]; | |
| 31 | - | |
| 32 | - let (wu, hu) = (w as usize, h as usize); | |
| 33 | - let cw = wu.div_ceil(2); | |
| 34 | - let ch = hu.div_ceil(2); | |
| 35 | - let frame_len = wu * hu + 2 * cw * ch; | |
| 36 | - let mut input: Box<dyn std::io::Read> = if args[1] == "-" { | |
| 37 | - Box::new(std::io::stdin().lock()) | |
| 38 | - } else { | |
| 39 | - Box::new(std::fs::File::open(&args[1]).expect("open raw i420 input")) | |
| 40 | - }; | |
| 41 | - | |
| 42 | - let mut cfg = EncoderConfig::new(w, h); | |
| 43 | - cfg.framerate = fps; | |
| 44 | - cfg.bitrate = bitrate; | |
| 45 | - cfg.qp = qp; | |
| 46 | - cfg.threads = threads; | |
| 47 | - // H264_CAVLC=1 codes CAVLC instead of the default CABAC (identity checks). | |
| 48 | - cfg.cabac = std::env::var_os("H264_CAVLC").is_none(); | |
| 49 | - cfg.gop_size = (fps.round() as u32).max(1) * 2; | |
| 50 | - let mut enc = Encoder::new(cfg).expect("h264 encoder"); | |
| 51 | - | |
| 52 | - let mut stream_out = (prefix != "none") | |
| 53 | - .then(|| std::fs::File::create(format!("{prefix}.h264")).expect("create bitstream")); | |
| 54 | - let mut recon_out = (prefix != "none") | |
| 55 | - .then(|| std::fs::File::create(format!("{prefix}.recon.yuv")).expect("create recon")); | |
| 56 | - // H264_TRACE=1 prints one line per picture: its QP and size. | |
| 57 | - let trace = std::env::var_os("H264_TRACE").is_some(); | |
| 58 | - let mut frame = vec![0u8; frame_len]; | |
| 59 | - let mut frames = 0usize; | |
| 60 | - let mut bytes = 0usize; | |
| 61 | - let mut spent = std::time::Duration::ZERO; | |
| 62 | - while input.read_exact(&mut frame).is_ok() { | |
| 63 | - let (y, rest) = frame.split_at(wu * hu); | |
| 64 | - let (u, v) = rest.split_at(cw * ch); | |
| 65 | - let view = PictureView::i420(w, h, y, u, v); | |
| 66 | - let t0 = Instant::now(); | |
| 67 | - let pic = enc.encode(&view).expect("h264 encode"); | |
| 68 | - spent += t0.elapsed(); | |
| 69 | - if trace { | |
| 70 | - println!( | |
| 71 | - "trace {frames} key {} qp {} bytes {}", | |
| 72 | - u8::from(pic.key_frame), | |
| 73 | - pic.qp, | |
| 74 | - pic.au.len() | |
| 75 | - ); | |
| 76 | - } | |
| 77 | - frames += 1; | |
| 78 | - bytes += pic.au.len(); | |
| 79 | - if let Some(out) = stream_out.as_mut() { | |
| 80 | - out.write_all(&pic.au).expect("write bitstream"); | |
| 81 | - } | |
| 82 | - if let Some(out) = recon_out.as_mut() { | |
| 83 | - let (ry, ru, rv) = enc.reconstruction().expect("a reconstruction"); | |
| 84 | - out.write_all(&ry) | |
| 85 | - .and_then(|_| out.write_all(&ru)) | |
| 86 | - .and_then(|_| out.write_all(&rv)) | |
| 87 | - .expect("write reconstruction"); | |
| 88 | - } | |
| 89 | - } | |
| 90 | - println!( | |
| 91 | - "frames {frames} bytes {bytes} encode_secs {:.3} fps {:.2}", | |
| 92 | - spent.as_secs_f64(), | |
| 93 | - frames as f64 / spent.as_secs_f64() | |
| 94 | - ); | |
| 95 | - let t = enc.timings(); | |
| 96 | - println!( | |
| 97 | - "stages pad {:.3} bands_wall {:.3} bands_busy {:.3} bands_slowest {:.3} stitch {:.3} deblock {:.3} output {:.3}", | |
| 98 | - t.pad, t.bands_wall, t.bands_busy, t.bands_slowest, t.stitch, t.deblock, t.output | |
| 99 | - ); | |
| 100 | - #[cfg(feature = "enc-profile")] | |
| 101 | - { | |
| 102 | - let snap = ec_h264::mb_stages::snapshot(); | |
| 103 | - for (name, ns) in ec_h264::mb_stages::NAMES.iter().zip(snap) { | |
| 104 | - println!("mb_stage {name} {:.3}", ns as f64 / 1e9); | |
| 105 | - } | |
| 106 | - } | |
| 107 | -} |
crates/ec-h264/src/cabac.rsmodified+14 -210
| @@ -107,49 +107,6 @@ pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; | ||
| 107 | 107 | pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; |
| 108 | 108 | const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; |
| 109 | 109 | |
| 110 | -/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The | |
| 111 | -/// arithmetic decoder spends fractional bits per element, so the sub-bit | |
| 112 | -/// resolution is the point: a class is charged the movement of | |
| 113 | -/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our | |
| 114 | -/// streams and any other encoder's are parsed by this decoder, which is what | |
| 115 | -/// makes the two accounts comparable. | |
| 116 | -#[derive(Clone, Copy, Default, Debug)] | |
| 117 | -pub struct BitAccount { | |
| 118 | - pub skip: u64, | |
| 119 | - pub mb_type: u64, | |
| 120 | - pub mv: u64, | |
| 121 | - pub ref_idx: u64, | |
| 122 | - pub cbp_qp: u64, | |
| 123 | - pub intra_mode: u64, | |
| 124 | - pub residual_luma: u64, | |
| 125 | - pub residual_chroma: u64, | |
| 126 | -} | |
| 127 | - | |
| 128 | -impl BitAccount { | |
| 129 | - /// Every class summed, in 1/256ths of a bit. | |
| 130 | - pub fn total(&self) -> u64 { | |
| 131 | - self.skip | |
| 132 | - + self.mb_type | |
| 133 | - + self.mv | |
| 134 | - + self.ref_idx | |
| 135 | - + self.cbp_qp | |
| 136 | - + self.intra_mode | |
| 137 | - + self.residual_luma | |
| 138 | - + self.residual_chroma | |
| 139 | - } | |
| 140 | - | |
| 141 | - pub(crate) fn add(&mut self, other: &BitAccount) { | |
| 142 | - self.skip += other.skip; | |
| 143 | - self.mb_type += other.mb_type; | |
| 144 | - self.mv += other.mv; | |
| 145 | - self.ref_idx += other.ref_idx; | |
| 146 | - self.cbp_qp += other.cbp_qp; | |
| 147 | - self.intra_mode += other.intra_mode; | |
| 148 | - self.residual_luma += other.residual_luma; | |
| 149 | - self.residual_chroma += other.residual_chroma; | |
| 150 | - } | |
| 151 | -} | |
| 152 | - | |
| 153 | 110 | pub(crate) struct Cabac<'a> { |
| 154 | 111 | r: BitCursor<'a>, |
| 155 | 112 | /// codIRange (9.3.3.2). |
| @@ -166,8 +123,6 @@ pub(crate) struct Cabac<'a> { | ||
| 166 | 123 | /// The macroblock being parsed is intra coded, which flips the |
| 167 | 124 | /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9). |
| 168 | 125 | cur_intra: bool, |
| 169 | - /// Bits spent so far, by syntax class. | |
| 170 | - account: BitAccount, | |
| 171 | 126 | } |
| 172 | 127 | |
| 173 | 128 | impl<'a> Cabac<'a> { |
| @@ -195,7 +150,6 @@ impl<'a> Cabac<'a> { | ||
| 195 | 150 | ctx: MbCtx::default(), |
| 196 | 151 | cbp_luma_bins: 0, |
| 197 | 152 | cur_intra: true, |
| 198 | - account: BitAccount::default(), | |
| 199 | 153 | }; |
| 200 | 154 | c.state = init_contexts_full(slice_qp, init_column.min(3)); |
| 201 | 155 | c.init_engine()?; |
| @@ -293,128 +247,6 @@ impl<'a> Cabac<'a> { | ||
| 293 | 247 | |
| 294 | 248 | /// Declare whether the macroblock being parsed is intra coded |
| 295 | 249 | /// (9.3.3.1.1.9 reads it for every coded_block_flag). |
| 296 | - /// The decoder's position in 1/256ths of a bit: the bits already read plus | |
| 297 | - /// what the arithmetic engine's interval says it is holding. | |
| 298 | - fn mark(&self) -> u64 { | |
| 299 | - self.r.bit_position() * 256 + u64::from(self.range.leading_zeros()) | |
| 300 | - } | |
| 301 | - | |
| 302 | - pub(crate) fn account(&self) -> BitAccount { | |
| 303 | - self.account | |
| 304 | - } | |
| 305 | - | |
| 306 | - pub(crate) fn mb_type_i(&mut self) -> Result<u32> { | |
| 307 | - let m = self.mark(); | |
| 308 | - let out = self.mb_type_i_inner(); | |
| 309 | - self.account.mb_type += self.mark() - m; | |
| 310 | - out | |
| 311 | - } | |
| 312 | - | |
| 313 | - pub(crate) fn mb_type_p(&mut self) -> Result<u32> { | |
| 314 | - let m = self.mark(); | |
| 315 | - let out = self.mb_type_p_inner(); | |
| 316 | - self.account.mb_type += self.mark() - m; | |
| 317 | - out | |
| 318 | - } | |
| 319 | - | |
| 320 | - pub(crate) fn mb_type_b(&mut self) -> Result<u32> { | |
| 321 | - let m = self.mark(); | |
| 322 | - let out = self.mb_type_b_inner(); | |
| 323 | - self.account.mb_type += self.mark() - m; | |
| 324 | - out | |
| 325 | - } | |
| 326 | - | |
| 327 | - pub(crate) fn sub_mb_type_p(&mut self) -> u32 { | |
| 328 | - let m = self.mark(); | |
| 329 | - let out = self.sub_mb_type_p_inner(); | |
| 330 | - self.account.mb_type += self.mark() - m; | |
| 331 | - out | |
| 332 | - } | |
| 333 | - | |
| 334 | - pub(crate) fn sub_mb_type_b(&mut self) -> u32 { | |
| 335 | - let m = self.mark(); | |
| 336 | - let out = self.sub_mb_type_b_inner(); | |
| 337 | - self.account.mb_type += self.mark() - m; | |
| 338 | - out | |
| 339 | - } | |
| 340 | - | |
| 341 | - pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { | |
| 342 | - let m = self.mark(); | |
| 343 | - let out = self.mb_skip_flag_inner(b_slice, inc); | |
| 344 | - self.account.skip += self.mark() - m; | |
| 345 | - out | |
| 346 | - } | |
| 347 | - | |
| 348 | - pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> { | |
| 349 | - let m = self.mark(); | |
| 350 | - let out = self.ref_idx_inner(inc); | |
| 351 | - self.account.ref_idx += self.mark() - m; | |
| 352 | - out | |
| 353 | - } | |
| 354 | - | |
| 355 | - pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> { | |
| 356 | - let m = self.mark(); | |
| 357 | - let out = self.mvd_inner(comp, inc); | |
| 358 | - self.account.mv += self.mark() - m; | |
| 359 | - out | |
| 360 | - } | |
| 361 | - | |
| 362 | - pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> { | |
| 363 | - let m = self.mark(); | |
| 364 | - let out = self.transform_size_8x8_flag_inner(); | |
| 365 | - self.account.cbp_qp += self.mark() - m; | |
| 366 | - out | |
| 367 | - } | |
| 368 | - | |
| 369 | - pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> { | |
| 370 | - let m = self.mark(); | |
| 371 | - let out = self.coded_block_pattern_inner(has_chroma); | |
| 372 | - self.account.cbp_qp += self.mark() - m; | |
| 373 | - out | |
| 374 | - } | |
| 375 | - | |
| 376 | - pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> { | |
| 377 | - let m = self.mark(); | |
| 378 | - let out = self.mb_qp_delta_inner(); | |
| 379 | - self.account.cbp_qp += self.mark() - m; | |
| 380 | - out | |
| 381 | - } | |
| 382 | - | |
| 383 | - pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> { | |
| 384 | - let m = self.mark(); | |
| 385 | - let out = self.intra4x4_pred_mode_inner(); | |
| 386 | - self.account.intra_mode += self.mark() - m; | |
| 387 | - out | |
| 388 | - } | |
| 389 | - | |
| 390 | - pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> { | |
| 391 | - let m = self.mark(); | |
| 392 | - let out = self.intra_chroma_pred_mode_inner(); | |
| 393 | - self.account.intra_mode += self.mark() - m; | |
| 394 | - out | |
| 395 | - } | |
| 396 | - | |
| 397 | - pub(crate) fn residual_block( | |
| 398 | - &mut self, | |
| 399 | - coeff: &mut [i32; 16], | |
| 400 | - cat: BlockCat, | |
| 401 | - comp: u8, | |
| 402 | - na: Option<u8>, | |
| 403 | - nb: Option<u8>, | |
| 404 | - ) -> Result<u8> { | |
| 405 | - let m = self.mark(); | |
| 406 | - let out = self.residual_block_inner(coeff, cat, comp, na, nb); | |
| 407 | - let spent = self.mark() - m; | |
| 408 | - match cat { | |
| 409 | - BlockCat::ChromaDc(_) | BlockCat::ChromaDc422(_) | BlockCat::ChromaAc => { | |
| 410 | - self.account.residual_chroma += spent | |
| 411 | - } | |
| 412 | - _ if comp != 0 => self.account.residual_chroma += spent, | |
| 413 | - _ => self.account.residual_luma += spent, | |
| 414 | - } | |
| 415 | - out | |
| 416 | - } | |
| 417 | - | |
| 418 | 250 | pub(crate) fn set_intra(&mut self, intra: bool) { |
| 419 | 251 | self.cur_intra = intra; |
| 420 | 252 | } |
| @@ -432,7 +264,7 @@ impl<'a> Cabac<'a> { | ||
| 432 | 264 | } |
| 433 | 265 | |
| 434 | 266 | /// mb_type of an I slice (Table 9-36). |
| 435 | - fn mb_type_i_inner(&mut self) -> Result<u32> { | |
| 267 | + pub(crate) fn mb_type_i(&mut self) -> Result<u32> { | |
| 436 | 268 | let mut ctx = I_MB_TYPE_CTX; |
| 437 | 269 | ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE); |
| 438 | 270 | self.mb_type_intra(&ctx) |
| @@ -461,14 +293,14 @@ impl<'a> Cabac<'a> { | ||
| 461 | 293 | } |
| 462 | 294 | |
| 463 | 295 | /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. |
| 464 | - fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool { | |
| 296 | + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { | |
| 465 | 297 | let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P }; |
| 466 | 298 | self.decision(off + inc) |
| 467 | 299 | } |
| 468 | 300 | |
| 469 | 301 | /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice |
| 470 | 302 | /// mb_type for an intra macroblock. |
| 471 | - fn mb_type_p_inner(&mut self) -> Result<u32> { | |
| 303 | + pub(crate) fn mb_type_p(&mut self) -> Result<u32> { | |
| 472 | 304 | if self.decision(OFF_MB_TYPE_P) { |
| 473 | 305 | return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); |
| 474 | 306 | } |
| @@ -485,7 +317,7 @@ impl<'a> Cabac<'a> { | ||
| 485 | 317 | |
| 486 | 318 | /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice |
| 487 | 319 | /// mb_type for an intra macroblock. |
| 488 | - fn mb_type_b_inner(&mut self) -> Result<u32> { | |
| 320 | + pub(crate) fn mb_type_b(&mut self) -> Result<u32> { | |
| 489 | 321 | if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { |
| 490 | 322 | return Ok(0); // B_Direct_16x16 |
| 491 | 323 | } |
| @@ -523,7 +355,7 @@ impl<'a> Cabac<'a> { | ||
| 523 | 355 | } |
| 524 | 356 | |
| 525 | 357 | /// sub_mb_type of a P macroblock (Table 9-38). |
| 526 | - fn sub_mb_type_p_inner(&mut self) -> u32 { | |
| 358 | + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { | |
| 527 | 359 | if self.decision(OFF_SUB_TYPE_P) { |
| 528 | 360 | return 0; |
| 529 | 361 | } |
| @@ -538,7 +370,7 @@ impl<'a> Cabac<'a> { | ||
| 538 | 370 | } |
| 539 | 371 | |
| 540 | 372 | /// sub_mb_type of a B macroblock (Table 9-38). |
| 541 | - fn sub_mb_type_b_inner(&mut self) -> u32 { | |
| 373 | + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { | |
| 542 | 374 | if !self.decision(OFF_SUB_TYPE_B) { |
| 543 | 375 | return 0; // B_Direct_8x8 |
| 544 | 376 | } |
| @@ -559,7 +391,7 @@ impl<'a> Cabac<'a> { | ||
| 559 | 391 | |
| 560 | 392 | /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the |
| 561 | 393 | /// first bin (Table 9-39 row 54). |
| 562 | - fn ref_idx_inner(&mut self, inc: usize) -> Result<u32> { | |
| 394 | + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> { | |
| 563 | 395 | if !self.decision(OFF_REF_IDX + inc) { |
| 564 | 396 | return Ok(0); |
| 565 | 397 | } |
| @@ -578,7 +410,7 @@ impl<'a> Cabac<'a> { | ||
| 578 | 410 | |
| 579 | 411 | /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with |
| 580 | 412 | /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7. |
| 581 | - fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result<i32> { | |
| 413 | + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> { | |
| 582 | 414 | let off = OFF_MVD[comp]; |
| 583 | 415 | if !self.decision(off + inc) { |
| 584 | 416 | return Ok(0); |
| @@ -603,7 +435,7 @@ impl<'a> Cabac<'a> { | ||
| 603 | 435 | |
| 604 | 436 | /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is |
| 605 | 437 | /// available and carried the flag itself. |
| 606 | - fn transform_size_8x8_flag_inner(&mut self) -> Result<bool> { | |
| 438 | + pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> { | |
| 607 | 439 | let cond = |n: Option<MbInfo>| match n { |
| 608 | 440 | None => 0, |
| 609 | 441 | Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), |
| @@ -614,7 +446,7 @@ impl<'a> Cabac<'a> { | ||
| 614 | 446 | |
| 615 | 447 | /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7 |
| 616 | 448 | /// with binIdx 0 the least significant bit. |
| 617 | - fn intra4x4_pred_mode_inner(&mut self) -> Result<Option<u8>> { | |
| 449 | + pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> { | |
| 618 | 450 | if self.decision(OFF_PREV_I4) { |
| 619 | 451 | return Ok(None); |
| 620 | 452 | } |
| @@ -626,7 +458,7 @@ impl<'a> Cabac<'a> { | ||
| 626 | 458 | } |
| 627 | 459 | |
| 628 | 460 | /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8. |
| 629 | - fn intra_chroma_pred_mode_inner(&mut self) -> Result<u8> { | |
| 461 | + pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> { | |
| 630 | 462 | let cond = |n: Option<MbInfo>| match n { |
| 631 | 463 | None => 0, |
| 632 | 464 | Some(i) => usize::from( |
| @@ -649,7 +481,7 @@ impl<'a> Cabac<'a> { | ||
| 649 | 481 | |
| 650 | 482 | /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma |
| 651 | 483 | /// suffix, both with the neighbour contexts of 9.3.3.1.1.4. |
| 652 | - fn coded_block_pattern_inner(&mut self, has_chroma: bool) -> Result<(u8, u8)> { | |
| 484 | + pub(crate) fn coded_block_pattern(&mut self, has_chroma: bool) -> Result<(u8, u8)> { | |
| 653 | 485 | let (a_lower, a_blk) = match self.ctx.mbaff_a { |
| 654 | 486 | None => (self.ctx.a, [1u8, 3]), |
| 655 | 487 | Some(m) => (m.lower, m.blk), |
| @@ -717,7 +549,7 @@ impl<'a> Cabac<'a> { | ||
| 717 | 549 | } |
| 718 | 550 | |
| 719 | 551 | /// mb_qp_delta: unary bin string of the Table 9-3 mapped value. |
| 720 | - fn mb_qp_delta_inner(&mut self) -> Result<i32> { | |
| 552 | + pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> { | |
| 721 | 553 | let mut k = 0i32; |
| 722 | 554 | while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) { |
| 723 | 555 | k += 1; |
| @@ -729,7 +561,7 @@ impl<'a> Cabac<'a> { | ||
| 729 | 561 | } |
| 730 | 562 | |
| 731 | 563 | /// residual_block_cabac (7.3.5.3.3) for one block, in scan order. |
| 732 | - fn residual_block_inner( | |
| 564 | + pub(crate) fn residual_block( | |
| 733 | 565 | &mut self, |
| 734 | 566 | coeff: &mut [i32; 16], |
| 735 | 567 | cat: BlockCat, |
| @@ -827,22 +659,6 @@ impl<'a> Cabac<'a> { | ||
| 827 | 659 | coeff: &mut [i32; 64], |
| 828 | 660 | comp: u8, |
| 829 | 661 | cbf: Option<(Option<u8>, Option<u8>)>, |
| 830 | - ) -> Result<u8> { | |
| 831 | - let m = self.mark(); | |
| 832 | - let out = self.residual_block_8x8_inner(coeff, comp, cbf); | |
| 833 | - if comp == 0 { | |
| 834 | - self.account.residual_luma += self.mark() - m; | |
| 835 | - } else { | |
| 836 | - self.account.residual_chroma += self.mark() - m; | |
| 837 | - } | |
| 838 | - out | |
| 839 | - } | |
| 840 | - | |
| 841 | - fn residual_block_8x8_inner( | |
| 842 | - &mut self, | |
| 843 | - coeff: &mut [i32; 64], | |
| 844 | - comp: u8, | |
| 845 | - cbf: Option<(Option<u8>, Option<u8>)>, | |
| 846 | 662 | ) -> Result<u8> { |
| 847 | 663 | *coeff = [0; 64]; |
| 848 | 664 | if let Some((na, nb)) = cbf { |
| @@ -989,18 +805,6 @@ impl<'a> Cabac<'a> { | ||
| 989 | 805 | Ok(bytes) |
| 990 | 806 | } |
| 991 | 807 | |
| 992 | - /// The raw engine, for the encoder's round-trip test. | |
| 993 | - #[cfg(test)] | |
| 994 | - pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool { | |
| 995 | - self.decision(ctx_idx) | |
| 996 | - } | |
| 997 | - | |
| 998 | - /// The raw bypass engine, for the encoder's round-trip test. | |
| 999 | - #[cfg(test)] | |
| 1000 | - pub(crate) fn bypass_for_test(&mut self) -> bool { | |
| 1001 | - self.bypass() | |
| 1002 | - } | |
| 1003 | - | |
| 1004 | 808 | /// end_of_slice_flag (ctxIdx 276, DecodeTerminate). |
| 1005 | 809 | pub(crate) fn more_macroblocks(&mut self) -> Result<bool> { |
| 1006 | 810 | debug_assert_eq!(CTX_TERMINATE, 276); |
crates/ec-h264/src/decoder.rsmodified+1 -101
| @@ -29,7 +29,6 @@ use ec_h264_syntax::{ | ||
| 29 | 29 | SliceType, Sps, WeightEntry, unescape_rbsp, |
| 30 | 30 | }; |
| 31 | 31 | |
| 32 | -use crate::cabac::BitAccount; | |
| 33 | 32 | use crate::deblock::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line}; |
| 34 | 33 | use crate::dpb::{ |
| 35 | 34 | BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE, |
| @@ -141,9 +140,6 @@ pub(crate) struct Core<S: Sample> { | ||
| 141 | 140 | last_decoded: i32, |
| 142 | 141 | output_order: OutputOrder, |
| 143 | 142 | out: VecDeque<VideoFrame>, |
| 144 | - /// Bits parsed so far, by syntax class (CABAC slices only). | |
| 145 | - account: BitAccount, | |
| 146 | - shapes: MbShapes, | |
| 147 | 143 | /// Presentation timestamp to attach to the next picture started. |
| 148 | 144 | pending_pts: Option<Timestamp>, |
| 149 | 145 | /// `PicOrderCnt` of the random-access point most recently established by |
| @@ -278,25 +274,6 @@ impl Decoder { | ||
| 278 | 274 | }) |
| 279 | 275 | } |
| 280 | 276 | |
| 281 | - /// Where the bits of every CABAC slice parsed so far went, by syntax | |
| 282 | - /// class, in 1/256ths of a bit. | |
| 283 | - pub fn bit_account(&self) -> BitAccount { | |
| 284 | - if self.hbd { | |
| 285 | - self.c16.bit_account() | |
| 286 | - } else { | |
| 287 | - self.c8.bit_account() | |
| 288 | - } | |
| 289 | - } | |
| 290 | - | |
| 291 | - /// How many macroblocks of each shape this decoder has read. | |
| 292 | - pub fn mb_shapes(&self) -> MbShapes { | |
| 293 | - if self.hbd { | |
| 294 | - self.c16.mb_shapes() | |
| 295 | - } else { | |
| 296 | - self.c8.mb_shapes() | |
| 297 | - } | |
| 298 | - } | |
| 299 | - | |
| 300 | 277 | /// Decode the first IDR picture of an Annex B stream and return it. |
| 301 | 278 | pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> { |
| 302 | 279 | let mut got_slice = false; |
| @@ -612,8 +589,6 @@ impl<S: Sample> Core<S> { | ||
| 612 | 589 | last_decoded: -1, |
| 613 | 590 | output_order: OutputOrder::default(), |
| 614 | 591 | out: VecDeque::new(), |
| 615 | - account: BitAccount::default(), | |
| 616 | - shapes: MbShapes::default(), | |
| 617 | 592 | pending_pts: None, |
| 618 | 593 | recovery_poc: None, |
| 619 | 594 | cur_ref_padded: false, |
| @@ -645,20 +620,6 @@ impl<S: Sample> Core<S> { | ||
| 645 | 620 | Some((sps.width, sps.height)) |
| 646 | 621 | } |
| 647 | 622 | |
| 648 | - /// Where the bits of every CABAC slice parsed so far went, by syntax | |
| 649 | - /// class, in 1/256ths of a bit. Any conforming stream can be measured | |
| 650 | - /// this way, so an encoder's spending can be compared with another's | |
| 651 | - /// through one account. | |
| 652 | - pub(crate) fn bit_account(&self) -> BitAccount { | |
| 653 | - self.account | |
| 654 | - } | |
| 655 | - | |
| 656 | - /// How many macroblocks of each shape this decoder has read, which is what | |
| 657 | - /// a stream's partitioning looks like from the outside. | |
| 658 | - pub(crate) fn mb_shapes(&self) -> MbShapes { | |
| 659 | - self.shapes | |
| 660 | - } | |
| 661 | - | |
| 662 | 623 | /// Feed one NAL unit (header byte first, no start code). |
| 663 | 624 | pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> { |
| 664 | 625 | let Some((&header_byte, payload)) = nal.split_first() else { |
| @@ -1030,7 +991,6 @@ impl<S: Sample> Core<S> { | ||
| 1030 | 991 | }; |
| 1031 | 992 | |
| 1032 | 993 | let mut ctx = SliceCtx { |
| 1033 | - shapes: MbShapes::default(), | |
| 1034 | 994 | slice_id, |
| 1035 | 995 | slice_type: sh.slice_type, |
| 1036 | 996 | qp: sh.slice_qp, |
| @@ -1071,10 +1031,6 @@ impl<S: Sample> Core<S> { | ||
| 1071 | 1031 | first_mb as usize * 2, |
| 1072 | 1032 | pps.entropy_coding_mode, |
| 1073 | 1033 | )?; |
| 1074 | - self.shapes.add(&ctx.shapes); | |
| 1075 | - if let Entropy::Cabac(c) = &r { | |
| 1076 | - self.account.add(&c.account()); | |
| 1077 | - } | |
| 1078 | 1034 | return Ok(NalOutcome::SliceDecoded); |
| 1079 | 1035 | } |
| 1080 | 1036 | let groups = if pps.num_slice_groups > 1 { |
| @@ -1154,10 +1110,6 @@ impl<S: Sample> Core<S> { | ||
| 1154 | 1110 | more = r.more_macroblocks()?; |
| 1155 | 1111 | mb_addr = step(mb_addr); |
| 1156 | 1112 | } |
| 1157 | - self.shapes.add(&ctx.shapes); | |
| 1158 | - if let Entropy::Cabac(c) = &r { | |
| 1159 | - self.account.add(&c.account()); | |
| 1160 | - } | |
| 1161 | 1113 | Ok(NalOutcome::SliceDecoded) |
| 1162 | 1114 | } |
| 1163 | 1115 | |
| @@ -1606,40 +1558,6 @@ fn check_supported<S: Sample>( | ||
| 1606 | 1558 | Ok(()) |
| 1607 | 1559 | } |
| 1608 | 1560 | |
| 1609 | -/// Mutable per-slice decode state. | |
| 1610 | -/// How many macroblocks of each shape a stream codes: the partitioning the | |
| 1611 | -/// encoder chose, counted from the outside. | |
| 1612 | -/// | |
| 1613 | -/// P macroblocks only; a B macroblock's own shapes are not split out. | |
| 1614 | -#[derive(Debug, Default, Clone, Copy)] | |
| 1615 | -pub struct MbShapes { | |
| 1616 | - pub skip: u64, | |
| 1617 | - pub p16x16: u64, | |
| 1618 | - pub p16x8: u64, | |
| 1619 | - pub p8x16: u64, | |
| 1620 | - /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are. | |
| 1621 | - pub p8x8: u64, | |
| 1622 | - pub bidir: u64, | |
| 1623 | - pub intra: u64, | |
| 1624 | -} | |
| 1625 | - | |
| 1626 | -impl MbShapes { | |
| 1627 | - /// Add another count into this one. | |
| 1628 | - pub fn add_public(&mut self, o: &MbShapes) { | |
| 1629 | - self.add(o); | |
| 1630 | - } | |
| 1631 | - | |
| 1632 | - pub(crate) fn add(&mut self, o: &MbShapes) { | |
| 1633 | - self.skip += o.skip; | |
| 1634 | - self.p16x16 += o.p16x16; | |
| 1635 | - self.p16x8 += o.p16x8; | |
| 1636 | - self.p8x16 += o.p8x16; | |
| 1637 | - self.p8x8 += o.p8x8; | |
| 1638 | - self.bidir += o.bidir; | |
| 1639 | - self.intra += o.intra; | |
| 1640 | - } | |
| 1641 | -} | |
| 1642 | - | |
| 1643 | 1561 | /// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value. |
| 1644 | 1562 | #[derive(Clone, Copy)] |
| 1645 | 1563 | struct Geo { |
| @@ -1663,6 +1581,7 @@ impl Geo { | ||
| 1663 | 1581 | } |
| 1664 | 1582 | } |
| 1665 | 1583 | |
| 1584 | +/// Mutable per-slice decode state. | |
| 1666 | 1585 | pub(crate) struct SliceCtx { |
| 1667 | 1586 | slice_id: u16, |
| 1668 | 1587 | slice_type: SliceType, |
| @@ -1699,8 +1618,6 @@ pub(crate) struct SliceCtx { | ||
| 1699 | 1618 | /// Where the macroblock being decoded sits when the picture is an MBAFF |
| 1700 | 1619 | /// frame (`pos.active`); inert otherwise. |
| 1701 | 1620 | pos: MbPos, |
| 1702 | - /// How many macroblocks of each shape this slice decoded. | |
| 1703 | - shapes: MbShapes, | |
| 1704 | 1621 | } |
| 1705 | 1622 | |
| 1706 | 1623 | impl SliceCtx { |
| @@ -2241,22 +2158,6 @@ fn decode_macroblock<S: Sample>( | ||
| 2241 | 2158 | r.mb_type_i()? |
| 2242 | 2159 | }; |
| 2243 | 2160 | |
| 2244 | - if skipped { | |
| 2245 | - ctx.shapes.skip += 1; | |
| 2246 | - } else if ctx.slice_type == SliceType::P { | |
| 2247 | - match mb_type { | |
| 2248 | - 0 => ctx.shapes.p16x16 += 1, | |
| 2249 | - 1 => ctx.shapes.p16x8 += 1, | |
| 2250 | - 2 => ctx.shapes.p8x16 += 1, | |
| 2251 | - 3 | 4 => ctx.shapes.p8x8 += 1, | |
| 2252 | - _ => ctx.shapes.intra += 1, | |
| 2253 | - } | |
| 2254 | - } else if ctx.is_b() { | |
| 2255 | - ctx.shapes.bidir += 1; | |
| 2256 | - } else { | |
| 2257 | - ctx.shapes.intra += 1; | |
| 2258 | - } | |
| 2259 | - | |
| 2260 | 2161 | // Split the P/B numbering into an inter shape or an intra mb_type. |
| 2261 | 2162 | let (shape, intra_type) = if skipped { |
| 2262 | 2163 | let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] }; |
| @@ -5006,7 +4907,6 @@ mod tests { | ||
| 5006 | 4907 | }), |
| 5007 | 4908 | poc: 4, |
| 5008 | 4909 | fpoc: [4, 4], |
| 5009 | - shapes: MbShapes::default(), | |
| 5010 | 4910 | }; |
| 5011 | 4911 | let mut pic = ramp_picture(|_, _| 0); |
| 5012 | 4912 |
crates/ec-h264/src/enc/cabac_enc.rsmodified+0 -38
| @@ -730,44 +730,6 @@ mod tests { | ||
| 730 | 730 | use super::*; |
| 731 | 731 | use crate::cabac::Cabac; |
| 732 | 732 | |
| 733 | - /// The engine round-trips: a pseudo-random bin string written against a | |
| 734 | - /// spread of contexts, with bypass and terminate bins mixed in, decodes | |
| 735 | - /// back identically. This is the property every syntax element rests on. | |
| 736 | - #[test] | |
| 737 | - fn engine_round_trips() { | |
| 738 | - let mut state = 0x2545_F491u32; | |
| 739 | - let mut rand = move |m: u32| { | |
| 740 | - state ^= state << 13; | |
| 741 | - state ^= state >> 17; | |
| 742 | - state ^= state << 5; | |
| 743 | - state % m | |
| 744 | - }; | |
| 745 | - let mut plan: Vec<(usize, bool, u8)> = Vec::new(); // (ctx, bin, kind) | |
| 746 | - for _ in 0..4000 { | |
| 747 | - let kind = if rand(10) == 0 { 1 } else { 0 }; | |
| 748 | - plan.push((rand(NUM_CTX as u32) as usize, rand(2) == 1, kind)); | |
| 749 | - } | |
| 750 | - let mut enc = CabacEnc::new(BitWriter::new(), 26, 0); | |
| 751 | - for &(ctx, bin, kind) in &plan { | |
| 752 | - match kind { | |
| 753 | - 0 => enc.decision(ctx, bin), | |
| 754 | - _ => enc.bypass(bin), | |
| 755 | - } | |
| 756 | - enc.not_end_of_slice(); | |
| 757 | - } | |
| 758 | - let bytes = enc.finish().into_bytes(); | |
| 759 | - | |
| 760 | - let mut dec = Cabac::new(&bytes, 0, 26, 0).expect("decoder starts"); | |
| 761 | - for (i, &(ctx, bin, kind)) in plan.iter().enumerate() { | |
| 762 | - let got = match kind { | |
| 763 | - 0 => dec.decision_for_test(ctx), | |
| 764 | - _ => dec.bypass_for_test(), | |
| 765 | - }; | |
| 766 | - assert_eq!(got, bin, "bin {i}"); | |
| 767 | - assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); | |
| 768 | - } | |
| 769 | - } | |
| 770 | - | |
| 771 | 733 | /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat |
| 772 | 734 | /// 5 blocks over a spread of densities and magnitudes all decode back |
| 773 | 735 | /// through the decoder's own syntax readers. |
crates/ec-h264/src/enc/mb.rsmodified+128 -189
| @@ -41,7 +41,7 @@ use super::quant::{ | ||
| 41 | 41 | forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, |
| 42 | 42 | quant_4x4_offset, quant_8x8, quant_8x8_offset, quant_chroma_dc, quant_luma_dc, |
| 43 | 43 | }; |
| 44 | -use super::timing::mb_timed; | |
| 44 | + | |
| 45 | 45 | use super::{ |
| 46 | 46 | entropy::{EncEntropy, sub_block_4x4}, |
| 47 | 47 | lambda_ssd, |
| @@ -128,24 +128,12 @@ pub(crate) struct MbEnc<'a> { | ||
| 128 | 128 | /// Lagrangian multiplier; it is in the squared-error domain when 8x8 |
| 129 | 129 | /// transform decisions are enabled. |
| 130 | 130 | pub lambda: f64, |
| 131 | - /// Whether `lambda` is the standard squared-error multiplier. | |
| 132 | - pub lambda_standard: bool, | |
| 133 | - /// Extra rate saving an 8x8 trial must buy before it may replace 4x4. | |
| 134 | - pub t8x8_margin_bits: f64, | |
| 135 | 131 | pub preset: Preset, |
| 136 | 132 | /// Fast-preset speed knobs (see [`FastKnobs`]). |
| 137 | 133 | pub fast: FastKnobs, |
| 138 | 134 | /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must |
| 139 | 135 | /// be written for every eligible macroblock (7.3.5). |
| 140 | 136 | pub transform_8x8: bool, |
| 141 | - /// Whether intra macroblocks may select 8x8. The PPS can remain enabled | |
| 142 | - /// while an ablation measures the classes independently. | |
| 143 | - pub transform_8x8_intra: bool, | |
| 144 | - /// Whether inter macroblocks may select 8x8. | |
| 145 | - pub transform_8x8_inter: bool, | |
| 146 | - /// Whether the ablation restricts 8x8 eligibility to even macroblock | |
| 147 | - /// rows; odd rows then code exactly as they would with 8x8 disabled. | |
| 148 | - pub transform_8x8_roweven: bool, | |
| 149 | 137 | pub ls: LevelScale4x4, |
| 150 | 138 | pub ls8: LevelScale8x8, |
| 151 | 139 | /// Neighbourhood of the macroblock being written (CABAC). |
| @@ -160,18 +148,6 @@ pub(crate) struct MbEnc<'a> { | ||
| 160 | 148 | pub qp_delta_inc: u8, |
| 161 | 149 | } |
| 162 | 150 | |
| 163 | -impl MbEnc<'_> { | |
| 164 | - /// Intra 8x8 eligibility of macroblock row `mb_y`. | |
| 165 | - fn t8x8_intra(&self, mb_y: usize) -> bool { | |
| 166 | - self.transform_8x8_intra && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven) | |
| 167 | - } | |
| 168 | - | |
| 169 | - /// Inter 8x8 eligibility of macroblock row `mb_y`. | |
| 170 | - fn t8x8_inter(&self, mb_y: usize) -> bool { | |
| 171 | - self.transform_8x8_inter && (mb_y.is_multiple_of(2) || !self.transform_8x8_roweven) | |
| 172 | - } | |
| 173 | -} | |
| 174 | - | |
| 175 | 151 | /// Quantised levels of one macroblock, scan order per block. |
| 176 | 152 | #[derive(Clone)] |
| 177 | 153 | struct Levels { |
| @@ -399,7 +375,7 @@ fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { | ||
| 399 | 375 | /// The multiplier `motion_rate` applies, for loops that price many vectors. |
| 400 | 376 | #[inline] |
| 401 | 377 | fn motion_lambda(e: &MbEnc<'_>) -> f64 { |
| 402 | - if e.lambda_standard { | |
| 378 | + if e.transform_8x8 { | |
| 403 | 379 | e.lambda.sqrt() |
| 404 | 380 | } else { |
| 405 | 381 | e.lambda |
| @@ -565,7 +541,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | ||
| 565 | 541 | |
| 566 | 542 | let mut inter: Option<Vec<InterChoice>> = None; |
| 567 | 543 | if e.slice_type == SliceType::P { |
| 568 | - inter = Some(mb_timed!(0, choose_inter(pic, e, mb_x, mb_y))); | |
| 544 | + inter = Some(choose_inter(pic, e, mb_x, mb_y)); | |
| 569 | 545 | } |
| 570 | 546 | |
| 571 | 547 | // Intra against inter is decided on real coded cost: both branches are |
| @@ -597,21 +573,21 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | ||
| 597 | 573 | let gate = e.preset == Preset::Fast && e.fast.intra_gate > 0.0; |
| 598 | 574 | let intra_cost = match inter.as_ref() { |
| 599 | 575 | Some(c) if gate && e.fast.lazy_i16 => { |
| 600 | - let dc = mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2])); | |
| 576 | + let dc = intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2]); | |
| 601 | 577 | if f64::from(c[0].satd) <= e.fast.intra_gate * f64::from(dc.satd) { |
| 602 | 578 | dc |
| 603 | 579 | } else { |
| 604 | - mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3])) | |
| 580 | + intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3]) | |
| 605 | 581 | } |
| 606 | 582 | } |
| 607 | - _ => mb_timed!(1, intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3])), | |
| 583 | + _ => intra_pre_cost(pic, e, &nbr, mb_x, mb_y, &[2, 0, 1, 3]), | |
| 608 | 584 | }; |
| 609 | 585 | let Some(choices) = inter else { |
| 610 | - mb_timed!(3, encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost)); | |
| 586 | + encode_intra_mb(pic, e, w, mb_addr, nbr, intra_cost); | |
| 611 | 587 | return; |
| 612 | 588 | }; |
| 613 | 589 | |
| 614 | - let lambda = if e.lambda_standard { | |
| 590 | + let lambda = if e.transform_8x8 { | |
| 615 | 591 | e.lambda |
| 616 | 592 | } else { |
| 617 | 593 | lambda_ssd(e.qp) |
| @@ -622,10 +598,10 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | ||
| 622 | 598 | if gated { |
| 623 | 599 | // Inter only and one candidate at Fast: nothing is compared, so the |
| 624 | 600 | // macroblock is coded straight into the picture and the writer. |
| 625 | - mb_timed!(2, encode_inter_mb(pic, e, w, mb_addr, nbr, choices[0])); | |
| 601 | + encode_inter_mb(pic, e, w, mb_addr, nbr, choices[0]); | |
| 626 | 602 | return; |
| 627 | 603 | } |
| 628 | - let before = mb_timed!(4, save_mb_state(pic, e, mb_addr)); | |
| 604 | + let before = save_mb_state(pic, e, mb_addr); | |
| 629 | 605 | // The shape and the skip flag are ranked the same way intra and inter are: |
| 630 | 606 | // by coding each candidate and measuring it. The SATD total that ordered |
| 631 | 607 | // them inside the search is a prediction-domain estimate that never sees |
| @@ -638,26 +614,23 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | ||
| 638 | 614 | }; |
| 639 | 615 | let mut best_inter: Option<(f64, MbState, EncEntropy)> = None; |
| 640 | 616 | for &choice in &choices[..rd_cands.max(1)] { |
| 641 | - mb_timed!(4, load_mb_state(pic, e, mb_addr, &before)); | |
| 642 | - let mut w_c = mb_timed!(5, w.probe_copy()); | |
| 617 | + load_mb_state(pic, e, mb_addr, &before); | |
| 618 | + let mut w_c = w.probe_copy(); | |
| 643 | 619 | let start = w_c.bit_len(); |
| 644 | - mb_timed!(2, encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice)); | |
| 620 | + encode_inter_mb(pic, e, &mut w_c, mb_addr, nbr, choice); | |
| 645 | 621 | let bits = (w_c.bit_len() - start) as f64; |
| 646 | 622 | let rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * bits; |
| 647 | 623 | if best_inter.as_ref().is_none_or(|b| rd < b.0) { |
| 648 | - best_inter = Some((rd, mb_timed!(4, save_mb_state(pic, e, mb_addr)), w_c)); | |
| 624 | + best_inter = Some((rd, save_mb_state(pic, e, mb_addr), w_c)); | |
| 649 | 625 | } |
| 650 | 626 | } |
| 651 | 627 | let (inter_rd, after_inter, w_inter) = best_inter.expect("at least one inter candidate"); |
| 652 | - mb_timed!(4, load_mb_state(pic, e, mb_addr, &before)); | |
| 628 | + load_mb_state(pic, e, mb_addr, &before); | |
| 653 | 629 | |
| 654 | - let mut w_intra = mb_timed!(5, w.probe_copy()); | |
| 630 | + let mut w_intra = w.probe_copy(); | |
| 655 | 631 | let intra_bits = { |
| 656 | 632 | let start = w_intra.bit_len(); |
| 657 | - mb_timed!( | |
| 658 | - 3, | |
| 659 | - encode_intra_mb(pic, e, &mut w_intra, mb_addr, nbr, intra_cost) | |
| 660 | - ); | |
| 633 | + encode_intra_mb(pic, e, &mut w_intra, mb_addr, nbr, intra_cost); | |
| 661 | 634 | (w_intra.bit_len() - start) as f64 |
| 662 | 635 | }; |
| 663 | 636 | let intra_rd = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda * intra_bits; |
| @@ -665,7 +638,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy | ||
| 665 | 638 | if intra_rd < inter_rd { |
| 666 | 639 | w.adopt(w_intra); |
| 667 | 640 | } else { |
| 668 | - mb_timed!(4, load_mb_state(pic, e, mb_addr, &after_inter)); | |
| 641 | + load_mb_state(pic, e, mb_addr, &after_inter); | |
| 669 | 642 | w.adopt(w_inter); |
| 670 | 643 | } |
| 671 | 644 | } |
| @@ -1097,18 +1070,15 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I | ||
| 1097 | 1070 | |
| 1098 | 1071 | let fast = e.preset == Preset::Fast; |
| 1099 | 1072 | let mut best = ([0i16; 2], i32::MAX); |
| 1100 | - mb_timed!( | |
| 1101 | - 12, | |
| 1102 | - for (i, &cand) in seeds.iter().enumerate() { | |
| 1103 | - if seeds[..i].contains(&cand) { | |
| 1104 | - continue; | |
| 1105 | - } | |
| 1106 | - let c = cost_of(cand, false); | |
| 1107 | - if c < best.1 { | |
| 1108 | - best = (cand, c); | |
| 1109 | - } | |
| 1073 | + for (i, &cand) in seeds.iter().enumerate() { | |
| 1074 | + if seeds[..i].contains(&cand) { | |
| 1075 | + continue; | |
| 1110 | 1076 | } |
| 1111 | - ); | |
| 1077 | + let c = cost_of(cand, false); | |
| 1078 | + if c < best.1 { | |
| 1079 | + best = (cand, c); | |
| 1080 | + } | |
| 1081 | + } | |
| 1112 | 1082 | // Every partition is searched. This used to stop at a seed whose cost |
| 1113 | 1083 | // was already under half a level a sample, on the reasoning that the |
| 1114 | 1084 | // prediction fit and the search is the encoder's hot loop. Swept on |
| @@ -1122,34 +1092,31 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I | ||
| 1122 | 1092 | // neighbours' motion, so the walk only has to settle around them. |
| 1123 | 1093 | let mut step = if fast { 2i16 * 4 } else { 4i16 * 4 }; |
| 1124 | 1094 | let mut passes = 0; |
| 1125 | - mb_timed!( | |
| 1126 | - 13, | |
| 1127 | - while step >= 4 { | |
| 1128 | - let mut improved = true; | |
| 1129 | - while improved { | |
| 1130 | - improved = false; | |
| 1131 | - passes += 1; | |
| 1132 | - if fast && passes > FAST_ME_PASSES { | |
| 1133 | - break; | |
| 1095 | + while step >= 4 { | |
| 1096 | + let mut improved = true; | |
| 1097 | + while improved { | |
| 1098 | + improved = false; | |
| 1099 | + passes += 1; | |
| 1100 | + if fast && passes > FAST_ME_PASSES { | |
| 1101 | + break; | |
| 1102 | + } | |
| 1103 | + for (dx, dy) in ME_PATTERN { | |
| 1104 | + let (dx, dy) = (dx * step, dy * step); | |
| 1105 | + let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 1106 | + if (cand[0] - mvp[0]).abs() > range * 4 | |
| 1107 | + || (cand[1] - mvp[1]).abs() > range * 4 | |
| 1108 | + { | |
| 1109 | + continue; | |
| 1134 | 1110 | } |
| 1135 | - for (dx, dy) in ME_PATTERN { | |
| 1136 | - let (dx, dy) = (dx * step, dy * step); | |
| 1137 | - let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 1138 | - if (cand[0] - mvp[0]).abs() > range * 4 | |
| 1139 | - || (cand[1] - mvp[1]).abs() > range * 4 | |
| 1140 | - { | |
| 1141 | - continue; | |
| 1142 | - } | |
| 1143 | - let c = cost_of(cand, false); | |
| 1144 | - if c < best.1 { | |
| 1145 | - best = (cand, c); | |
| 1146 | - improved = true; | |
| 1147 | - } | |
| 1111 | + let c = cost_of(cand, false); | |
| 1112 | + if c < best.1 { | |
| 1113 | + best = (cand, c); | |
| 1114 | + improved = true; | |
| 1148 | 1115 | } |
| 1149 | 1116 | } |
| 1150 | - step /= 2; | |
| 1151 | 1117 | } |
| 1152 | - ); | |
| 1118 | + step /= 2; | |
| 1119 | + } | |
| 1153 | 1120 | // Sub-sample refinement runs on SATD, not SAD: interpolation |
| 1154 | 1121 | // smooths, and a sum of absolute differences reads the smoothing |
| 1155 | 1122 | // as a better match where a transform-domain cost does not. Worth |
| @@ -1157,79 +1124,77 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Vec<I | ||
| 1157 | 1124 | // capture. The whole-sample winner is re-costed in the same domain |
| 1158 | 1125 | // first so the two halves of the search compare. |
| 1159 | 1126 | let sub_satd = !fast || e.fast.me_satd; |
| 1160 | - mb_timed!(14, { | |
| 1161 | - best.1 = cost_of(best.0, sub_satd); | |
| 1162 | - // Balanced iterates both sub-sample steps to convergence. Fast | |
| 1163 | - // looks at each ring of eight once. | |
| 1164 | - let rings: &[i16] = if !fast { | |
| 1165 | - &[2, 1] | |
| 1166 | - } else { | |
| 1167 | - match e.fast.me_sub { | |
| 1168 | - 0 => &[], | |
| 1169 | - 1 => &[2], | |
| 1170 | - _ => &[2, 1], | |
| 1171 | - } | |
| 1172 | - }; | |
| 1173 | - if fast && e.fast.me_sub == 1 { | |
| 1174 | - // The four half-sample neighbours on the axes, then only the | |
| 1175 | - // diagonal the two winning axes point at. | |
| 1176 | - let base = best; | |
| 1177 | - let mut axis = [(base.0, base.1); 2]; | |
| 1178 | - for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] | |
| 1179 | - .into_iter() | |
| 1180 | - .enumerate() | |
| 1181 | - { | |
| 1182 | - for (dx, dy) in dirs { | |
| 1183 | - let cand = [base.0[0] + dx, base.0[1] + dy]; | |
| 1184 | - let c = cost_of(cand, sub_satd); | |
| 1185 | - if c < axis[k].1 { | |
| 1186 | - axis[k] = (cand, c); | |
| 1187 | - } | |
| 1188 | - } | |
| 1189 | - } | |
| 1190 | - let both = axis[0].1 < base.1 && axis[1].1 < base.1; | |
| 1191 | - if both { | |
| 1192 | - let cand = [axis[0].0[0], axis[1].0[1]]; | |
| 1127 | + best.1 = cost_of(best.0, sub_satd); | |
| 1128 | + // Balanced iterates both sub-sample steps to convergence. Fast | |
| 1129 | + // looks at each ring of eight once. | |
| 1130 | + let rings: &[i16] = if !fast { | |
| 1131 | + &[2, 1] | |
| 1132 | + } else { | |
| 1133 | + match e.fast.me_sub { | |
| 1134 | + 0 => &[], | |
| 1135 | + 1 => &[2], | |
| 1136 | + _ => &[2, 1], | |
| 1137 | + } | |
| 1138 | + }; | |
| 1139 | + if fast && e.fast.me_sub == 1 { | |
| 1140 | + // The four half-sample neighbours on the axes, then only the | |
| 1141 | + // diagonal the two winning axes point at. | |
| 1142 | + let base = best; | |
| 1143 | + let mut axis = [(base.0, base.1); 2]; | |
| 1144 | + for (k, dirs) in [[(2i16, 0i16), (-2, 0)], [(0, 2), (0, -2)]] | |
| 1145 | + .into_iter() | |
| 1146 | + .enumerate() | |
| 1147 | + { | |
| 1148 | + for (dx, dy) in dirs { | |
| 1149 | + let cand = [base.0[0] + dx, base.0[1] + dy]; | |
| 1193 | 1150 | let c = cost_of(cand, sub_satd); |
| 1194 | - if c < best.1 { | |
| 1195 | - best = (cand, c); | |
| 1151 | + if c < axis[k].1 { | |
| 1152 | + axis[k] = (cand, c); | |
| 1196 | 1153 | } |
| 1197 | 1154 | } |
| 1198 | - for a in axis { | |
| 1199 | - if a.1 < best.1 { | |
| 1200 | - best = a; | |
| 1201 | - } | |
| 1155 | + } | |
| 1156 | + let both = axis[0].1 < base.1 && axis[1].1 < base.1; | |
| 1157 | + if both { | |
| 1158 | + let cand = [axis[0].0[0], axis[1].0[1]]; | |
| 1159 | + let c = cost_of(cand, sub_satd); | |
| 1160 | + if c < best.1 { | |
| 1161 | + best = (cand, c); | |
| 1202 | 1162 | } |
| 1203 | 1163 | } |
| 1204 | - let rings: &[i16] = if fast && e.fast.me_sub == 1 { | |
| 1205 | - &[] | |
| 1206 | - } else { | |
| 1207 | - rings | |
| 1208 | - }; | |
| 1209 | - for &step in rings { | |
| 1210 | - let mut improved = true; | |
| 1211 | - while improved { | |
| 1212 | - improved = false; | |
| 1213 | - for (dx, dy) in [ | |
| 1214 | - (step, 0), | |
| 1215 | - (-step, 0), | |
| 1216 | - (0, step), | |
| 1217 | - (0, -step), | |
| 1218 | - (step, step), | |
| 1219 | - (-step, -step), | |
| 1220 | - (step, -step), | |
| 1221 | - (-step, step), | |
| 1222 | - ] { | |
| 1223 | - let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 1224 | - let c = cost_of(cand, sub_satd); | |
| 1225 | - if c < best.1 { | |
| 1226 | - best = (cand, c); | |
| 1227 | - improved = !fast; | |
| 1228 | - } | |
| 1164 | + for a in axis { | |
| 1165 | + if a.1 < best.1 { | |
| 1166 | + best = a; | |
| 1167 | + } | |
| 1168 | + } | |
| 1169 | + } | |
| 1170 | + let rings: &[i16] = if fast && e.fast.me_sub == 1 { | |
| 1171 | + &[] | |
| 1172 | + } else { | |
| 1173 | + rings | |
| 1174 | + }; | |
| 1175 | + for &step in rings { | |
| 1176 | + let mut improved = true; | |
| 1177 | + while improved { | |
| 1178 | + improved = false; | |
| 1179 | + for (dx, dy) in [ | |
| 1180 | + (step, 0), | |
| 1181 | + (-step, 0), | |
| 1182 | + (0, step), | |
| 1183 | + (0, -step), | |
| 1184 | + (step, step), | |
| 1185 | + (-step, -step), | |
| 1186 | + (step, -step), | |
| 1187 | + (-step, step), | |
| 1188 | + ] { | |
| 1189 | + let cand = [best.0[0] + dx, best.0[1] + dy]; | |
| 1190 | + let c = cost_of(cand, sub_satd); | |
| 1191 | + if c < best.1 { | |
| 1192 | + best = (cand, c); | |
| 1193 | + improved = !fast; | |
| 1229 | 1194 | } |
| 1230 | 1195 | } |
| 1231 | 1196 | } |
| 1232 | - }); | |
| 1197 | + } | |
| 1233 | 1198 | } |
| 1234 | 1199 | ( |
| 1235 | 1200 | best.0, |
| @@ -1487,7 +1452,7 @@ fn code_luma_4x4( | ||
| 1487 | 1452 | &source, |
| 1488 | 1453 | &resid, |
| 1489 | 1454 | &lv.luma[blk], |
| 1490 | - zero_block_lambda(e, qp, e.t8x8_inter(mb_y)), | |
| 1455 | + zero_block_lambda(e, qp, e.transform_8x8), | |
| 1491 | 1456 | ) |
| 1492 | 1457 | { |
| 1493 | 1458 | lv.luma[blk] = [0; 16]; |
| @@ -1535,7 +1500,7 @@ fn code_luma_4x4( | ||
| 1535 | 1500 | let lambda = if w.is_cabac() { |
| 1536 | 1501 | GROUP_LAMBDA * lambda_ssd(qp) |
| 1537 | 1502 | } else { |
| 1538 | - zero_block_lambda(e, qp, e.t8x8_inter(mb_y)) | |
| 1503 | + zero_block_lambda(e, qp, e.transform_8x8) | |
| 1539 | 1504 | }; |
| 1540 | 1505 | for g in 0..4 { |
| 1541 | 1506 | if rate[g] == 0.0 { |
| @@ -1957,15 +1922,7 @@ fn code_chroma( | ||
| 1957 | 1922 | &source, |
| 1958 | 1923 | &resid, |
| 1959 | 1924 | &ac[comp][blk], |
| 1960 | - zero_block_lambda( | |
| 1961 | - e, | |
| 1962 | - qp_c, | |
| 1963 | - if intra { | |
| 1964 | - e.t8x8_intra(mb_y) | |
| 1965 | - } else { | |
| 1966 | - e.t8x8_inter(mb_y) | |
| 1967 | - }, | |
| 1968 | - ), | |
| 1925 | + zero_block_lambda(e, qp_c, e.transform_8x8), | |
| 1969 | 1926 | ) { |
| 1970 | 1927 | ac[comp][blk] = [0; 16]; |
| 1971 | 1928 | nz = 0; |
| @@ -2189,7 +2146,7 @@ fn code_intra_4x4( | ||
| 2189 | 2146 | // full rate term this search loses 0.065 dB instead of gaining, |
| 2190 | 2147 | // and it loses more the more candidates it sees. |
| 2191 | 2148 | let lambda = ZERO_BLOCK_LAMBDA |
| 2192 | - * if e.lambda_standard { | |
| 2149 | + * if e.transform_8x8 { | |
| 2193 | 2150 | e.lambda |
| 2194 | 2151 | } else { |
| 2195 | 2152 | lambda_ssd(qp) |
| @@ -2322,14 +2279,7 @@ fn code_block_8x8( | ||
| 2322 | 2279 | dequant_8x8(&mut raster, &e.ls8, qp); |
| 2323 | 2280 | let mut resid = [0i32; 64]; |
| 2324 | 2281 | inverse_transform_8x8(&raster, &mut resid); |
| 2325 | - if !rdoq | |
| 2326 | - && !intra | |
| 2327 | - && !worth_coding( | |
| 2328 | - &d, | |
| 2329 | - &resid, | |
| 2330 | - out, | |
| 2331 | - zero_block_lambda(e, qp, e.transform_8x8_inter), | |
| 2332 | - ) | |
| 2282 | + if !rdoq && !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp, e.transform_8x8)) | |
| 2333 | 2283 | { |
| 2334 | 2284 | *out = [0; 64]; |
| 2335 | 2285 | return 0; |
| @@ -2807,16 +2757,13 @@ fn encode_intra_mb( | ||
| 2807 | 2757 | let mut pred_modes8 = [2u8; 4]; |
| 2808 | 2758 | let mut use_i4 = false; |
| 2809 | 2759 | let mut chroma_lv = Levels::default(); |
| 2810 | - let chroma_mode = mb_timed!( | |
| 2811 | - 10, | |
| 2812 | - choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv) | |
| 2813 | - ); | |
| 2760 | + let chroma_mode = choose_chroma_mode_rd(pic, e, w, &nbr, mb_x, mb_y, qp, &mut chroma_lv); | |
| 2814 | 2761 | let mut use_i8 = false; |
| 2815 | 2762 | |
| 2816 | 2763 | if cost.allow_i4 { |
| 2817 | 2764 | let mut lv4 = chroma_lv.clone(); |
| 2818 | - let (m4, p4) = mb_timed!(6, code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4)); | |
| 2819 | - let cost4 = if e.t8x8_intra(mb_y) { | |
| 2765 | + let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); | |
| 2766 | + let cost4 = if e.transform_8x8 { | |
| 2820 | 2767 | let bits = intra_mb_bits( |
| 2821 | 2768 | pic, |
| 2822 | 2769 | e, |
| @@ -2847,8 +2794,8 @@ fn encode_intra_mb( | ||
| 2847 | 2794 | let mut recon8 = [0u8; 256]; |
| 2848 | 2795 | let skip8 = e.preset == Preset::Fast |
| 2849 | 2796 | && (e.fast.skip_i8 || (e.fast.p_skip_i8 && e.slice_type == SliceType::P)); |
| 2850 | - let cost8 = if e.t8x8_intra(mb_y) && !skip8 { | |
| 2851 | - let (m8, p8) = mb_timed!(7, code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8)); | |
| 2797 | + let cost8 = if e.transform_8x8 && !skip8 { | |
| 2798 | + let (m8, p8) = code_intra_8x8(pic, e, w, mb_x, mb_y, qp, &nbr, &mut lv8); | |
| 2852 | 2799 | modes8 = m8; |
| 2853 | 2800 | pred_modes8 = p8; |
| 2854 | 2801 | save_luma(pic, mb_x, mb_y, &mut recon8); |
| @@ -2870,11 +2817,8 @@ fn encode_intra_mb( | ||
| 2870 | 2817 | }; |
| 2871 | 2818 | |
| 2872 | 2819 | let mut lv16 = chroma_lv; |
| 2873 | - mb_timed!( | |
| 2874 | - 11, | |
| 2875 | - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16) | |
| 2876 | - ); | |
| 2877 | - let cost16 = if e.t8x8_intra(mb_y) { | |
| 2820 | + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); | |
| 2821 | + let cost16 = if e.transform_8x8 { | |
| 2878 | 2822 | let bits = intra_mb_bits( |
| 2879 | 2823 | pic, |
| 2880 | 2824 | e, |
| @@ -2893,9 +2837,7 @@ fn encode_intra_mb( | ||
| 2893 | 2837 | + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 |
| 2894 | 2838 | }; |
| 2895 | 2839 | |
| 2896 | - if cost8 + e.lambda * e.t8x8_margin_bits <= cost4 | |
| 2897 | - && cost8 + e.lambda * e.t8x8_margin_bits <= cost16 | |
| 2898 | - { | |
| 2840 | + if cost8 <= cost4 && cost8 <= cost16 { | |
| 2899 | 2841 | use_i4 = true; |
| 2900 | 2842 | use_i8 = true; |
| 2901 | 2843 | restore_luma(pic, mb_x, mb_y, &recon8); |
| @@ -2921,10 +2863,7 @@ fn encode_intra_mb( | ||
| 2921 | 2863 | } |
| 2922 | 2864 | } else { |
| 2923 | 2865 | lv = chroma_lv; |
| 2924 | - mb_timed!( | |
| 2925 | - 11, | |
| 2926 | - code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv) | |
| 2927 | - ); | |
| 2866 | + code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); | |
| 2928 | 2867 | } |
| 2929 | 2868 | |
| 2930 | 2869 | // ---- syntax ---- |
| @@ -3372,9 +3311,9 @@ fn encode_inter_mb( | ||
| 3372 | 3311 | } else { |
| 3373 | 3312 | 0 |
| 3374 | 3313 | }; |
| 3375 | - if e.t8x8_inter(mb_y) && tx_mode == 1 { | |
| 3314 | + if e.transform_8x8 && tx_mode == 1 { | |
| 3376 | 3315 | code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv); |
| 3377 | - } else if e.t8x8_inter(mb_y) && tx_mode != 2 { | |
| 3316 | + } else if e.transform_8x8 && tx_mode != 2 { | |
| 3378 | 3317 | // Both transform sizes on the same prediction; the cheaper |
| 3379 | 3318 | // rate-distortion cost is coded. |
| 3380 | 3319 | let mut pred = [0u8; 256]; |
| @@ -3397,7 +3336,7 @@ fn encode_inter_mb( | ||
| 3397 | 3336 | code_luma_8x8(pic, e, w, mb_x, mb_y, qp, &mut lv8); |
| 3398 | 3337 | let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); |
| 3399 | 3338 | let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; |
| 3400 | - if cost8 + e.lambda * e.t8x8_margin_bits < cost4 { | |
| 3339 | + if cost8 < cost4 { | |
| 3401 | 3340 | lv = lv8; |
| 3402 | 3341 | } else { |
| 3403 | 3342 | lv = lv4; |
| @@ -3412,7 +3351,7 @@ fn encode_inter_mb( | ||
| 3412 | 3351 | None => false, |
| 3413 | 3352 | Some(_) if empty => true, |
| 3414 | 3353 | Some(ssd_skip) => { |
| 3415 | - let coded = if e.t8x8_inter(mb_y) { | |
| 3354 | + let coded = if e.transform_8x8 { | |
| 3416 | 3355 | let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); |
| 3417 | 3356 | ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 |
| 3418 | 3357 | } else { |
crates/ec-h264/src/enc/mod.rsmodified+5 -242
| @@ -27,7 +27,6 @@ mod mb; | ||
| 27 | 27 | mod pool; |
| 28 | 28 | mod quant; |
| 29 | 29 | mod rc; |
| 30 | -pub(crate) mod timing; | |
| 31 | 30 | mod vlc; |
| 32 | 31 | |
| 33 | 32 | use ec_core::BitWriter; |
| @@ -37,8 +36,6 @@ use ec_h264_syntax::{SliceType, Sps}; | ||
| 37 | 36 | |
| 38 | 37 | use crate::decoder::deblock_picture; |
| 39 | 38 | use crate::dpb::{Picture, SliceParams as DeblockParams}; |
| 40 | -#[cfg(feature = "rd-ablation")] | |
| 41 | -use crate::entropy::FLAG_SKIP; | |
| 42 | 39 | use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; |
| 43 | 40 | use crate::transform::{LevelScale4x4, LevelScale8x8}; |
| 44 | 41 | |
| @@ -48,8 +45,6 @@ use mb::{MbEnc, Source, encode_mb}; | ||
| 48 | 45 | use pool::BandPool; |
| 49 | 46 | use rc::RateControl; |
| 50 | 47 | use std::sync::Arc; |
| 51 | -use std::time::Instant; | |
| 52 | -pub use timing::EncodeTimings; | |
| 53 | 48 | |
| 54 | 49 | pub use mb::Preset; |
| 55 | 50 | |
| @@ -87,16 +82,6 @@ pub struct EncoderConfig { | ||
| 87 | 82 | /// Turning it off restricts the stream to the Baseline/Main-profile 4x4 |
| 88 | 83 | /// path, which costs 0.7 dB BD-PSNR on film and 0.2 dB on screen capture. |
| 89 | 84 | pub transform_8x8: bool, |
| 90 | - #[cfg(feature = "rd-ablation")] | |
| 91 | - rd_lambda_standard: bool, | |
| 92 | - #[cfg(feature = "rd-ablation")] | |
| 93 | - rd_transform_8x8_intra: bool, | |
| 94 | - #[cfg(feature = "rd-ablation")] | |
| 95 | - rd_transform_8x8_inter: bool, | |
| 96 | - #[cfg(feature = "rd-ablation")] | |
| 97 | - rd_transform_8x8_roweven: bool, | |
| 98 | - #[cfg(feature = "rd-ablation")] | |
| 99 | - rd_transform_8x8_margin_bits: f64, | |
| 100 | 85 | } |
| 101 | 86 | |
| 102 | 87 | impl EncoderConfig { |
| @@ -114,16 +99,6 @@ impl EncoderConfig { | ||
| 114 | 99 | threads: 0, |
| 115 | 100 | qp: 26, |
| 116 | 101 | transform_8x8: true, |
| 117 | - #[cfg(feature = "rd-ablation")] | |
| 118 | - rd_lambda_standard: false, | |
| 119 | - #[cfg(feature = "rd-ablation")] | |
| 120 | - rd_transform_8x8_intra: false, | |
| 121 | - #[cfg(feature = "rd-ablation")] | |
| 122 | - rd_transform_8x8_inter: false, | |
| 123 | - #[cfg(feature = "rd-ablation")] | |
| 124 | - rd_transform_8x8_roweven: false, | |
| 125 | - #[cfg(feature = "rd-ablation")] | |
| 126 | - rd_transform_8x8_margin_bits: 0.0, | |
| 127 | 102 | } |
| 128 | 103 | } |
| 129 | 104 | } |
| @@ -169,7 +144,6 @@ pub struct Encoder { | ||
| 169 | 144 | have_reference: bool, |
| 170 | 145 | /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter). |
| 171 | 146 | t8x8_mbs: (u64, u64), |
| 172 | - timings: timing::EncodeTimings, | |
| 173 | 147 | } |
| 174 | 148 | |
| 175 | 149 | /// A picture handed to the encoder: three planes, no padding assumptions. |
| @@ -204,10 +178,6 @@ impl<'a> PictureView<'a> { | ||
| 204 | 178 | impl Encoder { |
| 205 | 179 | /// Build an encoder for `cfg`, refusing what it cannot code. |
| 206 | 180 | pub fn new(cfg: EncoderConfig) -> Result<Encoder> { |
| 207 | - #[cfg(feature = "rd-ablation")] | |
| 208 | - let mut cfg = cfg; | |
| 209 | - #[cfg(feature = "rd-ablation")] | |
| 210 | - apply_rd_ablation(&mut cfg); | |
| 211 | 181 | if cfg.width < 16 || cfg.height < 16 { |
| 212 | 182 | return Err(Error::unsupported( |
| 213 | 183 | "picture smaller than one macroblock", |
| @@ -288,7 +258,6 @@ impl Encoder { | ||
| 288 | 258 | next_id: 0, |
| 289 | 259 | have_reference: false, |
| 290 | 260 | t8x8_mbs: (0, 0), |
| 291 | - timings: timing::EncodeTimings::default(), | |
| 292 | 261 | cfg, |
| 293 | 262 | }) |
| 294 | 263 | } |
| @@ -304,11 +273,6 @@ impl Encoder { | ||
| 304 | 273 | &self.cfg |
| 305 | 274 | } |
| 306 | 275 | |
| 307 | - /// Where the encode time went so far; see [`EncodeTimings`]. | |
| 308 | - pub fn timings(&self) -> EncodeTimings { | |
| 309 | - self.timings | |
| 310 | - } | |
| 311 | - | |
| 312 | 276 | /// The reconstruction of the last coded picture, cropped, as I420 planes. |
| 313 | 277 | /// This is what a conformant decoder produces for that picture — the tests |
| 314 | 278 | /// compare it against this crate's decoder and against the oracle. |
| @@ -351,9 +315,7 @@ impl Encoder { | ||
| 351 | 315 | if frame.width != self.cfg.width || frame.height != self.cfg.height { |
| 352 | 316 | return Err(Error::corrupt("frame size differs from the encoder's")); |
| 353 | 317 | } |
| 354 | - let t_pad = Instant::now(); | |
| 355 | 318 | self.pad_source(frame)?; |
| 356 | - self.timings.pad += t_pad.elapsed().as_secs_f64(); | |
| 357 | 319 | if self.frames == 0 { |
| 358 | 320 | self.cqo = chroma_qp_offset_for_source(&self.src, self.cfg.width, self.cfg.height); |
| 359 | 321 | let pps_rbsp = write_pps(self.cfg.cabac, self.cfg.transform_8x8, self.cqo); |
| @@ -399,9 +361,6 @@ impl Encoder { | ||
| 399 | 361 | mb_w, |
| 400 | 362 | }); |
| 401 | 363 | |
| 402 | - let mut busiest = 0.0f64; | |
| 403 | - let mut busy = 0.0f64; | |
| 404 | - let t_bands = Instant::now(); | |
| 405 | 364 | let mut answers = Vec::with_capacity(bands.len()); |
| 406 | 365 | if self.threads == 1 { |
| 407 | 366 | // One band: coded on this thread, with no workers. |
| @@ -434,8 +393,6 @@ impl Encoder { | ||
| 434 | 393 | } |
| 435 | 394 | let mut outputs: Vec<Vec<u8>> = Vec::with_capacity(bands.len()); |
| 436 | 395 | for (band, answer) in answers.into_iter().enumerate() { |
| 437 | - busiest = busiest.max(answer.secs); | |
| 438 | - busy += answer.secs; | |
| 439 | 396 | outputs.push(answer.rbsp); |
| 440 | 397 | self.workers[band] = answer.pic; |
| 441 | 398 | } |
| @@ -447,10 +404,6 @@ impl Encoder { | ||
| 447 | 404 | if let Some(reference) = shared.reference { |
| 448 | 405 | self.reference = reference; |
| 449 | 406 | } |
| 450 | - self.timings.bands_wall += t_bands.elapsed().as_secs_f64(); | |
| 451 | - self.timings.bands_busy += busy; | |
| 452 | - self.timings.bands_slowest += busiest; | |
| 453 | - let t_stitch = Instant::now(); | |
| 454 | 407 | |
| 455 | 408 | // Stitch the bands into worker 0's picture, then filter the whole |
| 456 | 409 | // picture the way a decoder does. |
| @@ -469,7 +422,6 @@ impl Encoder { | ||
| 469 | 422 | for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { |
| 470 | 423 | merge_band(master, worker, *band); |
| 471 | 424 | } |
| 472 | - self.timings.stitch += t_stitch.elapsed().as_secs_f64(); | |
| 473 | 425 | for &f in &master.mb_flags { |
| 474 | 426 | if f & FLAG_TRANS8X8 != 0 { |
| 475 | 427 | if f & FLAG_INTER != 0 { |
| @@ -479,19 +431,7 @@ impl Encoder { | ||
| 479 | 431 | } |
| 480 | 432 | } |
| 481 | 433 | } |
| 482 | - // H5 measurement hook: the chosen candidate's trial SSD is the | |
| 483 | - // pre-deblock SSD of the macroblock in this picture (round 4 verified | |
| 484 | - // trial bits and SSD against the final picture), so capturing the | |
| 485 | - // per-macroblock SSD right before and right after the filter is the | |
| 486 | - // exact pre/post comparison with no hooks inside the RD trials. | |
| 487 | - #[cfg(feature = "rd-ablation")] | |
| 488 | - let rd_pre = rd_trace_capture(master, &self.src); | |
| 489 | - let t_deblock = Instant::now(); | |
| 490 | 434 | deblock_picture(master); |
| 491 | - self.timings.deblock += t_deblock.elapsed().as_secs_f64(); | |
| 492 | - #[cfg(feature = "rd-ablation")] | |
| 493 | - rd_trace_write(master, &self.src, self.frames, rd_pre); | |
| 494 | - let t_output = Instant::now(); | |
| 495 | 435 | master.extend_borders(); |
| 496 | 436 | master.complete = true; |
| 497 | 437 | std::mem::swap(master, &mut self.reference); |
| @@ -513,8 +453,6 @@ impl Encoder { | ||
| 513 | 453 | } |
| 514 | 454 | |
| 515 | 455 | let bits = au.len() as u64 * 8; |
| 516 | - self.timings.output += t_output.elapsed().as_secs_f64(); | |
| 517 | - self.timings.pictures += 1; | |
| 518 | 456 | self.rc.update(idr, qp, bits); |
| 519 | 457 | self.frames += 1; |
| 520 | 458 | self.frame_num = (self.frame_num + 1) % (1 << headers::LOG2_MAX_FRAME_NUM); |
| @@ -682,7 +620,6 @@ struct BandMsg { | ||
| 682 | 620 | struct BandOut { |
| 683 | 621 | pic: Picture, |
| 684 | 622 | rbsp: Vec<u8>, |
| 685 | - secs: f64, | |
| 686 | 623 | } |
| 687 | 624 | |
| 688 | 625 | /// Code one band on a worker picture. |
| @@ -693,7 +630,6 @@ fn run_band(msg: BandMsg) -> BandOut { | ||
| 693 | 630 | band, |
| 694 | 631 | picture_id, |
| 695 | 632 | } = msg; |
| 696 | - let t_band = Instant::now(); | |
| 697 | 633 | let (row0, row1) = shared.bands[band]; |
| 698 | 634 | let mb_w = shared.mb_w; |
| 699 | 635 | pic.start(&shared.sps); |
| @@ -719,11 +655,7 @@ fn run_band(msg: BandMsg) -> BandOut { | ||
| 719 | 655 | cqo: shared.cqo, |
| 720 | 656 | }, |
| 721 | 657 | ); |
| 722 | - BandOut { | |
| 723 | - pic, | |
| 724 | - rbsp, | |
| 725 | - secs: t_band.elapsed().as_secs_f64(), | |
| 726 | - } | |
| 658 | + BandOut { pic, rbsp } | |
| 727 | 659 | } |
| 728 | 660 | |
| 729 | 661 | struct BandJob<'a> { |
| @@ -776,15 +708,10 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | ||
| 776 | 708 | slice_id: job.slice_id, |
| 777 | 709 | qp: job.qp, |
| 778 | 710 | target_qp: job.qp, |
| 779 | - lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)), | |
| 780 | - t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg), | |
| 711 | + lambda: lambda_for(job.qp, job.cfg.transform_8x8), | |
| 781 | 712 | preset: job.cfg.preset, |
| 782 | 713 | fast: fast_knobs(), |
| 783 | - lambda_standard: rd_lambda_standard(job.cfg), | |
| 784 | 714 | transform_8x8: job.cfg.transform_8x8, |
| 785 | - transform_8x8_intra: rd_transform_8x8_intra(job.cfg), | |
| 786 | - transform_8x8_inter: rd_transform_8x8_inter(job.cfg), | |
| 787 | - transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg), | |
| 788 | 715 | ls: LevelScale4x4::new(&[16; 16]), |
| 789 | 716 | ls8: LevelScale8x8::new(&[16; 64]), |
| 790 | 717 | mb_ctx: crate::entropy::MbCtx::default(), |
| @@ -801,7 +728,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> { | ||
| 801 | 728 | let expected = job.band_target * n as f64 / rows as f64; |
| 802 | 729 | let delta = job.rc.row_delta(spent, expected); |
| 803 | 730 | e.target_qp = (job.qp + delta).clamp(10, 51); |
| 804 | - e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg)); | |
| 731 | + e.lambda = lambda_for(e.target_qp, job.cfg.transform_8x8); | |
| 805 | 732 | } |
| 806 | 733 | for mb_x in 0..mb_w { |
| 807 | 734 | let addr = mb_y * mb_w + mb_x; |
| @@ -878,167 +805,6 @@ fn lambda_for(qp: i32, standard: bool) -> f64 { | ||
| 878 | 805 | } |
| 879 | 806 | } |
| 880 | 807 | |
| 881 | -#[cfg(feature = "rd-ablation")] | |
| 882 | -fn apply_rd_ablation(cfg: &mut EncoderConfig) { | |
| 883 | - if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") { | |
| 884 | - cfg.rd_lambda_standard = match lambda.as_str() { | |
| 885 | - "ladder" => false, | |
| 886 | - "standard" => true, | |
| 887 | - _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"), | |
| 888 | - }; | |
| 889 | - } | |
| 890 | - if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") { | |
| 891 | - let (intra, inter, roweven) = match transform.as_str() { | |
| 892 | - "off" => (false, false, false), | |
| 893 | - "on" => (true, true, false), | |
| 894 | - "roweven" => (true, true, true), | |
| 895 | - "intra" => (true, false, false), | |
| 896 | - "inter" => (false, true, false), | |
| 897 | - _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"), | |
| 898 | - }; | |
| 899 | - cfg.rd_transform_8x8_intra = intra; | |
| 900 | - cfg.rd_transform_8x8_inter = inter; | |
| 901 | - cfg.rd_transform_8x8_roweven = roweven; | |
| 902 | - cfg.transform_8x8 = intra || inter; | |
| 903 | - } else if cfg.transform_8x8 { | |
| 904 | - cfg.rd_transform_8x8_intra = true; | |
| 905 | - cfg.rd_transform_8x8_inter = true; | |
| 906 | - } | |
| 907 | - if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") { | |
| 908 | - cfg.rd_transform_8x8_margin_bits = margin | |
| 909 | - .parse() | |
| 910 | - .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number"); | |
| 911 | - } | |
| 912 | -} | |
| 913 | - | |
| 914 | -/// Luma and chroma SSD of every macroblock against the source, before the | |
| 915 | -/// deblocking filter — the distortion the RD decision actually paid. | |
| 916 | -#[cfg(feature = "rd-ablation")] | |
| 917 | -fn rd_trace_capture(pic: &Picture, src: &Source) -> Option<Vec<(i64, i64)>> { | |
| 918 | - if std::env::var_os("EC_H264_RD_TRACE").is_none() { | |
| 919 | - return None; | |
| 920 | - } | |
| 921 | - let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h); | |
| 922 | - for mb_y in 0..pic.mb_h { | |
| 923 | - for mb_x in 0..pic.mb_w { | |
| 924 | - out.push(rd_trace_ssd(pic, src, mb_x, mb_y)); | |
| 925 | - } | |
| 926 | - } | |
| 927 | - Some(out) | |
| 928 | -} | |
| 929 | - | |
| 930 | -/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma | |
| 931 | -/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`. | |
| 932 | -#[cfg(feature = "rd-ablation")] | |
| 933 | -fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64, i64)>>) { | |
| 934 | - use std::io::Write; | |
| 935 | - let Some(pre) = pre else { return }; | |
| 936 | - let mut out = std::fs::OpenOptions::new() | |
| 937 | - .create(true) | |
| 938 | - .append(true) | |
| 939 | - .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture")) | |
| 940 | - .expect("open EC_H264_RD_TRACE"); | |
| 941 | - for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() { | |
| 942 | - let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w); | |
| 943 | - let f = pic.mb_flags[addr]; | |
| 944 | - // A discarded write result here is a SILENTLY SHORT trace: the reader | |
| 945 | - // of `$EC_H264_RD_TRACE` attributes decisions from it and cannot tell a | |
| 946 | - // short line count from a real one. No length check is possible (append | |
| 947 | - // mode has no knowable total), so this is the ec-av1 `append_unknown` | |
| 948 | - // shape: the write error is fatal instead. | |
| 949 | - writeln!( | |
| 950 | - out, | |
| 951 | - "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}", | |
| 952 | - u8::from(f & FLAG_INTER == 0), | |
| 953 | - u8::from(f & FLAG_TRANS8X8 != 0), | |
| 954 | - u8::from(f & FLAG_SKIP != 0), | |
| 955 | - pic.mb_qp[addr] | |
| 956 | - ) | |
| 957 | - .expect("write EC_H264_RD_TRACE"); | |
| 958 | - } | |
| 959 | -} | |
| 960 | - | |
| 961 | -/// Luma and chroma SSD of one macroblock against the source planes. | |
| 962 | -#[cfg(feature = "rd-ablation")] | |
| 963 | -fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) { | |
| 964 | - let mut luma = 0i64; | |
| 965 | - let stride = pic.y.stride; | |
| 966 | - let origin = pic.y.at(mb_x * 16, mb_y * 16); | |
| 967 | - for row in 0..16 { | |
| 968 | - let s = (mb_y * 16 + row) * src.stride + mb_x * 16; | |
| 969 | - for x in 0..16 { | |
| 970 | - let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); | |
| 971 | - luma += d * d; | |
| 972 | - } | |
| 973 | - } | |
| 974 | - let mut chroma = 0i64; | |
| 975 | - for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] { | |
| 976 | - let stride = plane.stride; | |
| 977 | - let origin = plane.at(mb_x * 8, mb_y * 8); | |
| 978 | - for row in 0..8 { | |
| 979 | - let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8; | |
| 980 | - for x in 0..8 { | |
| 981 | - let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]); | |
| 982 | - chroma += d * d; | |
| 983 | - } | |
| 984 | - } | |
| 985 | - } | |
| 986 | - (luma, chroma) | |
| 987 | -} | |
| 988 | - | |
| 989 | -#[cfg(feature = "rd-ablation")] | |
| 990 | -fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { | |
| 991 | - cfg.rd_lambda_standard | |
| 992 | -} | |
| 993 | - | |
| 994 | -#[cfg(not(feature = "rd-ablation"))] | |
| 995 | -fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { | |
| 996 | - cfg.transform_8x8 | |
| 997 | -} | |
| 998 | - | |
| 999 | -#[cfg(feature = "rd-ablation")] | |
| 1000 | -fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { | |
| 1001 | - cfg.rd_transform_8x8_intra | |
| 1002 | -} | |
| 1003 | - | |
| 1004 | -#[cfg(not(feature = "rd-ablation"))] | |
| 1005 | -fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { | |
| 1006 | - cfg.transform_8x8 | |
| 1007 | -} | |
| 1008 | - | |
| 1009 | -#[cfg(feature = "rd-ablation")] | |
| 1010 | -fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { | |
| 1011 | - cfg.rd_transform_8x8_inter | |
| 1012 | -} | |
| 1013 | - | |
| 1014 | -#[cfg(not(feature = "rd-ablation"))] | |
| 1015 | -fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { | |
| 1016 | - cfg.transform_8x8 | |
| 1017 | -} | |
| 1018 | - | |
| 1019 | -#[cfg(feature = "rd-ablation")] | |
| 1020 | -fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool { | |
| 1021 | - cfg.rd_transform_8x8_roweven | |
| 1022 | -} | |
| 1023 | - | |
| 1024 | -#[cfg(not(feature = "rd-ablation"))] | |
| 1025 | -fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool { | |
| 1026 | - false | |
| 1027 | -} | |
| 1028 | - | |
| 1029 | -#[cfg(not(feature = "rd-ablation"))] | |
| 1030 | -const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0; | |
| 1031 | - | |
| 1032 | -#[cfg(feature = "rd-ablation")] | |
| 1033 | -fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 { | |
| 1034 | - cfg.rd_transform_8x8_margin_bits | |
| 1035 | -} | |
| 1036 | - | |
| 1037 | -#[cfg(not(feature = "rd-ablation"))] | |
| 1038 | -fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 { | |
| 1039 | - TRANSFORM_8X8_MARGIN_BITS | |
| 1040 | -} | |
| 1041 | - | |
| 1042 | 808 | /// Split `mb_h` macroblock rows into at most `n` contiguous bands. |
| 1043 | 809 | fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { |
| 1044 | 810 | let n = n.clamp(1, mb_h); |
| @@ -1198,12 +964,9 @@ mod tests { | ||
| 1198 | 964 | fn production_lambda_tracks_transform_mode() { |
| 1199 | 965 | let mut cfg = EncoderConfig::new(640, 480); |
| 1200 | 966 | cfg.transform_8x8 = false; |
| 1201 | - assert_eq!( | |
| 1202 | - lambda_for(26, rd_lambda_standard(&cfg)), | |
| 1203 | - lambda_for(26, false) | |
| 1204 | - ); | |
| 967 | + assert_eq!(lambda_for(26, cfg.transform_8x8), lambda_for(26, false)); | |
| 1205 | 968 | cfg.transform_8x8 = true; |
| 1206 | - assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26)); | |
| 969 | + assert_eq!(lambda_for(26, cfg.transform_8x8), lambda_ssd(26)); | |
| 1207 | 970 | } |
| 1208 | 971 | |
| 1209 | 972 | /// Flat chroma over textured luma picks the negative chroma QP offset, and |
crates/ec-h264/src/enc/timing.rsdeleted+0 -81
| @@ -1,81 +0,0 @@ | ||
| 1 | -//! Stage timers for one encoder, read through [`Encoder::timings`]. They cost a | |
| 2 | -//! clock read per stage per picture, which is noise next to a picture's coding. | |
| 3 | -//! | |
| 4 | -//! [`Encoder::timings`]: super::Encoder::timings | |
| 5 | - | |
| 6 | -/// Wall-clock seconds spent in each stage of `encode`, summed over every | |
| 7 | -/// picture the encoder has coded. | |
| 8 | -#[derive(Debug, Clone, Copy, Default, PartialEq)] | |
| 9 | -pub struct EncodeTimings { | |
| 10 | - /// Pictures counted. | |
| 11 | - pub pictures: u64, | |
| 12 | - /// Copying and padding the source planes. | |
| 13 | - pub pad: f64, | |
| 14 | - /// The parallel band coding, wall clock. | |
| 15 | - pub bands_wall: f64, | |
| 16 | - /// Sum of every band's own coding time (the work the threads share). | |
| 17 | - pub bands_busy: f64, | |
| 18 | - /// Sum over pictures of the slowest band (the critical path). | |
| 19 | - pub bands_slowest: f64, | |
| 20 | - /// Stitching the bands into one picture. | |
| 21 | - pub stitch: f64, | |
| 22 | - /// The in-loop deblocking filter, which runs on one thread. | |
| 23 | - pub deblock: f64, | |
| 24 | - /// Border extension, the reference swap and assembling the access unit. | |
| 25 | - pub output: f64, | |
| 26 | -} | |
| 27 | - | |
| 28 | -/// Per-stage nanosecond counters for the macroblock coder, behind the | |
| 29 | -/// `enc-profile` feature so a normal build pays nothing. Shared atomics: the | |
| 30 | -/// bands add to them concurrently, which is fine for a profile. | |
| 31 | -#[cfg(feature = "enc-profile")] | |
| 32 | -pub mod mb_stages { | |
| 33 | - use std::sync::atomic::{AtomicU64, Ordering}; | |
| 34 | - | |
| 35 | - /// Stage names, in index order. | |
| 36 | - pub const NAMES: [&str; 16] = [ | |
| 37 | - "choose_inter", | |
| 38 | - "intra_pre_cost", | |
| 39 | - "inter_rd_candidates", | |
| 40 | - "intra_rd_total", | |
| 41 | - "state_save_load", | |
| 42 | - "entropy_clone", | |
| 43 | - "intra4x4_rd", | |
| 44 | - "intra8x8_rd", | |
| 45 | - "intra_bits_and_ssd", | |
| 46 | - "(unused)", | |
| 47 | - "chroma_mode_rd", | |
| 48 | - "intra16_rd", | |
| 49 | - "me_seeds", | |
| 50 | - "me_int", | |
| 51 | - "me_sub", | |
| 52 | - "me_chroma_skip", | |
| 53 | - ]; | |
| 54 | - pub(crate) static NANOS: [AtomicU64; 16] = [const { AtomicU64::new(0) }; 16]; | |
| 55 | - | |
| 56 | - /// Nanoseconds spent in each stage so far, in [`NAMES`] order. | |
| 57 | - pub fn snapshot() -> [u64; 16] { | |
| 58 | - std::array::from_fn(|i| NANOS[i].load(Ordering::Relaxed)) | |
| 59 | - } | |
| 60 | -} | |
| 61 | - | |
| 62 | -/// Time `$body` into stage `$idx` of [`mb_stages`] when profiling, else just run it. | |
| 63 | -#[cfg(feature = "enc-profile")] | |
| 64 | -macro_rules! mb_timed { | |
| 65 | - ($idx:expr, $body:expr) => {{ | |
| 66 | - let t = std::time::Instant::now(); | |
| 67 | - let r = $body; | |
| 68 | - $crate::enc::timing::mb_stages::NANOS[$idx].fetch_add( | |
| 69 | - t.elapsed().as_nanos() as u64, | |
| 70 | - std::sync::atomic::Ordering::Relaxed, | |
| 71 | - ); | |
| 72 | - r | |
| 73 | - }}; | |
| 74 | -} | |
| 75 | -#[cfg(not(feature = "enc-profile"))] | |
| 76 | -macro_rules! mb_timed { | |
| 77 | - ($idx:expr, $body:expr) => { | |
| 78 | - $body | |
| 79 | - }; | |
| 80 | -} | |
| 81 | -pub(crate) use mb_timed; |
crates/ec-h264/src/lib.rsmodified+3 -6
| @@ -46,8 +46,8 @@ mod deblock_mbaff; | ||
| 46 | 46 | mod decoder; |
| 47 | 47 | mod dpb; |
| 48 | 48 | mod enc; |
| 49 | -mod fmo; | |
| 50 | 49 | mod entropy; |
| 50 | +mod fmo; | |
| 51 | 51 | mod inter; |
| 52 | 52 | mod inter16; |
| 53 | 53 | mod mbaff; |
| @@ -57,10 +57,7 @@ mod sample; | ||
| 57 | 57 | mod tables; |
| 58 | 58 | mod transform; |
| 59 | 59 | |
| 60 | -pub use cabac::BitAccount; | |
| 61 | 60 | pub use codec::H264Decoder; |
| 62 | -pub use decoder::{Decoder, MbShapes, NalOutcome, OutputOrder}; | |
| 61 | +pub use decoder::{Decoder, NalOutcome, OutputOrder}; | |
| 63 | 62 | pub use ec_core::error::{Error, Result}; |
| 64 | -#[cfg(feature = "enc-profile")] | |
| 65 | -pub use enc::timing::mb_stages; | |
| 66 | -pub use enc::{EncodeTimings, EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; | |
| 63 | +pub use enc::{EncodedPicture, Encoder, EncoderConfig, PictureView, Preset}; |
crates/ec-h264/src/tables.rsmodified+1 -4
| @@ -625,9 +625,6 @@ pub const TC0: [[u8; 52]; 3] = [ | ||
| 625 | 625 | ], |
| 626 | 626 | ]; |
| 627 | 627 | |
| 628 | -/// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan). | |
| 629 | -pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; | |
| 630 | - | |
| 631 | 628 | /// 4x4 field scan: scan position -> raster index (Table 8-13, field scan). |
| 632 | 629 | pub const FIELD_4X4: [u8; 16] = [0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15]; |
| 633 | 630 | |
| @@ -640,7 +637,7 @@ pub const FIELD_8X8: [u8; 64] = [ | ||
| 640 | 637 | |
| 641 | 638 | /// 8x8 zig-zag scan: scan position -> raster index (Table 8-14, frame scan). |
| 642 | 639 | /// Shared with the scaling-list parser, which reads the same scan. |
| 643 | -pub use ec_h264_syntax::sps::ZIGZAG_8X8; | |
| 640 | +pub use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; | |
| 644 | 641 | |
| 645 | 642 | /// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock |
| 646 | 643 | /// (spec 6.4.3 inverse 4x4 luma block scan). |
crates/ec-h264/tests/conformance.rsmodified+18 -309
| @@ -6,72 +6,13 @@ | ||
| 6 | 6 | //! frame) — ffmpeg-independent. |
| 7 | 7 | //! 2. `ffmpeg -i <stream> -frames:v 1` raw output, cross-checked when the |
| 8 | 8 | //! binary is present. |
| 9 | -//! | |
| 10 | -//! The same binary hosts the zero-allocation proof and the ns/MB | |
| 11 | -//! measurement so the crate keeps a single integration-test link unit. | |
| 12 | - | |
| 13 | -use std::alloc::System; | |
| 14 | -use std::sync::Once; | |
| 15 | 9 | |
| 16 | -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; | |
| 17 | -use std::cell::Cell; | |
| 18 | 10 | use std::path::{Path, PathBuf}; |
| 19 | -use std::sync::atomic::{AtomicU64, Ordering}; | |
| 20 | 11 | |
| 21 | 12 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 22 | 13 | use ec_core::{Buf, Frame, Packet, TimeBase}; |
| 23 | 14 | use ec_h264::{Decoder, Error, H264Decoder, NalOutcome}; |
| 24 | 15 | |
| 25 | -// --------------------------------------------------------------------------- | |
| 26 | -// Counting allocator: proves the steady-state decode loop allocates nothing. | |
| 27 | -// Lives in the test binary only — the shipped crates have no allocator games. | |
| 28 | -// --------------------------------------------------------------------------- | |
| 29 | - | |
| 30 | -struct CountingAlloc; | |
| 31 | - | |
| 32 | -static ALLOCS: AtomicU64 = AtomicU64::new(0); | |
| 33 | - | |
| 34 | -std::thread_local! { | |
| 35 | - /// Only the test thread that armed the counter is counted — other test | |
| 36 | - /// threads (and their ffmpeg child plumbing) allocate freely. | |
| 37 | - static COUNTING_HERE: Cell<bool> = const { Cell::new(false) }; | |
| 38 | -} | |
| 39 | - | |
| 40 | -fn counting_here() -> bool { | |
| 41 | - COUNTING_HERE.try_with(Cell::get).unwrap_or(false) | |
| 42 | -} | |
| 43 | - | |
| 44 | -impl AllocationTracker for CountingAlloc { | |
| 45 | - fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { | |
| 46 | - if counting_here() { | |
| 47 | - ALLOCS.fetch_add(1, Ordering::Relaxed); | |
| 48 | - } | |
| 49 | - } | |
| 50 | - fn deallocated( | |
| 51 | - &self, | |
| 52 | - _addr: usize, | |
| 53 | - _object_size: usize, | |
| 54 | - _wrapped: usize, | |
| 55 | - _source: AllocationGroupId, | |
| 56 | - _current: AllocationGroupId, | |
| 57 | - ) { | |
| 58 | - } | |
| 59 | -} | |
| 60 | - | |
| 61 | -#[global_allocator] | |
| 62 | -static A: Allocator<System> = Allocator::system(); | |
| 63 | - | |
| 64 | -/// Installs the tracker once; every test that arms the counter calls this first. | |
| 65 | -fn install_counter() { | |
| 66 | - static ONCE: Once = Once::new(); | |
| 67 | - ONCE.call_once(|| { | |
| 68 | - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); | |
| 69 | - AllocationRegistry::enable_tracking(); | |
| 70 | - }); | |
| 71 | -} | |
| 72 | - | |
| 73 | -// --------------------------------------------------------------------------- | |
| 74 | - | |
| 75 | 16 | fn vectors_dir() -> PathBuf { |
| 76 | 17 | ec_testkit::fixture("vectors/h264-jvt") |
| 77 | 18 | } |
| @@ -383,235 +324,6 @@ fn jvt_cavlc_first_idr_bit_exact() { | ||
| 383 | 324 | ); |
| 384 | 325 | } |
| 385 | 326 | |
| 386 | -/// Steady-state slice decoding performs zero heap allocations. | |
| 387 | -/// | |
| 388 | -/// After a warm-up pass the picture pool, every per-picture array and the | |
| 389 | -/// parameter-set store are all sized, so decoding the same stream again must | |
| 390 | -/// not allocate at all: not per macroblock, not per slice, not per picture. | |
| 391 | -/// Emitting a frame is measured separately and *does* allocate — it hands the | |
| 392 | -/// caller owned planes — which also proves the counter is alive. | |
| 393 | -#[test] | |
| 394 | -fn steady_state_decode_loop_zero_alloc() { | |
| 395 | - install_counter(); | |
| 396 | - let base = vectors_dir(); | |
| 397 | - // One stream per entropy coder, and one with B slices and multiple | |
| 398 | - // reference frames so the decoded picture buffer really recycles pictures. | |
| 399 | - for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B"] { | |
| 400 | - let Some(stream) = find_stream(&base.join(name)) else { | |
| 401 | - continue; | |
| 402 | - }; | |
| 403 | - let bytes = std::fs::read(stream).unwrap(); | |
| 404 | - let mut dec = Decoder::new(); | |
| 405 | - let drive = |dec: &mut Decoder, count: bool| -> usize { | |
| 406 | - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); | |
| 407 | - let mut frames = 0usize; | |
| 408 | - for nal in &nals { | |
| 409 | - if count { | |
| 410 | - COUNTING_HERE.with(|c| c.set(true)); | |
| 411 | - } | |
| 412 | - let outcome = dec.push_nal(nal); | |
| 413 | - if count { | |
| 414 | - COUNTING_HERE.with(|c| c.set(false)); | |
| 415 | - } | |
| 416 | - match outcome { | |
| 417 | - Ok(ec_h264::NalOutcome::PictureBoundary) => { | |
| 418 | - dec.end_picture().expect("end_picture"); | |
| 419 | - dec.push_nal(nal).expect("re-push"); | |
| 420 | - } | |
| 421 | - Ok(_) => {} | |
| 422 | - Err(e) => panic!("{name}: {e}"), | |
| 423 | - } | |
| 424 | - while dec.next_frame().is_some() { | |
| 425 | - frames += 1; | |
| 426 | - } | |
| 427 | - } | |
| 428 | - dec.flush().expect("flush"); | |
| 429 | - while dec.next_frame().is_some() { | |
| 430 | - frames += 1; | |
| 431 | - } | |
| 432 | - frames | |
| 433 | - }; | |
| 434 | - // Warm-up: every reusable buffer reaches its final size. | |
| 435 | - let warm = drive(&mut dec, false); | |
| 436 | - assert!(warm > 1, "{name}: only {warm} frames decoded"); | |
| 437 | - dec.reset_pictures(); | |
| 438 | - | |
| 439 | - ALLOCS.store(0, Ordering::SeqCst); | |
| 440 | - let again = drive(&mut dec, true); | |
| 441 | - let n = ALLOCS.load(Ordering::SeqCst); | |
| 442 | - assert_eq!( | |
| 443 | - again, warm, | |
| 444 | - "{name}: frame count changed on the second pass" | |
| 445 | - ); | |
| 446 | - assert_eq!( | |
| 447 | - n, 0, | |
| 448 | - "{name}: steady-state slice decode allocated {n} times" | |
| 449 | - ); | |
| 450 | - } | |
| 451 | - | |
| 452 | - // Sanity: the counter is alive — emitting a frame does allocate. | |
| 453 | - let bytes = std::fs::read(find_stream(&base.join("BA1_Sony_D")).unwrap()).unwrap(); | |
| 454 | - let mut dec = Decoder::new(); | |
| 455 | - let _ = dec.decode_first_idr(&bytes).expect("decode"); | |
| 456 | - ALLOCS.store(0, Ordering::SeqCst); | |
| 457 | - COUNTING_HERE.with(|c| c.set(true)); | |
| 458 | - let frame = dec.frame().expect("frame"); | |
| 459 | - COUNTING_HERE.with(|c| c.set(false)); | |
| 460 | - assert!(frame.width > 0); | |
| 461 | - assert!( | |
| 462 | - ALLOCS.load(Ordering::SeqCst) > 0, | |
| 463 | - "allocation counter appears dead" | |
| 464 | - ); | |
| 465 | -} | |
| 466 | - | |
| 467 | -/// Decode-rate measurement: ns per macroblock and Mpx/s, printed for the perf | |
| 468 | -/// report. Run with `--nocapture` to see it. Uses the steady-state path | |
| 469 | -/// (buffers warm) like a playback loop would. | |
| 470 | -/// | |
| 471 | -/// Both halves matter: the intra measurement is what the previous release | |
| 472 | -/// reported, and the whole-sequence one is what playback actually costs, since | |
| 473 | -/// a real stream is almost all inter pictures. | |
| 474 | -#[test] | |
| 475 | -fn ns_per_macroblock_measurement() { | |
| 476 | - let base = vectors_dir(); | |
| 477 | - for name in [ | |
| 478 | - "BA1_Sony_D", | |
| 479 | - "CI_MW_D", | |
| 480 | - "NL1_Sony_D", | |
| 481 | - "CABA1_SVA_B", | |
| 482 | - "CABA3_SVA_B", | |
| 483 | - ] { | |
| 484 | - let Some(stream) = find_stream(&base.join(name)) else { | |
| 485 | - continue; | |
| 486 | - }; | |
| 487 | - let bytes = std::fs::read(stream).unwrap(); | |
| 488 | - let mut dec = Decoder::new(); | |
| 489 | - let frame = dec.decode_first_idr(&bytes).expect("warm-up"); | |
| 490 | - let (w, h) = (frame.width as u64, frame.height as u64); | |
| 491 | - let mbs = (w.div_ceil(16)) * (h.div_ceil(16)); | |
| 492 | - let nals: Vec<&[u8]> = ec_h264_syntax::AnnexBIter::new(&bytes).collect(); | |
| 493 | - | |
| 494 | - let iters = 200u32; | |
| 495 | - let start = std::time::Instant::now(); | |
| 496 | - for _ in 0..iters { | |
| 497 | - for nal in &nals { | |
| 498 | - match dec.push_nal(nal) { | |
| 499 | - Ok(ec_h264::NalOutcome::PictureBoundary) => break, | |
| 500 | - Ok(_) => {} | |
| 501 | - Err(e) => panic!("{e}"), | |
| 502 | - } | |
| 503 | - } | |
| 504 | - dec.end_picture().expect("end_picture"); | |
| 505 | - } | |
| 506 | - let elapsed = start.elapsed(); | |
| 507 | - let ns_per_mb = elapsed.as_nanos() as f64 / f64::from(iters) / mbs as f64; | |
| 508 | - let mpx_s = (w * h) as f64 * f64::from(iters) / elapsed.as_secs_f64() / 1e6; | |
| 509 | - eprintln!( | |
| 510 | - "PERF {name}: {w}x{h}, {mbs} MBs, {ns_per_mb:.0} ns/MB, {mpx_s:.1} Mpx/s \ | |
| 511 | - (intra IDR, single thread, deblock included, output copy excluded)" | |
| 512 | - ); | |
| 513 | - } | |
| 514 | - perf_whole_sequence(); | |
| 515 | -} | |
| 516 | - | |
| 517 | -/// The same measurement over whole sequences, where inter prediction, the | |
| 518 | -/// decoded picture buffer and output all count. | |
| 519 | -fn perf_whole_sequence() { | |
| 520 | - let base = vectors_dir(); | |
| 521 | - for name in ["BA_MW_D", "CABA3_SVA_B", "MR1_BT_A"] { | |
| 522 | - let Some(stream) = find_stream(&base.join(name)) else { | |
| 523 | - continue; | |
| 524 | - }; | |
| 525 | - let bytes = std::fs::read(stream).unwrap(); | |
| 526 | - let Ok(warm) = decode_all(&bytes) else { | |
| 527 | - continue; | |
| 528 | - }; | |
| 529 | - if warm.is_empty() { | |
| 530 | - continue; | |
| 531 | - } | |
| 532 | - let frames = warm.len() as f64; | |
| 533 | - let start = std::time::Instant::now(); | |
| 534 | - let iters = 5u32; | |
| 535 | - for _ in 0..iters { | |
| 536 | - let _ = decode_all(&bytes).expect("decode"); | |
| 537 | - } | |
| 538 | - let elapsed = start.elapsed().as_secs_f64() / f64::from(iters); | |
| 539 | - // Every vector here is QCIF: 11 x 9 macroblocks. | |
| 540 | - let mbs = 99.0 * frames; | |
| 541 | - eprintln!( | |
| 542 | - "PERF {name}: {frames} frames, {:.0} ns/MB, {:.1} Mpx/s \ | |
| 543 | - (full sequence, single thread, deblock and output copy included)", | |
| 544 | - elapsed * 1e9 / mbs, | |
| 545 | - 176.0 * 144.0 * frames / elapsed / 1e6 | |
| 546 | - ); | |
| 547 | - } | |
| 548 | -} | |
| 549 | - | |
| 550 | -/// Corrupt-input smoke sweep (fuzz-lite, deterministic): single-byte | |
| 551 | -/// mutations and truncations of a real stream must produce `Err` or a frame, | |
| 552 | -/// never a panic. A cargo-fuzz target owns the deep search later (S18 lane | |
| 553 | -/// done-criterion); this keeps the invariant enforced in every test run. | |
| 554 | -#[test] | |
| 555 | -fn corrupt_streams_never_panic() { | |
| 556 | - let base = vectors_dir(); | |
| 557 | - // One stream per entropy coder, plus one with B slices and multiple | |
| 558 | - // references: CABAC's arithmetic decoder indexes context and coefficient | |
| 559 | - // arrays from stream-derived values, and inter prediction indexes the | |
| 560 | - // decoded picture buffer, the reference lists and the motion arrays from | |
| 561 | - // them too. All of it needs the same no-panic floor as the CAVLC tables. | |
| 562 | - for name in ["BA1_Sony_D", "CABA1_SVA_B", "CABA3_SVA_B", "BA_MW_D"] { | |
| 563 | - let Some(stream) = find_stream(&base.join(name)) else { | |
| 564 | - continue; | |
| 565 | - }; | |
| 566 | - corrupt_sweep(&std::fs::read(stream).unwrap()); | |
| 567 | - } | |
| 568 | -} | |
| 569 | - | |
| 570 | -/// Truncate and bit-flip `bytes` many ways; every decode must return, error or | |
| 571 | -/// succeed, and never panic. | |
| 572 | -fn corrupt_sweep(bytes: &[u8]) { | |
| 573 | - let bytes = bytes.to_vec(); | |
| 574 | - | |
| 575 | - // Truncations at prefix lengths spanning SPS/PPS/slice-header/slice-data. | |
| 576 | - for len in (0..bytes.len().min(4096)) | |
| 577 | - .step_by(37) | |
| 578 | - .chain([bytes.len() / 2]) | |
| 579 | - { | |
| 580 | - let mut dec = Decoder::new(); | |
| 581 | - let _ = dec.decode_first_idr(&bytes[..len]); | |
| 582 | - // Truncation must also be survivable on the full-sequence path, where | |
| 583 | - // a half-decoded picture meets the decoded picture buffer. | |
| 584 | - let _ = decode_all(&bytes[..len]); | |
| 585 | - } | |
| 586 | - // Single-byte corruptions: xor a walking pattern through the first 6KB | |
| 587 | - // (covers parameter sets and the first slices), plus scattered hits. | |
| 588 | - let mut xorshift = 0x243F_6A88u32; // deterministic PRNG, no rand dep | |
| 589 | - // Debug builds carry overflow checks but decode ~10x slower; a smaller | |
| 590 | - // sweep keeps the suite fast while release runs the full one. | |
| 591 | - let count = if cfg!(debug_assertions) { 400 } else { 2000 }; | |
| 592 | - let dense = count * 3 / 4; | |
| 593 | - for i in 0..count { | |
| 594 | - let mut m = bytes.clone(); | |
| 595 | - let pos = if i < dense { | |
| 596 | - i * 4 % m.len().min(6144) | |
| 597 | - } else { | |
| 598 | - xorshift ^= xorshift << 13; | |
| 599 | - xorshift ^= xorshift >> 17; | |
| 600 | - xorshift ^= xorshift << 5; | |
| 601 | - (xorshift as usize) % m.len() | |
| 602 | - }; | |
| 603 | - m[pos] ^= (0x5Bu8.wrapping_add(i as u8)).max(1); | |
| 604 | - let mut dec = Decoder::new(); | |
| 605 | - let _ = dec.decode_first_idr(&m); // must not panic; any Err is fine | |
| 606 | - if i % 8 == 0 { | |
| 607 | - // The whole-sequence path costs more, so it gets a thinner sweep; | |
| 608 | - // it is the one that exercises reference lists and marking with | |
| 609 | - // stream-derived indices. | |
| 610 | - let _ = decode_all(&m); | |
| 611 | - } | |
| 612 | - } | |
| 613 | -} | |
| 614 | - | |
| 615 | 327 | // --------------------------------------------------------------------------- |
| 616 | 328 | // ffmpeg-driven coverage: the JVT vectors are all QCIF, single-slice and coded |
| 617 | 329 | // at a handful of quantisers, which leaves most of the deblocking tables, every |
| @@ -1401,29 +1113,26 @@ fn switching_slices_are_refused_by_name() { | ||
| 1401 | 1113 | } |
| 1402 | 1114 | } |
| 1403 | 1115 | |
| 1404 | - | |
| 1405 | 1116 | /// Extract the video elementary stream of a real file as Annex B. |
| 1406 | 1117 | fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool { |
| 1407 | - run( | |
| 1408 | - &[ | |
| 1409 | - "-v", | |
| 1410 | - "error", | |
| 1411 | - "-y", | |
| 1412 | - "-i", | |
| 1413 | - &src.to_string_lossy(), | |
| 1414 | - "-map", | |
| 1415 | - "0:v:0", | |
| 1416 | - "-c", | |
| 1417 | - "copy", | |
| 1418 | - "-bsf:v", | |
| 1419 | - "h264_mp4toannexb", | |
| 1420 | - "-frames:v", | |
| 1421 | - &frames.to_string(), | |
| 1422 | - "-f", | |
| 1423 | - "h264", | |
| 1424 | - &dst.to_string_lossy(), | |
| 1425 | - ], | |
| 1426 | - ) | |
| 1118 | + run(&[ | |
| 1119 | + "-v", | |
| 1120 | + "error", | |
| 1121 | + "-y", | |
| 1122 | + "-i", | |
| 1123 | + &src.to_string_lossy(), | |
| 1124 | + "-map", | |
| 1125 | + "0:v:0", | |
| 1126 | + "-c", | |
| 1127 | + "copy", | |
| 1128 | + "-bsf:v", | |
| 1129 | + "h264_mp4toannexb", | |
| 1130 | + "-frames:v", | |
| 1131 | + &frames.to_string(), | |
| 1132 | + "-f", | |
| 1133 | + "h264", | |
| 1134 | + &dst.to_string_lossy(), | |
| 1135 | + ]) | |
| 1427 | 1136 | } |
| 1428 | 1137 | |
| 1429 | 1138 | #[test] |
crates/ec-h264/tests/it/common.rsmodified+46 -25
| @@ -1,28 +1,62 @@ | ||
| 1 | -//! Helpers shared by the merged integration-test modules: byte layouts, the | |
| 2 | -//! ffmpeg pipes and stream utilities that were identical in each file. | |
| 3 | - | |
| 4 | 1 | use std::path::{Path, PathBuf}; |
| 5 | 2 | |
| 6 | 3 | use ec_core::frame::{PixelFormat, VideoFrame}; |
| 4 | +use ec_h264::{Decoder, NalOutcome}; | |
| 7 | 5 | |
| 8 | -/// One decoded frame as planar bytes (16-bit little endian samples for High 10). | |
| 9 | -pub(super) fn frame_bytes(frame: &VideoFrame) -> Vec<u8> { | |
| 10 | - let bytes_per_sample = match frame.format { | |
| 11 | - PixelFormat::I422 => 1, | |
| 12 | - PixelFormat::I210 => 2, | |
| 6 | +pub(super) fn layout(f: PixelFormat) -> (usize, usize, usize) { | |
| 7 | + match f { | |
| 8 | + PixelFormat::I444 => (1, 1, 1), | |
| 9 | + PixelFormat::I410 => (2, 1, 1), | |
| 10 | + PixelFormat::I422 => (1, 2, 1), | |
| 11 | + PixelFormat::I210 => (2, 2, 1), | |
| 12 | + PixelFormat::I420 => (1, 2, 2), | |
| 13 | + PixelFormat::I010 => (2, 2, 2), | |
| 13 | 14 | other => panic!("unexpected output format {other:?}"), |
| 14 | - }; | |
| 15 | + } | |
| 16 | +} | |
| 17 | + | |
| 18 | +pub(super) fn frame_bytes(frame: &VideoFrame) -> Vec<u8> { | |
| 19 | + let (bps, dx, dy) = layout(frame.format); | |
| 15 | 20 | let (w, h) = (frame.width as usize, frame.height as usize); |
| 16 | - let dims = [(w, h), (w.div_ceil(2), h), (w.div_ceil(2), h)]; | |
| 21 | + let (cw, ch) = (w.div_ceil(dx), h.div_ceil(dy)); | |
| 17 | 22 | let mut out = Vec::new(); |
| 18 | - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { | |
| 23 | + for (plane, (pw, ph)) in frame.planes.iter().zip([(w, h), (cw, ch), (cw, ch)]) { | |
| 19 | 24 | for y in 0..ph { |
| 20 | - out.extend_from_slice(plane.row(y, pw * bytes_per_sample).expect("plane row")); | |
| 25 | + out.extend_from_slice(plane.row(y, pw * bps).expect("plane row")); | |
| 21 | 26 | } |
| 22 | 27 | } |
| 23 | 28 | out |
| 24 | 29 | } |
| 25 | 30 | |
| 31 | +pub(super) fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, ec_h264::Error> { | |
| 32 | + let mut dec = Decoder::new(); | |
| 33 | + let mut frames = Vec::new(); | |
| 34 | + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 35 | + if dec.push_nal(nal)? == NalOutcome::PictureBoundary { | |
| 36 | + dec.end_picture()?; | |
| 37 | + dec.push_nal(nal)?; | |
| 38 | + } | |
| 39 | + while let Some(f) = dec.next_frame() { | |
| 40 | + frames.push(frame_bytes(&f)); | |
| 41 | + } | |
| 42 | + } | |
| 43 | + dec.flush()?; | |
| 44 | + while let Some(f) = dec.next_frame() { | |
| 45 | + frames.push(frame_bytes(&f)); | |
| 46 | + } | |
| 47 | + Ok(frames) | |
| 48 | +} | |
| 49 | + | |
| 50 | +pub(super) fn scratch(tag: &str) -> PathBuf { | |
| 51 | + let dir = std::env::temp_dir().join(format!( | |
| 52 | + "ec-h264-{tag}-{}-{:?}", | |
| 53 | + std::process::id(), | |
| 54 | + std::thread::current().id() | |
| 55 | + )); | |
| 56 | + std::fs::create_dir_all(&dir).unwrap(); | |
| 57 | + dir | |
| 58 | +} | |
| 59 | + | |
| 26 | 60 | pub(super) fn ffmpeg_frames(stream: &Path, pix_fmt: &str, frame_len: usize) -> Option<Vec<u8>> { |
| 27 | 61 | let out = ec_testkit::ffmpeg() |
| 28 | 62 | .args(["-v", "error", "-i"]) |
| @@ -63,19 +97,6 @@ pub(super) fn find_stream(dir: &Path) -> Option<PathBuf> { | ||
| 63 | 97 | fallback |
| 64 | 98 | } |
| 65 | 99 | |
| 66 | -/// (bytes per sample, chroma width divisor, chroma height divisor) | |
| 67 | -pub(super) fn layout(f: PixelFormat) -> (usize, usize, usize) { | |
| 68 | - match f { | |
| 69 | - PixelFormat::I444 => (1, 1, 1), | |
| 70 | - PixelFormat::I410 => (2, 1, 1), | |
| 71 | - PixelFormat::I422 => (1, 2, 1), | |
| 72 | - PixelFormat::I210 => (2, 2, 1), | |
| 73 | - PixelFormat::I420 => (1, 2, 2), | |
| 74 | - PixelFormat::I010 => (2, 2, 2), | |
| 75 | - other => panic!("unexpected output format {other:?}"), | |
| 76 | - } | |
| 77 | -} | |
| 78 | - | |
| 79 | 100 | pub(super) fn ffmpeg_pix_frames(stream: &Path, pix_fmt: &str) -> Option<Vec<u8>> { |
| 80 | 101 | let out = ec_testkit::ffmpeg() |
| 81 | 102 | .args(["-v", "error", "-f", "h264", "-i"]) |
crates/ec-h264/tests/it/encode.rsmodified+1 -918
| @@ -58,48 +58,6 @@ impl Clip { | ||
| 58 | 58 | } |
| 59 | 59 | } |
| 60 | 60 | |
| 61 | - /// Frame `t` without the per-sample noise field: smooth gradients, a | |
| 62 | - /// band of sinusoidal texture and a box translating by whole and | |
| 63 | - /// sub-sample amounts. `render`'s noise is incompressible, which makes a | |
| 64 | - /// rate-quality comparison read mostly as how willing each encoder is to | |
| 65 | - /// throw residual away; this one is content where prediction matters, the | |
| 66 | - /// half a rate-quality comparison is about. | |
| 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 | - // A slow diagonal ramp that drifts by 1.5 samples a frame, so | |
| 74 | - // motion is not always on the sample grid. | |
| 75 | - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; | |
| 76 | - // A textured band, the part a search has to actually find. | |
| 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 | 61 | fn view(&self) -> PictureView<'_> { |
| 104 | 62 | PictureView::i420(self.w as u32, self.h as u32, &self.y, &self.u, &self.v) |
| 105 | 63 | } |
| @@ -147,35 +105,6 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { | ||
| 147 | 105 | (y, u, v) |
| 148 | 106 | } |
| 149 | 107 | |
| 150 | -/// Mean squared error between two equal-length planes. | |
| 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 | -/// PSNR over all three planes, pooled by sample count the way x264 reports it: | |
| 163 | -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number | |
| 164 | -/// rewards an encoder for throwing chroma away — a chroma decision measured | |
| 165 | -/// against it will always say "code less" — so any decision that can move | |
| 166 | -/// chroma bits is read here instead. | |
| 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 | 108 | fn psnr(a: &[u8], b: &[u8]) -> f64 { |
| 180 | 109 | let mse: f64 = a |
| 181 | 110 | .iter() |
| @@ -193,82 +122,6 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 193 | 122 | } |
| 194 | 123 | } |
| 195 | 124 | |
| 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 | -/// A sample window with nothing in it (a film's black head, a fade) codes to | |
| 233 | -/// almost no bits and decodes back to the source exactly, so every point on | |
| 234 | -/// both curves sits at the PSNR cap and the BD number is a flat +0.000 that | |
| 235 | -/// reads like a measurement. Refuse such a window by name. | |
| 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 | 125 | /// The encoder's reconstruction and a decode of its bitstream agree sample for |
| 273 | 126 | /// sample, over a QP sweep, both presets, single and multi threaded. |
| 274 | 127 | #[test] |
| @@ -427,167 +280,6 @@ fn all_intra_when_the_gop_is_one() { | ||
| 427 | 280 | // absent, exactly like the conformance suite's ffmpeg cross-check. |
| 428 | 281 | // --------------------------------------------------------------------------- |
| 429 | 282 | |
| 430 | -/// Write `bytes` to `path` and PROVE the file on disk is exactly that long. | |
| 431 | -/// | |
| 432 | -/// lane-h26xpinloud: every write below used `std::fs::write(..).ok()?` and then | |
| 433 | -/// handed `path` to ffmpeg, which closes only the ERROR path. An Ok-but-short | |
| 434 | -/// write -- a filesystem that reports success and stores fewer bytes (ENOSPC on | |
| 435 | -/// a full mount, EFBIG under a size cap, a quota, a failed final flush) -- left | |
| 436 | -/// ffmpeg decoding a truncated stream, and the failure surfaced as a | |
| 437 | -/// plausible-looking wrong pixel or a shifted PSNR number, not as a write | |
| 438 | -/// failure. MEASURED: 1234 bytes written through a path that LOOKS like a | |
| 439 | -/// stream file in a scratch directory but whose filesystem accepts every byte | |
| 440 | -/// and stores none returns `Ok`, and the file on disk is 0 bytes. So the length | |
| 441 | -/// is checked here once, from the same `bytes.len()` the writer used, and any | |
| 442 | -/// shortfall carries the path, both counts, and the OS error -- or, for the | |
| 443 | -/// write that reported success and left a short file, the plain statement that | |
| 444 | -/// there was no OS error, which is exactly the case that used to print nothing. | |
| 445 | -/// | |
| 446 | -/// Returns the failure LINE rather than a bare bool, so the bail callers and any | |
| 447 | -/// panic caller all end on one format that cannot drift apart. The success path | |
| 448 | -/// is byte-identical to the old `fs::write`: same bytes, same path, truncate | |
| 449 | -/// then write. | |
| 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 | - // The count here is the file's REAL length, not what the writer had | |
| 454 | - // confirmed in hand: under a size cap the kernel stores everything up | |
| 455 | - // to the cap and only THEN returns the error, and `fs::write` confirms | |
| 456 | - // none of it. | |
| 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 | -/// The one failure line every short pin ends on: site, path, the bytes the file | |
| 488 | -/// holds vs the bytes owed, and the reason. | |
| 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 | -/// A pin whose shortfall is reported and then BAILED on, for a caller that | |
| 504 | -/// returns `None` today. Prints the same line [`pin_loud`] returns, so `None` | |
| 505 | -/// from here never reads as a plain "ffmpeg said no". | |
| 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 | - // The shape the four sites left open: a write that reports success and | |
| 516 | - // leaves a file of a different length. A symlink to /dev/null accepts every | |
| 517 | - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- | |
| 518 | - // a stream path, silently empty. | |
| 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 | - // The control: the same call on a real file succeeds and leaves every byte. | |
| 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 | - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores | |
| 542 | - // everything up to the cap and only then returns EFBIG. The line must carry | |
| 543 | - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count | |
| 544 | - // the writer confirmed, which is zero. | |
| 545 | - use std::process::Command; | |
| 546 | - let Ok(exe) = std::env::current_exe() else { | |
| 547 | - return; | |
| 548 | - }; | |
| 549 | - // SIGXFSZ's default action would kill the child before it can print; | |
| 550 | - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. | |
| 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 | -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under | |
| 574 | -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails | |
| 575 | -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. | |
| 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 | 283 | /// Decode an Annex B stream with ffmpeg, returning one I420 triple per picture. |
| 592 | 284 | fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Vec<Planes>> { |
| 593 | 285 | // Distinct per call, not per process: several #[test]s in this binary |
| @@ -601,7 +293,7 @@ fn ffmpeg_decode(stream: &[u8], w: usize, h: usize, extra: &[&str]) -> Option<Ve | ||
| 601 | 293 | stream.len(), |
| 602 | 294 | SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 603 | 295 | )); |
| 604 | - pin_or_bail("ffmpeg_decode", &path, stream)?; | |
| 296 | + std::fs::write(&path, stream).ok()?; | |
| 605 | 297 | let mut cmd = ec_testkit::ffmpeg(); |
| 606 | 298 | cmd.args(["-v", "error"]); |
| 607 | 299 | cmd.args(extra); |
| @@ -656,90 +348,6 @@ fn encode_clip( | ||
| 656 | 348 | (stream, recons, enc.transform_8x8_mbs()) |
| 657 | 349 | } |
| 658 | 350 | |
| 659 | -/// Flat gradients and glyph-like rectangles: the content the 8x8 transform | |
| 660 | -/// exists for. A 10-frame clip with the flag on must keep a clear positive | |
| 661 | -/// gain at equal bits, or cut bits at equal PSNR. | |
| 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 | - // A half-sample pan per frame: inter prediction has a residual to code. | |
| 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 | - // Curved shading: smooth but not a plane, so no 16x16 mode | |
| 672 | - // predicts it for free. | |
| 673 | - let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; | |
| 674 | - // Gentle texture with a 20-sample period: residual energy that | |
| 675 | - // spans more than a 4x4 block, which is what the 8x8 transform | |
| 676 | - // is for. | |
| 677 | - let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; | |
| 678 | - let shade = shade + tri(px) * tri(py) / 1.5; | |
| 679 | - // Glyph rows: 16x24 cells, stroke pattern hashed per cell. | |
| 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 | - // What the flag buys, not what the encoder is worth: both arms move when | |
| 724 | - // the paths under them change. It was re-pinned from 0.255 when the 4x4 | |
| 725 | - // luma path gained its coded_block_pattern group test, which is in the | |
| 726 | - // flag-off arm and improved it -- the same change moves the absolute | |
| 727 | - // synthetic comparison against x264 from -4.060 to -3.969 dB, and the | |
| 728 | - // flag-on arm barely at all, because a transform_8x8 macroblock does not | |
| 729 | - // go through that path. | |
| 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 | 351 | /// ffmpeg's decode of our stream is our reconstruction, sample for sample, |
| 744 | 352 | /// across a QP sweep and at a size that is not a multiple of a macroblock. |
| 745 | 353 | #[test] |
| @@ -968,516 +576,12 @@ fn open_h264_source( | ||
| 968 | 576 | panic!("{}: no video track found", path.to_string_lossy()); |
| 969 | 577 | } |
| 970 | 578 | |
| 971 | -/// The first `want` pictures a second apart from one of the user's media | |
| 972 | -/// files: demuxed by [`open_h264_source`] (MP4 or Matroska), decoded by this | |
| 973 | -/// crate, every Nth frame with N the source frame rate. Returns the | |
| 974 | -/// luma/chroma size and the pictures. | |
| 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 | - // Consecutive pictures by default. This used to take one picture a second, | |
| 985 | - // which measured an encoder on content it never sees: at a second apart | |
| 986 | - // nothing is predictable from the previous picture, so P slices went 93% | |
| 987 | - // intra on film and the inter path was never really under test. | |
| 988 | - // `EC_H264_CLIP_STRIDE` restores a wider spacing (`fps` takes one a | |
| 989 | - // second) for the deliberately-uncorrelated case. | |
| 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 | - // Pictures to pass over before sampling: the head of a film is titles and | |
| 999 | - // fades, which are not what a codec is measured on. | |
| 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 | -/// BD-PSNR of the `transform_8x8` flag (on by default) against flag-off on one real | |
| 1038 | -/// clip from the library, full size, over a QP sweep: the number the synthetic | |
| 1039 | -/// gate above cannot give, because the synthetic clip is content the flag wins | |
| 1040 | -/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; | |
| 1041 | -/// asserts nothing, so a regressing clip fails a gate, not the test run. | |
| 1042 | -/// | |
| 1043 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | |
| 1044 | -/// real_clip_t8x8_bd_psnr -- --ignored --nocapture | |
| 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; // the kept pictures are a second apart | |
| 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 | 579 | // --------------------------------------------------------------------------- |
| 1093 | 580 | // The encoder's rate-quality distance from x264: the survey's rank-1 gap, |
| 1094 | 581 | // because until this test existed the repo could measure our decoder against |
| 1095 | 582 | // every reference and our encoder against nothing but itself. |
| 1096 | 583 | // --------------------------------------------------------------------------- |
| 1097 | 584 | |
| 1098 | -/// Floor for [`bd_psnr_vs_x264`] on the synthetic clip. Our encoder measures | |
| 1099 | -/// -4.523 dB against x264 there (352x288, 24 pictures of | |
| 1100 | -/// `Clip::render_smooth`, both encoders at their own default effort: our | |
| 1101 | -/// `Preset::Fast`, x264's `-preset medium`). The floor is that number with | |
| 1102 | -/// room for platform noise, so the distance can shrink but not grow | |
| 1103 | -/// unnoticed; it is not a claim that -4.5 dB is fine. On a 3840x1608 clip | |
| 1104 | -/// from the library the same measurement reads -0.728 dB and on a 2560x1440 | |
| 1105 | -/// screen capture -0.500, so this synthetic number is the pessimistic end of | |
| 1106 | -/// the range and not the typical one. | |
| 1107 | -/// | |
| 1108 | -/// It moved -4.449 -> -4.523 when the intra-versus-inter decision started | |
| 1109 | -/// coding both branches for real. That change is worth 0.315 dB on the film | |
| 1110 | -/// clip and 0.564 on the screen capture, and takes fewer bits at every QP | |
| 1111 | -/// while doing it. This clip prefers a heavier rate term in that decision | |
| 1112 | -/// (see the sweep in `enc/mb.rs`), which the two real clips do not. | |
| 1113 | -/// | |
| 1114 | -/// It moved -4.523 -> -4.073 when inter luma levels started being chosen | |
| 1115 | -/// against the CABAC coder's own price for them (0.100 dB on the film clip, | |
| 1116 | -/// 0.029 on the screen capture). | |
| 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 | -/// Encode raw I420 pictures with x264 at constant QP, matched to what our | |
| 1127 | -/// encoder actually does: Main profile (CABAC, no 8x8 transform), one | |
| 1128 | -/// reference, no B pictures, the same GOP, and adaptive quantisation and psy | |
| 1129 | -/// off so both encoders spend bits by the same rule. Returns the Annex B | |
| 1130 | -/// stream. | |
| 1131 | -fn x264_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32, gop: u32) -> Option<Vec<u8>> { | |
| 1132 | - // Distinct per call, not per process: two #[test]s in this binary call | |
| 1133 | - // this on parallel threads with overlapping qp values, and a path keyed | |
| 1134 | - // only on qp lets one call's cleanup delete another's still-in-use file. | |
| 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 | - // EC_H264_X264_PRESET selects the reference preset; the DONE.md target is | |
| 1155 | - // measured against `veryfast`, the default stays `medium` for the older gates. | |
| 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 | - // ipratio/pbratio 1.0 matter: x264's constant-QP mode otherwise codes | |
| 1165 | - // I pictures at a lower QP than the one asked for, which reads as a | |
| 1166 | - // rate-quality win that is really a different quantiser. | |
| 1167 | - // EC_H264_X264_PARAMS appends to this list, which is how a single | |
| 1168 | - // reference feature gets attributed: running the sweep again with | |
| 1169 | - // `trellis=0` says how much of x264's lead is its rate-distortion | |
| 1170 | - // quantisation rather than its prediction. | |
| 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 | - // The value may or may not carry its own leading colon; | |
| 1177 | - // both spell the same thing. Passing it through would not: | |
| 1178 | - // ffmpeg drops the token after an empty one, so "::subme=1" | |
| 1179 | - // silently encodes at the preset's subme and the sweep | |
| 1180 | - // reads as "the feature does nothing". | |
| 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 | -/// BD-PSNR of our encoder against x264 at matched features over QP | |
| 1202 | -/// 22/26/30/34. Runs on the synthetic clip by default, so the number cannot | |
| 1203 | -/// rot behind an `#[ignore]`; point `EC_H264_CLIP` at a media file to measure | |
| 1204 | -/// the same thing on real content. | |
| 1205 | -/// | |
| 1206 | -/// Both curves are (bits, luma PSNR against the same source pictures), and | |
| 1207 | -/// both are measured on ffmpeg's decode of the stream rather than on an | |
| 1208 | -/// encoder's own reconstruction, so the two halves are read the same way. | |
| 1209 | -/// | |
| 1210 | -/// `EC_H264_GOP` sets the GOP of both encoders; 1 makes the comparison | |
| 1211 | -/// all-intra, which splits the gap between the intra path and the P pictures. | |
| 1212 | -/// | |
| 1213 | -/// `EC_H264_PRESET_BALANCED` runs our half of the comparison at | |
| 1214 | -/// `Preset::Balanced` instead of the default `Preset::Fast`, which separates | |
| 1215 | -/// what search effort buys from what the coder itself costs. | |
| 1216 | -/// | |
| 1217 | -/// `EC_H264_CLIP_SKIP` passes over that many pictures before sampling (film | |
| 1218 | -/// heads are titles and fades), and `EC_H264_CLIP_STRIDE` widens the spacing | |
| 1219 | -/// between the sampled pictures; both default to consecutive pictures from the | |
| 1220 | -/// start of the file. The measurements quoted through this crate that predate | |
| 1221 | -/// those two knobs were taken one picture a second, where nothing is | |
| 1222 | -/// predictable from the previous picture -- they are not comparable with the | |
| 1223 | -/// numbers taken since. | |
| 1224 | -/// | |
| 1225 | -/// cargo test --release -p ec-h264 --test encode bd_psnr_vs_x264 -- --nocapture | |
| 1226 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | |
| 1227 | -/// bd_psnr_vs_x264 -- --nocapture | |
| 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 | - // Measured the same way x264 is: on what a decoder shows, not on the | |
| 1268 | - // encoder's own reconstruction. The two are printed together because a | |
| 1269 | - // gap between them is a bug in one of the halves, not a rate-quality | |
| 1270 | - // result. | |
| 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 | - // The floor is calibrated on the synthetic clip; a clip of the user's is a | |
| 1378 | - // measurement, not a gate, because its content is not pinned. | |
| 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 | -/// Where our bits go against where x264's go, class by class, on the same | |
| 1389 | -/// sources at the same QP. Both streams are parsed by this crate's decoder, so | |
| 1390 | -/// the two accounts are the same measurement; the BD-PSNR gate says how much | |
| 1391 | -/// we overspend, this says on what. | |
| 1392 | -/// | |
| 1393 | -/// cargo test --release -p ec-h264 --test encode bit_account_vs_x264 -- --nocapture | |
| 1394 | -/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \ | |
| 1395 | -/// bit_account_vs_x264 -- --nocapture | |
| 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 | 585 | /// The partitions only `Preset::Balanced` searches, decoded by ffmpeg. |
| 1482 | 586 | /// |
| 1483 | 587 | /// The default preset codes every P macroblock as one 16x16 partition, so the |
| @@ -1486,7 +590,6 @@ fn bit_account_vs_x264() { | ||
| 1486 | 590 | #[test] |
| 1487 | 591 | fn balanced_partitions_decode_bit_exactly() { |
| 1488 | 592 | let (w, h) = (176, 144); |
| 1489 | - let mut shapes = ec_h264::MbShapes::default(); | |
| 1490 | 593 | for qp in [16, 26, 36] { |
| 1491 | 594 | let cavlc = qp == 26; // both entropy coders write sub_mb_type |
| 1492 | 595 | let (stream, recons, _) = encode_clip(w, h, 8, |cfg| { |
| @@ -1501,27 +604,7 @@ fn balanced_partitions_decode_bit_exactly() { | ||
| 1501 | 604 | assert_eq!(dec.1, rec.1, "qp {qp}: Cb of frame {i}"); |
| 1502 | 605 | assert_eq!(dec.2, rec.2, "qp {qp}: Cr of frame {i}"); |
| 1503 | 606 | } |
| 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 | 607 | } |
| 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 | 608 | } |
| 1526 | 609 | |
| 1527 | 610 | #[test] |
crates/ec-h264/tests/it/high10.rsmodified+5 -64
| @@ -8,57 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | use std::path::{Path, PathBuf}; |
| 10 | 10 | |
| 11 | -use ec_core::frame::{PixelFormat, VideoFrame}; | |
| 12 | -use ec_h264::{Decoder, NalOutcome}; | |
| 13 | - | |
| 14 | -/// One decoded frame as I010 bytes (little-endian 16-bit samples, planes | |
| 15 | -/// back to back), checking the format and plane geometry on the way. | |
| 16 | -fn frame_bytes(frame: &VideoFrame) -> Vec<u8> { | |
| 17 | - assert_eq!(frame.format, PixelFormat::I010, "High 10 comes out as I010"); | |
| 18 | - let (w, h) = (frame.width as usize, frame.height as usize); | |
| 19 | - let dims = [ | |
| 20 | - (w, h), | |
| 21 | - (w.div_ceil(2), h.div_ceil(2)), | |
| 22 | - (w.div_ceil(2), h.div_ceil(2)), | |
| 23 | - ]; | |
| 24 | - let mut out = Vec::new(); | |
| 25 | - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { | |
| 26 | - for y in 0..ph { | |
| 27 | - out.extend_from_slice(plane.row(y, pw * 2).expect("plane row")); | |
| 28 | - } | |
| 29 | - } | |
| 30 | - out | |
| 31 | -} | |
| 32 | - | |
| 33 | -fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, ec_h264::Error> { | |
| 34 | - let mut dec = Decoder::new(); | |
| 35 | - let mut frames = Vec::new(); | |
| 36 | - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 37 | - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { | |
| 38 | - dec.end_picture()?; | |
| 39 | - dec.push_nal(nal)?; | |
| 40 | - } | |
| 41 | - while let Some(f) = dec.next_frame() { | |
| 42 | - frames.push(frame_bytes(&f)); | |
| 43 | - } | |
| 44 | - } | |
| 45 | - dec.flush()?; | |
| 46 | - while let Some(f) = dec.next_frame() { | |
| 47 | - frames.push(frame_bytes(&f)); | |
| 48 | - } | |
| 49 | - Ok(frames) | |
| 50 | -} | |
| 51 | - | |
| 52 | -fn ffmpeg_frames(stream: &Path, frame_len: usize) -> Option<Vec<u8>> { | |
| 53 | - let out = ec_testkit::ffmpeg() | |
| 54 | - .args(["-v", "error", "-i"]) | |
| 55 | - .arg(stream) | |
| 56 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"]) | |
| 57 | - .output() | |
| 58 | - .ok()?; | |
| 59 | - (out.status.success() && !out.stdout.is_empty() && out.stdout.len() % frame_len == 0) | |
| 60 | - .then_some(out.stdout) | |
| 61 | -} | |
| 11 | +use super::common::{decode_all, ffmpeg_frames, frame_bytes, scratch}; | |
| 62 | 12 | |
| 63 | 13 | // ---- MD5 (RFC 1321), so the committed fixtures need no ffmpeg ---------------- |
| 64 | 14 | |
| @@ -142,16 +92,6 @@ fn committed_streams_match_ffmpeg_md5() { | ||
| 142 | 92 | |
| 143 | 93 | // ---- the libx264 sweep -------------------------------------------------------- |
| 144 | 94 | |
| 145 | -fn scratch() -> PathBuf { | |
| 146 | - let dir = std::env::temp_dir().join(format!( | |
| 147 | - "ec-h264-high10-{}-{:?}", | |
| 148 | - std::process::id(), | |
| 149 | - std::thread::current().id() | |
| 150 | - )); | |
| 151 | - std::fs::create_dir_all(&dir).unwrap(); | |
| 152 | - dir | |
| 153 | -} | |
| 154 | - | |
| 155 | 95 | struct Case { |
| 156 | 96 | tag: &'static str, |
| 157 | 97 | /// lavfi source and size. |
| @@ -203,13 +143,14 @@ fn encode(dir: &Path, c: &Case) -> Option<PathBuf> { | ||
| 203 | 143 | } |
| 204 | 144 | |
| 205 | 145 | fn check(c: &Case) -> Result<usize, String> { |
| 206 | - let dir = scratch(); | |
| 146 | + let dir = scratch("high10"); | |
| 207 | 147 | let stream = |
| 208 | 148 | encode(&dir, c).unwrap_or_else(|| panic!("{}: ffmpeg/libx264 10-bit cannot encode", c.tag)); |
| 209 | 149 | let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; |
| 210 | 150 | let ours = decode_all(&bytes).map_err(|e| format!("{}: {e}", c.tag))?; |
| 211 | 151 | let first = ours.first().ok_or("no frames decoded")?; |
| 212 | - let theirs = ffmpeg_frames(&stream, first.len()).ok_or("ffmpeg cannot decode")?; | |
| 152 | + let theirs = | |
| 153 | + ffmpeg_frames(&stream, "yuv420p10le", first.len()).ok_or("ffmpeg cannot decode")?; | |
| 213 | 154 | let _ = std::fs::remove_file(&stream); |
| 214 | 155 | if theirs.len() != first.len() * ours.len() { |
| 215 | 156 | return Err(format!( |
| @@ -242,7 +183,7 @@ fn sweep(cases: &[Case]) { | ||
| 242 | 183 | Err(e) => failed.push(e), |
| 243 | 184 | } |
| 244 | 185 | } |
| 245 | - let _ = std::fs::remove_dir_all(scratch()); | |
| 186 | + let _ = std::fs::remove_dir_all(scratch("high10")); | |
| 246 | 187 | assert!( |
| 247 | 188 | failed.is_empty(), |
| 248 | 189 | "High 10 mismatches:\n{}", |
crates/ec-h264/tests/it/high422.rsmodified+21 -48
| @@ -6,38 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | use std::path::{Path, PathBuf}; |
| 8 | 8 | |
| 9 | -use ec_h264::{Decoder, NalOutcome}; | |
| 10 | - | |
| 11 | -use super::common::{escape, ffmpeg_frames, frame_bytes}; | |
| 12 | - | |
| 13 | -fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, ec_h264::Error> { | |
| 14 | - let mut dec = Decoder::new(); | |
| 15 | - let mut frames = Vec::new(); | |
| 16 | - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 17 | - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { | |
| 18 | - dec.end_picture()?; | |
| 19 | - dec.push_nal(nal)?; | |
| 20 | - } | |
| 21 | - while let Some(f) = dec.next_frame() { | |
| 22 | - frames.push(frame_bytes(&f)); | |
| 23 | - } | |
| 24 | - } | |
| 25 | - dec.flush()?; | |
| 26 | - while let Some(f) = dec.next_frame() { | |
| 27 | - frames.push(frame_bytes(&f)); | |
| 28 | - } | |
| 29 | - Ok(frames) | |
| 30 | -} | |
| 31 | - | |
| 32 | -fn scratch() -> PathBuf { | |
| 33 | - let dir = std::env::temp_dir().join(format!( | |
| 34 | - "ec-h264-hi422-{}-{:?}", | |
| 35 | - std::process::id(), | |
| 36 | - std::thread::current().id() | |
| 37 | - )); | |
| 38 | - std::fs::create_dir_all(&dir).unwrap(); | |
| 39 | - dir | |
| 40 | -} | |
| 9 | +use super::common::{decode_all, escape, ffmpeg_frames, scratch}; | |
| 41 | 10 | |
| 42 | 11 | struct Case { |
| 43 | 12 | tag: &'static str, |
| @@ -92,7 +61,7 @@ fn encode(dir: &Path, c: &Case) -> Option<PathBuf> { | ||
| 92 | 61 | } |
| 93 | 62 | |
| 94 | 63 | fn check(c: &Case) -> Result<usize, String> { |
| 95 | - let dir = scratch(); | |
| 64 | + let dir = scratch("hi422"); | |
| 96 | 65 | let stream = encode(&dir, c) |
| 97 | 66 | .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); |
| 98 | 67 | let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; |
| @@ -132,7 +101,7 @@ fn sweep(cases: &[Case]) { | ||
| 132 | 101 | Err(e) => failed.push(e), |
| 133 | 102 | } |
| 134 | 103 | } |
| 135 | - let _ = std::fs::remove_dir_all(scratch()); | |
| 104 | + let _ = std::fs::remove_dir_all(scratch("hi422")); | |
| 136 | 105 | assert!( |
| 137 | 106 | failed.is_empty(), |
| 138 | 107 | "4:2:2 mismatches:\n{}", |
| @@ -332,21 +301,17 @@ const SMALL: &[Case] = &[ | ||
| 332 | 301 | ]; |
| 333 | 302 | |
| 334 | 303 | /// Every case at 8 bits, progressive. |
| 335 | -#[test] | |
| 336 | -fn x264_hi422_progressive_8bit() { | |
| 337 | - sweep(SMALL); | |
| 304 | +fn progressive_8bit_cases() -> Vec<Case> { | |
| 305 | + SMALL.iter().map(|c| Case { ..*c }).collect() | |
| 338 | 306 | } |
| 339 | 307 | |
| 340 | 308 | /// The same at 10 bits. |
| 341 | -#[test] | |
| 342 | -fn x264_hi422_progressive_10bit() { | |
| 343 | - let cases: Vec<Case> = SMALL.iter().map(|c| ten(Case { ..*c })).collect(); | |
| 344 | - sweep(&cases); | |
| 309 | +fn progressive_10bit_cases() -> Vec<Case> { | |
| 310 | + SMALL.iter().map(|c| ten(Case { ..*c })).collect() | |
| 345 | 311 | } |
| 346 | 312 | |
| 347 | 313 | /// MBAFF at 8 and 10 bits. |
| 348 | -#[test] | |
| 349 | -fn x264_hi422_mbaff() { | |
| 314 | +fn mbaff_cases() -> Vec<Case> { | |
| 350 | 315 | let mut cases: Vec<Case> = Vec::new(); |
| 351 | 316 | for (i, c) in SMALL.iter().enumerate() { |
| 352 | 317 | // Every other case keeps the sweep quick; the rest run progressive. |
| @@ -360,13 +325,12 @@ fn x264_hi422_mbaff() { | ||
| 360 | 325 | format!("mbaff-{}{}", c.tag, if c.ten_bit { "-10" } else { "" }).into_boxed_str(), |
| 361 | 326 | ); |
| 362 | 327 | } |
| 363 | - sweep(&cases); | |
| 328 | + cases | |
| 364 | 329 | } |
| 365 | 330 | |
| 366 | 331 | /// 1920x1080 intra and long-GOP, progressive and MBAFF (slow). |
| 367 | -#[test] | |
| 368 | -fn x264_hi422_hd() { | |
| 369 | - sweep(&[ | |
| 332 | +fn hd_cases() -> Vec<Case> { | |
| 333 | + vec![ | |
| 370 | 334 | case("hd-i-cabac", "testsrc2", "1920x1080", 2, "keyint=1"), |
| 371 | 335 | case( |
| 372 | 336 | "hd-b-cabac", |
| @@ -403,7 +367,7 @@ fn x264_hi422_hd() { | ||
| 403 | 367 | 2, |
| 404 | 368 | "keyint=1:cabac=0", |
| 405 | 369 | ))), |
| 406 | - ]); | |
| 370 | + ] | |
| 407 | 371 | } |
| 408 | 372 | |
| 409 | 373 | // ---- I_PCM in 4:2:2 (x264 never writes one) ---------------------------- |
| @@ -530,3 +494,12 @@ fn hi422_pcm_macroblocks_round_trip() { | ||
| 530 | 494 | assert_eq!(bytes, &expected, "{bd}-bit I_PCM 4:2:2"); |
| 531 | 495 | } |
| 532 | 496 | } |
| 497 | + | |
| 498 | +#[test] | |
| 499 | +fn x264_hi422_family() { | |
| 500 | + let mut cases = progressive_8bit_cases(); | |
| 501 | + cases.extend(progressive_10bit_cases()); | |
| 502 | + cases.extend(mbaff_cases()); | |
| 503 | + cases.extend(hd_cases()); | |
| 504 | + sweep(&cases); | |
| 505 | +} |
crates/ec-h264/tests/it/high444.rsmodified+39 -43
| @@ -15,7 +15,7 @@ use std::path::{Path, PathBuf}; | ||
| 15 | 15 | use ec_core::frame::{PixelFormat, VideoFrame}; |
| 16 | 16 | use ec_h264::{Decoder, NalOutcome}; |
| 17 | 17 | |
| 18 | -use super::common::{ffmpeg_pix_frames, layout}; | |
| 18 | +use super::common::{ffmpeg_pix_frames, layout, scratch}; | |
| 19 | 19 | |
| 20 | 20 | /// One decoded frame as planar bytes (16-bit little endian above 8 bits). |
| 21 | 21 | fn frame_bytes(frame: &VideoFrame) -> (Vec<u8>, PixelFormat) { |
| @@ -50,16 +50,6 @@ fn decode_all(bytes: &[u8]) -> Result<Vec<(Vec<u8>, PixelFormat)>, ec_h264::Erro | ||
| 50 | 50 | Ok(frames) |
| 51 | 51 | } |
| 52 | 52 | |
| 53 | -fn scratch() -> PathBuf { | |
| 54 | - let dir = std::env::temp_dir().join(format!( | |
| 55 | - "ec-h264-hi444-{}-{:?}", | |
| 56 | - std::process::id(), | |
| 57 | - std::thread::current().id() | |
| 58 | - )); | |
| 59 | - std::fs::create_dir_all(&dir).unwrap(); | |
| 60 | - dir | |
| 61 | -} | |
| 62 | - | |
| 63 | 53 | #[derive(Clone, Copy)] |
| 64 | 54 | struct Case { |
| 65 | 55 | tag: &'static str, |
| @@ -114,7 +104,7 @@ fn encode(dir: &Path, c: &Case) -> Option<PathBuf> { | ||
| 114 | 104 | } |
| 115 | 105 | |
| 116 | 106 | fn check(c: &Case) -> Result<usize, String> { |
| 117 | - let dir = scratch(); | |
| 107 | + let dir = scratch("hi444"); | |
| 118 | 108 | let stream = encode(&dir, c) |
| 119 | 109 | .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); |
| 120 | 110 | let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; |
| @@ -186,7 +176,7 @@ fn sweep(label: &str, cases: &[Case]) { | ||
| 186 | 176 | Err(e) => failed.push(e), |
| 187 | 177 | } |
| 188 | 178 | } |
| 189 | - let _ = std::fs::remove_dir_all(scratch()); | |
| 179 | + let _ = std::fs::remove_dir_all(scratch("hi444")); | |
| 190 | 180 | assert!( |
| 191 | 181 | failed.is_empty(), |
| 192 | 182 | "{label} mismatches:\n{}", |
| @@ -431,16 +421,14 @@ fn all(pix: &'static str, prefix: &str, mbaff: bool, step: usize) -> Vec<Case> { | ||
| 431 | 421 | .collect() |
| 432 | 422 | } |
| 433 | 423 | |
| 434 | -#[test] | |
| 435 | -fn x264_hi444_8bit() { | |
| 436 | - sweep("4:4:4 8-bit", &all("yuv444p", "", false, 1)); | |
| 424 | +fn hi444_8bit_cases() -> Vec<Case> { | |
| 425 | + all("yuv444p", "", false, 1) | |
| 437 | 426 | } |
| 438 | 427 | |
| 439 | -#[test] | |
| 440 | -fn x264_hi444_mbaff() { | |
| 428 | +fn hi444_mbaff_cases() -> Vec<Case> { | |
| 441 | 429 | let mut cases = all("yuv444p", "mbaff-", true, 2); |
| 442 | 430 | cases.extend(all("yuv444p10le", "mbaff-", true, 4)); |
| 443 | - sweep("4:4:4 MBAFF", &cases); | |
| 431 | + cases | |
| 444 | 432 | } |
| 445 | 433 | |
| 446 | 434 | // ---- lossless (qpprime_y_zero_transform_bypass) ---- |
| @@ -539,19 +527,16 @@ fn lossless(pix: &'static str) -> Vec<Case> { | ||
| 539 | 527 | LOSSLESS.iter().map(|c| with(c, pix, "", false)).collect() |
| 540 | 528 | } |
| 541 | 529 | |
| 542 | -#[test] | |
| 543 | -fn x264_lossless_444_8bit() { | |
| 544 | - sweep("lossless 4:4:4", &lossless("yuv444p")); | |
| 530 | +fn lossless_444_8bit_cases() -> Vec<Case> { | |
| 531 | + lossless("yuv444p") | |
| 545 | 532 | } |
| 546 | 533 | |
| 547 | -#[test] | |
| 548 | -fn x264_lossless_444_10bit() { | |
| 549 | - sweep("lossless 4:4:4 10-bit", &lossless("yuv444p10le")); | |
| 534 | +fn lossless_444_10bit_cases() -> Vec<Case> { | |
| 535 | + lossless("yuv444p10le") | |
| 550 | 536 | } |
| 551 | 537 | |
| 552 | 538 | /// Profile 244 lossless also carries 4:2:0 and 4:2:2. |
| 553 | -#[test] | |
| 554 | -fn x264_lossless_420_422() { | |
| 539 | +fn lossless_420_422_cases() -> Vec<Case> { | |
| 555 | 540 | let mut cases: Vec<Case> = Vec::new(); |
| 556 | 541 | for (i, c) in LOSSLESS.iter().enumerate() { |
| 557 | 542 | if i % 2 == 0 { |
| @@ -563,34 +548,30 @@ fn x264_lossless_420_422() { | ||
| 563 | 548 | cases.push(with(c, "yuv422p10le", "", false)); |
| 564 | 549 | } |
| 565 | 550 | } |
| 566 | - sweep("lossless 4:2:0 / 4:2:2", &cases); | |
| 551 | + cases | |
| 567 | 552 | } |
| 568 | 553 | |
| 569 | -#[test] | |
| 570 | -fn x264_lossless_mbaff() { | |
| 554 | +fn lossless_mbaff_cases() -> Vec<Case> { | |
| 571 | 555 | let cases: Vec<Case> = LOSSLESS |
| 572 | 556 | .iter() |
| 573 | 557 | .enumerate() |
| 574 | 558 | .filter(|(i, _)| i % 4 == 0) |
| 575 | 559 | .map(|(_, c)| with(c, "yuv444p", "mbaff-", true)) |
| 576 | 560 | .collect(); |
| 577 | - sweep("lossless MBAFF", &cases); | |
| 561 | + cases | |
| 578 | 562 | } |
| 579 | 563 | |
| 580 | 564 | // ---- monochrome ---- |
| 581 | 565 | |
| 582 | -#[test] | |
| 583 | -fn x264_monochrome_8bit() { | |
| 584 | - sweep("gray", &all("gray", "", false, 1)); | |
| 566 | +fn monochrome_8bit_cases() -> Vec<Case> { | |
| 567 | + all("gray", "", false, 1) | |
| 585 | 568 | } |
| 586 | 569 | |
| 587 | -#[test] | |
| 588 | -fn x264_monochrome_10bit() { | |
| 589 | - sweep("gray10le", &all("gray10le", "", false, 2)); | |
| 570 | +fn monochrome_10bit_cases() -> Vec<Case> { | |
| 571 | + all("gray10le", "", false, 2) | |
| 590 | 572 | } |
| 591 | 573 | |
| 592 | -#[test] | |
| 593 | -fn x264_monochrome_mbaff_and_lossless() { | |
| 574 | +fn monochrome_mbaff_and_lossless_cases() -> Vec<Case> { | |
| 594 | 575 | let mut cases = all("gray", "mbaff-", true, 6); |
| 595 | 576 | cases.extend( |
| 596 | 577 | LOSSLESS |
| @@ -599,12 +580,11 @@ fn x264_monochrome_mbaff_and_lossless() { | ||
| 599 | 580 | .filter(|(i, _)| i % 3 == 0) |
| 600 | 581 | .map(|(_, c)| with(c, "gray", "", false)), |
| 601 | 582 | ); |
| 602 | - sweep("gray MBAFF / lossless", &cases); | |
| 583 | + cases | |
| 603 | 584 | } |
| 604 | 585 | |
| 605 | 586 | /// 1280x720 (slow). |
| 606 | -#[test] | |
| 607 | -fn x264_hi444_hd() { | |
| 587 | +fn hi444_hd_cases() -> Vec<Case> { | |
| 608 | 588 | let base = [ |
| 609 | 589 | case("hd-i-cabac", "testsrc2", "1280x720", 2, "keyint=1"), |
| 610 | 590 | case( |
| @@ -630,5 +610,21 @@ fn x264_hi444_hd() { | ||
| 630 | 610 | } |
| 631 | 611 | cases.push(with(&base[0], "gray", "", false)); |
| 632 | 612 | cases.push(with(&base[0], "yuv444p", "mbaff-", true)); |
| 633 | - sweep("4:4:4 HD", &cases); | |
| 613 | + cases | |
| 614 | +} | |
| 615 | + | |
| 616 | +#[test] | |
| 617 | +fn x264_hi444_family() { | |
| 618 | + let mut cases = Vec::new(); | |
| 619 | + cases.extend(hi444_8bit_cases()); | |
| 620 | + cases.extend(hi444_mbaff_cases()); | |
| 621 | + cases.extend(lossless_444_8bit_cases()); | |
| 622 | + cases.extend(lossless_444_10bit_cases()); | |
| 623 | + cases.extend(lossless_420_422_cases()); | |
| 624 | + cases.extend(lossless_mbaff_cases()); | |
| 625 | + cases.extend(monochrome_8bit_cases()); | |
| 626 | + cases.extend(monochrome_10bit_cases()); | |
| 627 | + cases.extend(monochrome_mbaff_and_lossless_cases()); | |
| 628 | + cases.extend(hi444_hd_cases()); | |
| 629 | + sweep("x264 4:4:4, lossless and monochrome", &cases); | |
| 634 | 630 | } |
crates/ec-h264/tests/it/main.rsmodified+0 -4
| @@ -1,8 +1,5 @@ | ||
| 1 | 1 | //! ec-h264 integration tests, one binary. Each module is one former |
| 2 | 2 | //! `tests/<name>.rs` file; the test path is `<module>::<test>`. |
| 3 | -//! | |
| 4 | -//! `conformance.rs` stays a separate binary: it installs a `#[global_allocator]` | |
| 5 | -//! and measures wall-clock speed. | |
| 6 | 3 | |
| 7 | 4 | #![forbid(unsafe_code)] |
| 8 | 5 | |
| @@ -16,5 +13,4 @@ mod high444; | ||
| 16 | 13 | mod high444_jvt; |
| 17 | 14 | mod interlaced; |
| 18 | 15 | mod mbaff_x264; |
| 19 | -mod no_panic; | |
| 20 | 16 | mod refusals; |
crates/ec-h264/tests/it/mbaff_x264.rsmodified+25 -73
| @@ -6,61 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | use std::path::{Path, PathBuf}; |
| 8 | 8 | |
| 9 | -use ec_core::frame::{PixelFormat, VideoFrame}; | |
| 10 | -use ec_h264::{Decoder, NalOutcome}; | |
| 11 | - | |
| 12 | -use super::common::ffmpeg_frames; | |
| 13 | - | |
| 14 | -/// One decoded frame as planar bytes (16-bit little endian samples for High 10). | |
| 15 | -fn frame_bytes(frame: &VideoFrame) -> Vec<u8> { | |
| 16 | - let bytes_per_sample = match frame.format { | |
| 17 | - PixelFormat::I420 => 1, | |
| 18 | - PixelFormat::I010 => 2, | |
| 19 | - other => panic!("unexpected output format {other:?}"), | |
| 20 | - }; | |
| 21 | - let (w, h) = (frame.width as usize, frame.height as usize); | |
| 22 | - let dims = [ | |
| 23 | - (w, h), | |
| 24 | - (w.div_ceil(2), h.div_ceil(2)), | |
| 25 | - (w.div_ceil(2), h.div_ceil(2)), | |
| 26 | - ]; | |
| 27 | - let mut out = Vec::new(); | |
| 28 | - for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { | |
| 29 | - for y in 0..ph { | |
| 30 | - out.extend_from_slice(plane.row(y, pw * bytes_per_sample).expect("plane row")); | |
| 31 | - } | |
| 32 | - } | |
| 33 | - out | |
| 34 | -} | |
| 35 | - | |
| 36 | -fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, ec_h264::Error> { | |
| 37 | - let mut dec = Decoder::new(); | |
| 38 | - let mut frames = Vec::new(); | |
| 39 | - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 40 | - if dec.push_nal(nal)? == NalOutcome::PictureBoundary { | |
| 41 | - dec.end_picture()?; | |
| 42 | - dec.push_nal(nal)?; | |
| 43 | - } | |
| 44 | - while let Some(f) = dec.next_frame() { | |
| 45 | - frames.push(frame_bytes(&f)); | |
| 46 | - } | |
| 47 | - } | |
| 48 | - dec.flush()?; | |
| 49 | - while let Some(f) = dec.next_frame() { | |
| 50 | - frames.push(frame_bytes(&f)); | |
| 51 | - } | |
| 52 | - Ok(frames) | |
| 53 | -} | |
| 54 | - | |
| 55 | -fn scratch() -> PathBuf { | |
| 56 | - let dir = std::env::temp_dir().join(format!( | |
| 57 | - "ec-h264-mbaff-{}-{:?}", | |
| 58 | - std::process::id(), | |
| 59 | - std::thread::current().id() | |
| 60 | - )); | |
| 61 | - std::fs::create_dir_all(&dir).unwrap(); | |
| 62 | - dir | |
| 63 | -} | |
| 9 | +use super::common::{decode_all, ffmpeg_frames, scratch}; | |
| 64 | 10 | |
| 65 | 11 | struct Case { |
| 66 | 12 | tag: &'static str, |
| @@ -105,7 +51,7 @@ fn encode(dir: &Path, c: &Case) -> Option<PathBuf> { | ||
| 105 | 51 | } |
| 106 | 52 | |
| 107 | 53 | fn check(c: &Case) -> Result<usize, String> { |
| 108 | - let dir = scratch(); | |
| 54 | + let dir = scratch("mbaff"); | |
| 109 | 55 | let stream = encode(&dir, c) |
| 110 | 56 | .unwrap_or_else(|| panic!("{}: ffmpeg/libx264 cannot encode this case", c.tag)); |
| 111 | 57 | let bytes = std::fs::read(&stream).map_err(|e| e.to_string())?; |
| @@ -145,7 +91,7 @@ fn sweep(cases: &[Case]) { | ||
| 145 | 91 | Err(e) => failed.push(e), |
| 146 | 92 | } |
| 147 | 93 | } |
| 148 | - let _ = std::fs::remove_dir_all(scratch()); | |
| 94 | + let _ = std::fs::remove_dir_all(scratch("mbaff")); | |
| 149 | 95 | assert!( |
| 150 | 96 | failed.is_empty(), |
| 151 | 97 | "MBAFF mismatches:\n{}", |
| @@ -171,9 +117,8 @@ const fn case( | ||
| 171 | 117 | } |
| 172 | 118 | |
| 173 | 119 | /// Small pictures: every coding tool once, quick enough for every run. |
| 174 | -#[test] | |
| 175 | -fn x264_mbaff_small() { | |
| 176 | - sweep(&[ | |
| 120 | +fn mbaff_small_cases() -> Vec<Case> { | |
| 121 | + vec![ | |
| 177 | 122 | case("i-cabac-tff", "testsrc2", "192x128", 3, "tff=1:keyint=1"), |
| 178 | 123 | case("i-cabac-bff", "testsrc2", "192x128", 3, "bff=1:keyint=1"), |
| 179 | 124 | case( |
| @@ -296,12 +241,11 @@ fn x264_mbaff_small() { | ||
| 296 | 241 | 8, |
| 297 | 242 | "tff=1:bframes=3:subme=9:trellis=2:me=umh", |
| 298 | 243 | ), |
| 299 | - ]); | |
| 244 | + ] | |
| 300 | 245 | } |
| 301 | 246 | |
| 302 | 247 | /// High 10 MBAFF. |
| 303 | -#[test] | |
| 304 | -fn x264_mbaff_high10() { | |
| 248 | +fn mbaff_high10_cases() -> Vec<Case> { | |
| 305 | 249 | let t = |tag, params| Case { |
| 306 | 250 | tag, |
| 307 | 251 | src: "testsrc2", |
| @@ -310,19 +254,18 @@ fn x264_mbaff_high10() { | ||
| 310 | 254 | ten_bit: true, |
| 311 | 255 | params, |
| 312 | 256 | }; |
| 313 | - sweep(&[ | |
| 257 | + vec![ | |
| 314 | 258 | t("h10-i-cabac", "tff=1:keyint=1"), |
| 315 | 259 | t("h10-i-cavlc", "cabac=0:bff=1:keyint=1"), |
| 316 | 260 | t("h10-b-cabac", "tff=1:bframes=3"), |
| 317 | 261 | t("h10-b-cavlc", "cabac=0:bff=1:bframes=3"), |
| 318 | 262 | t("h10-weightp", "tff=1:bframes=2:weightp=2:weightb=1"), |
| 319 | - ]); | |
| 263 | + ] | |
| 320 | 264 | } |
| 321 | 265 | |
| 322 | 266 | /// 720x576 (the broadcast interlaced size). |
| 323 | -#[test] | |
| 324 | -fn x264_mbaff_sd() { | |
| 325 | - sweep(&[ | |
| 267 | +fn mbaff_sd_cases() -> Vec<Case> { | |
| 268 | + vec![ | |
| 326 | 269 | case("sd-cabac-tff", "testsrc2", "720x576", 6, "tff=1:bframes=3"), |
| 327 | 270 | case( |
| 328 | 271 | "sd-cabac-bff", |
| @@ -352,13 +295,12 @@ fn x264_mbaff_sd() { | ||
| 352 | 295 | 6, |
| 353 | 296 | "tff=1:bframes=2:weightp=2:weightb=1", |
| 354 | 297 | ), |
| 355 | - ]); | |
| 298 | + ] | |
| 356 | 299 | } |
| 357 | 300 | |
| 358 | 301 | /// 1920x1080. |
| 359 | -#[test] | |
| 360 | -fn x264_mbaff_hd() { | |
| 361 | - sweep(&[ | |
| 302 | +fn mbaff_hd_cases() -> Vec<Case> { | |
| 303 | + vec![ | |
| 362 | 304 | case( |
| 363 | 305 | "hd-cabac-tff", |
| 364 | 306 | "testsrc2", |
| @@ -401,5 +343,15 @@ fn x264_mbaff_hd() { | ||
| 401 | 343 | 5, |
| 402 | 344 | "bff=1:bframes=2:weightp=2:weightb=1", |
| 403 | 345 | ), |
| 404 | - ]); | |
| 346 | + ] | |
| 347 | +} | |
| 348 | + | |
| 349 | +#[test] | |
| 350 | +fn x264_mbaff() { | |
| 351 | + let mut cases = Vec::new(); | |
| 352 | + cases.extend(mbaff_small_cases()); | |
| 353 | + cases.extend(mbaff_high10_cases()); | |
| 354 | + cases.extend(mbaff_sd_cases()); | |
| 355 | + cases.extend(mbaff_hd_cases()); | |
| 356 | + sweep(&cases); | |
| 405 | 357 | } |
crates/ec-h264/tests/it/no_panic.rsdeleted+0 -85
| @@ -1,85 +0,0 @@ | ||
| 1 | -//! No-panic floor for the decoder on malformed input. | |
| 2 | -//! | |
| 3 | -//! For each of the first 10 JVT conformance streams (the same name-sorted walk | |
| 4 | -//! `conformance.rs` uses), truncate at 8 positions and flip one byte at 30 | |
| 5 | -//! fixed-seed positions. Every mutant is decoded end to end. An `Err` is fine; | |
| 6 | -//! a panic fails the test. | |
| 7 | -//! | |
| 8 | - | |
| 9 | -use std::path::{Path, PathBuf}; | |
| 10 | - | |
| 11 | -use ec_h264::{Decoder, NalOutcome}; | |
| 12 | - | |
| 13 | -use super::common::find_stream; | |
| 14 | - | |
| 15 | -const STREAMS: usize = 10; | |
| 16 | -const TRUNCATIONS: usize = 8; | |
| 17 | -const CORRUPTIONS: usize = 30; | |
| 18 | -const SEED: u32 = 0x9E37_79B9; | |
| 19 | - | |
| 20 | -fn vectors_dir() -> PathBuf { | |
| 21 | - ec_testkit::fixture("vectors/h264-jvt") | |
| 22 | -} | |
| 23 | - | |
| 24 | -/// Every vector directory, in name order (the order `conformance.rs` walks). | |
| 25 | -fn vector_names(base: &Path) -> Vec<String> { | |
| 26 | - let mut names: Vec<String> = std::fs::read_dir(base) | |
| 27 | - .into_iter() | |
| 28 | - .flatten() | |
| 29 | - .flatten() | |
| 30 | - .filter(|e| e.path().is_dir()) | |
| 31 | - .map(|e| e.file_name().to_string_lossy().into_owned()) | |
| 32 | - .collect(); | |
| 33 | - names.sort(); | |
| 34 | - names | |
| 35 | -} | |
| 36 | - | |
| 37 | -/// Decode a whole byte stream, ignoring every error. Only a panic matters here. | |
| 38 | -fn decode_everything(bytes: &[u8]) { | |
| 39 | - let mut dec = Decoder::new(); | |
| 40 | - for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | |
| 41 | - if let Ok(NalOutcome::PictureBoundary) = dec.push_nal(nal) { | |
| 42 | - let _ = dec.end_picture(); | |
| 43 | - let _ = dec.push_nal(nal); | |
| 44 | - } | |
| 45 | - while dec.next_frame().is_some() {} | |
| 46 | - } | |
| 47 | - let _ = dec.flush(); | |
| 48 | - while dec.next_frame().is_some() {} | |
| 49 | -} | |
| 50 | - | |
| 51 | -#[test] | |
| 52 | -fn truncated_and_corrupted_conformance_streams_never_panic() { | |
| 53 | - let base = vectors_dir(); | |
| 54 | - let mut streams = 0usize; | |
| 55 | - for name in vector_names(&base).into_iter().take(STREAMS) { | |
| 56 | - let Some(stream) = find_stream(&base.join(&name)) else { | |
| 57 | - continue; | |
| 58 | - }; | |
| 59 | - let bytes = std::fs::read(&stream).expect("read conformance stream"); | |
| 60 | - if bytes.is_empty() { | |
| 61 | - continue; | |
| 62 | - } | |
| 63 | - streams += 1; | |
| 64 | - | |
| 65 | - for k in 1..=TRUNCATIONS { | |
| 66 | - decode_everything(&bytes[..bytes.len() * k / (TRUNCATIONS + 1)]); | |
| 67 | - } | |
| 68 | - | |
| 69 | - let mut seed = SEED; | |
| 70 | - for _ in 0..CORRUPTIONS { | |
| 71 | - seed ^= seed << 13; | |
| 72 | - seed ^= seed >> 17; | |
| 73 | - seed ^= seed << 5; | |
| 74 | - let pos = seed as usize % bytes.len(); | |
| 75 | - // Never xor by zero: that would leave the stream unchanged. | |
| 76 | - let flip = ((seed >> 24) as u8) | 1; | |
| 77 | - let mut m = bytes.clone(); | |
| 78 | - m[pos] ^= flip; | |
| 79 | - decode_everything(&m); | |
| 80 | - } | |
| 81 | - } | |
| 82 | - eprintln!( | |
| 83 | - "no-panic sweep: {streams} streams, {TRUNCATIONS} truncations + {CORRUPTIONS} corruptions each" | |
| 84 | - ); | |
| 85 | -} |