Merge branch 'simplify/u7' into simplify/w1b
Browse files at this commit45 changed files +306 -7412
- crates/ec-h265-syntax/src/sei.rs +12 -23
- crates/ec-h265-syntax/tests/sei_sweep.rs +0 -83
- crates/ec-h265/Cargo.toml +0 -1
- crates/ec-h265/src/dec/amvp.rs +0 -230
- crates/ec-h265/src/dec/cu_syntax.rs +25 -144
- crates/ec-h265/src/dec/cu_syntax/wpp.rs +34 -63
- crates/ec-h265/src/dec/deblock.rs +1 -4
- crates/ec-h265/src/dec/dpb.rs +5 -3
- crates/ec-h265/src/dec/inter.rs +1 -4
- crates/ec-h265/src/dec/mc.rs +0 -4
- crates/ec-h265/src/dec/mc_tests.rs +0 -1137
- crates/ec-h265/src/dec/merge.rs +8 -367
- crates/ec-h265/src/dec/mod.rs +14 -112
- crates/ec-h265/src/dec/motion_field.rs +23 -78
- crates/ec-h265/src/dec/pic.rs +16 -52
- crates/ec-h265/src/dec/picjob.rs +9 -16
- crates/ec-h265/src/dec/recon.rs +0 -10
- crates/ec-h265/src/dec/rowfilter.rs +1 -6
- crates/ec-h265/src/dec/rps.rs +10 -22
- crates/ec-h265/src/dec/runner.rs +13 -59
- crates/ec-h265/src/dec/sao.rs +1 -4
- crates/ec-h265/src/dec/shared.rs +14 -32
- crates/ec-h265/src/dec/trace.rs +0 -155
- crates/ec-h265/src/decode.rs +0 -28
- crates/ec-h265/src/enc_p.rs +90 -93
- crates/ec-h265/src/encoder.rs +8 -3
- crates/ec-h265/src/residual.rs +0 -258
- crates/ec-h265/src/transform.rs +0 -7
- crates/ec-h265/tests/it/common.rs +12 -3
- crates/ec-h265/tests/it/conformance.rs +0 -964
- crates/ec-h265/tests/it/conformance_intra.rs +0 -276
- crates/ec-h265/tests/it/conformance_rext.rs +0 -325
- crates/ec-h265/tests/it/conformance_rext422.rs +0 -128
- crates/ec-h265/tests/it/cu_syntax.rs +0 -130
- crates/ec-h265/tests/it/dec_meta.rs +0 -244
- crates/ec-h265/tests/it/dec_shell.rs +0 -454
- crates/ec-h265/tests/it/dolby_vision_p8.rs +0 -197
- crates/ec-h265/tests/it/encode.rs +0 -922
- crates/ec-h265/tests/it/encode_threads.rs +6 -2
- crates/ec-h265/tests/it/main.rs +0 -13
- crates/ec-h265/tests/it/rate_control.rs +0 -207
- crates/ec-h265/tests/it/rdoq_cache_hash.rs +0 -70
- crates/ec-h265/tests/it/real_library.rs +0 -367
- crates/ec-h265/tests/it/rext_generated.rs +3 -1
- crates/ec-h265/tests/it/scaling_lists.rs +0 -111
crates/ec-h265-syntax/src/sei.rsmodified+12 -23
| @@ -11,7 +11,6 @@ | |||
| 11 | //! RBSP, and refuses a malformed one rather than guessing. | 11 | //! RBSP, and refuses a malformed one rather than guessing. |
| 12 | 12 | ||
| 13 | use crate::md5::Md5; | 13 | use crate::md5::Md5; |
| 14 | -use crate::nal::{NalHeader, NalUnitType}; | ||
| 15 | use crate::ps::rbsp_trailing_bits; | 14 | use crate::ps::rbsp_trailing_bits; |
| 16 | use ec_core::bitio::BitWriter; | 15 | use ec_core::bitio::BitWriter; |
| 17 | use ec_core::color::ContentLight; | 16 | use ec_core::color::ContentLight; |
| @@ -48,19 +47,14 @@ fn sei_rbsp(messages: &[(u32, Vec<u8>)]) -> Vec<u8> { | |||
| 48 | } | 47 | } |
| 49 | 48 | ||
| 50 | /// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there | 49 | /// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there |
| 51 | -/// is nothing to say. | 50 | +/// is nothing to say. When `display` is given it is written verbatim (chromaticities |
| 51 | +/// and luminances), and the mastering pair inside `light` is ignored. The content light | ||
| 52 | +/// level comes from `light`. | ||
| 52 | /// | 53 | /// |
| 53 | /// Both messages are written whole or not at all: a `mastering_display_colour_volume` | 54 | /// Both messages are written whole or not at all: a `mastering_display_colour_volume` |
| 54 | /// with a zero luminance pair is what the oracle writes when it knows nothing, and a | 55 | /// with a zero luminance pair is what the oracle writes when it knows nothing, and a |
| 55 | /// tone map that believes it maps the film to black. | 56 | /// tone map that believes it maps the film to black. |
| 56 | -pub fn hdr_metadata_rbsp(light: ContentLight) -> Option<Vec<u8>> { | 57 | +pub fn hdr_metadata_rbsp( |
| 57 | - hdr_metadata_rbsp_with(None, light) | ||
| 58 | -} | ||
| 59 | - | ||
| 60 | -/// [`hdr_metadata_rbsp`] with an explicit mastering display: when `display` is | ||
| 61 | -/// given it is written verbatim (chromaticities and luminances), and the mastering | ||
| 62 | -/// pair inside `light` is ignored. The content light level comes from `light`. | ||
| 63 | -pub fn hdr_metadata_rbsp_with( | ||
| 64 | display: Option<MasteringDisplay>, | 58 | display: Option<MasteringDisplay>, |
| 65 | light: ContentLight, | 59 | light: ContentLight, |
| 66 | ) -> Option<Vec<u8>> { | 60 | ) -> Option<Vec<u8>> { |
| @@ -126,16 +120,6 @@ pub fn decoded_picture_hash_rbsp(planes: &[(&[u8], usize, usize, usize)]) -> Vec | |||
| 126 | sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)]) | 120 | sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)]) |
| 127 | } | 121 | } |
| 128 | 122 | ||
| 129 | -/// The NAL header a prefix SEI travels under. | ||
| 130 | -pub fn prefix_sei_header() -> NalHeader { | ||
| 131 | - NalHeader::new(NalUnitType::PrefixSei) | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -/// The NAL header a suffix SEI (the picture hash) travels under. | ||
| 135 | -pub fn suffix_sei_header() -> NalHeader { | ||
| 136 | - NalHeader::new(NalUnitType::SuffixSei) | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | /// `payloadType` of the alternative transfer characteristics message (D.2.x). | 123 | /// `payloadType` of the alternative transfer characteristics message (D.2.x). |
| 140 | const PAYLOAD_ALTERNATIVE_TRANSFER: u32 = 147; | 124 | const PAYLOAD_ALTERNATIVE_TRANSFER: u32 = 147; |
| 141 | 125 | ||
| @@ -373,16 +357,21 @@ mod tests { | |||
| 373 | mastering_min: Some(0.005), | 357 | mastering_min: Some(0.005), |
| 374 | ..ContentLight::default() | 358 | ..ContentLight::default() |
| 375 | }; | 359 | }; |
| 376 | - let rbsp = hdr_metadata_rbsp(light).unwrap(); | 360 | + let rbsp = hdr_metadata_rbsp(None, light).unwrap(); |
| 377 | let mut annex_b = Vec::new(); | 361 | let mut annex_b = Vec::new(); |
| 378 | - crate::nal::write_annex_b(&mut annex_b, prefix_sei_header(), &rbsp, true); | 362 | + crate::nal::write_annex_b( |
| 363 | + &mut annex_b, | ||
| 364 | + crate::nal::NalHeader::new(crate::nal::NalUnitType::PrefixSei), | ||
| 365 | + &rbsp, | ||
| 366 | + true, | ||
| 367 | + ); | ||
| 379 | // ec-core's reader is the consumer this exists for. | 368 | // ec-core's reader is the consumer this exists for. |
| 380 | let read = ec_core::color::hevc_sei_light(&annex_b); | 369 | let read = ec_core::color::hevc_sei_light(&annex_b); |
| 381 | assert_eq!(read.max_cll, Some(1000.0)); | 370 | assert_eq!(read.max_cll, Some(1000.0)); |
| 382 | assert_eq!(read.max_fall, Some(400.0)); | 371 | assert_eq!(read.max_fall, Some(400.0)); |
| 383 | assert_eq!(read.mastering_max, Some(1000.0)); | 372 | assert_eq!(read.mastering_max, Some(1000.0)); |
| 384 | assert_eq!(read.mastering_min, Some(0.005)); | 373 | assert_eq!(read.mastering_min, Some(0.005)); |
| 385 | - assert!(hdr_metadata_rbsp(ContentLight::default()).is_none()); | 374 | + assert!(hdr_metadata_rbsp(None, ContentLight::default()).is_none()); |
| 386 | } | 375 | } |
| 387 | 376 | ||
| 388 | #[test] | 377 | #[test] |
crates/ec-h265-syntax/tests/sei_sweep.rsdeleted+0 -83
| @@ -1,83 +0,0 @@ | |||
| 1 | -//! The SEI reader over the JCT-VC conformance streams. | ||
| 2 | -//! | ||
| 3 | -//! Every prefix and suffix SEI NAL unit of every stream must parse without error, | ||
| 4 | - | ||
| 5 | -use std::path::{Path, PathBuf}; | ||
| 6 | - | ||
| 7 | -use ec_h265_syntax::nal::split_annex_b; | ||
| 8 | -use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp}; | ||
| 9 | - | ||
| 10 | -fn streams() -> Vec<PathBuf> { | ||
| 11 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 12 | - fn walk(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 13 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 14 | - return; | ||
| 15 | - }; | ||
| 16 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 17 | - paths.sort(); | ||
| 18 | - for p in paths { | ||
| 19 | - if p.is_dir() && depth > 0 { | ||
| 20 | - walk(&p, depth - 1, out); | ||
| 21 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 22 | - out.push(p); | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - let mut out = Vec::new(); | ||
| 27 | - walk(&root, 2, &mut out); | ||
| 28 | - out | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -#[test] | ||
| 32 | -fn every_sei_in_the_conformance_streams_parses() { | ||
| 33 | - let streams = streams(); | ||
| 34 | - assert!(!streams.is_empty(), "no streams under vectors/hevc-jctvc"); | ||
| 35 | - let mut with_hash = 0usize; | ||
| 36 | - let mut hash_streams = Vec::new(); | ||
| 37 | - let mut sei_nals = 0usize; | ||
| 38 | - let mut messages = 0usize; | ||
| 39 | - let mut hashes = 0usize; | ||
| 40 | - let mut failures = Vec::new(); | ||
| 41 | - for path in &streams { | ||
| 42 | - let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); | ||
| 43 | - let data = match std::fs::read(path) { | ||
| 44 | - Ok(d) => d, | ||
| 45 | - Err(e) => { | ||
| 46 | - failures.push(format!("{name}: read: {e}")); | ||
| 47 | - continue; | ||
| 48 | - } | ||
| 49 | - }; | ||
| 50 | - let mut stream_hashes = 0usize; | ||
| 51 | - for nal in split_annex_b(&data) { | ||
| 52 | - if nal.header.layer_id > 0 || !matches!(nal.header.nal_type.code(), 39 | 40) { | ||
| 53 | - continue; | ||
| 54 | - } | ||
| 55 | - sei_nals += 1; | ||
| 56 | - match parse_sei_rbsp(&nal.rbsp()) { | ||
| 57 | - Ok(msgs) => { | ||
| 58 | - messages += msgs.len(); | ||
| 59 | - for msg in &msgs { | ||
| 60 | - if matches!(msg, SeiMessage::DecodedPictureHash(_)) { | ||
| 61 | - stream_hashes += 1; | ||
| 62 | - } | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - Err(e) => failures.push(format!("{name}: SEI NAL #{sei_nals}: {e}")), | ||
| 66 | - } | ||
| 67 | - } | ||
| 68 | - if stream_hashes > 0 { | ||
| 69 | - with_hash += 1; | ||
| 70 | - hash_streams.push(name.clone()); | ||
| 71 | - } | ||
| 72 | - hashes += stream_hashes; | ||
| 73 | - } | ||
| 74 | - eprintln!( | ||
| 75 | - "SEI sweep: {} streams, {with_hash} carry decoded_picture_hash ({hashes} hash messages), \ | ||
| 76 | - {sei_nals} SEI NAL units, {messages} messages, {} parse failures", | ||
| 77 | - streams.len(), | ||
| 78 | - failures.len() | ||
| 79 | - ); | ||
| 80 | - eprintln!("streams with decoded_picture_hash: {}", hash_streams.join(" ")); | ||
| 81 | - assert!(failures.is_empty(), "SEI that failed to parse:\n{}", failures.join("\n")); | ||
| 82 | - assert!(with_hash > 0, "no conformance stream carries decoded_picture_hash SEI"); | ||
| 83 | -} | ||
crates/ec-h265/Cargo.tomlmodified+0 -1
| @@ -16,4 +16,3 @@ multiversion = "0.9" | |||
| 16 | 16 | ||
| 17 | [dev-dependencies] | 17 | [dev-dependencies] |
| 18 | ec-testkit.workspace = true | 18 | ec-testkit.workspace = true |
| 19 | -ec-h265-syntax.workspace = true | ||
crates/ec-h265/src/dec/amvp.rsmodified+0 -230
| @@ -146,233 +146,3 @@ fn wrap16(v: i32) -> i16 { | |||
| 146 | let signed = if u >= 1 << 15 { u - (1 << 16) } else { u }; | 146 | let signed = if u >= 1 << 15 { u - (1 << 16) } else { u }; |
| 147 | signed as i16 | 147 | signed as i16 |
| 148 | } | 148 | } |
| 149 | - | ||
| 150 | -#[cfg(test)] | ||
| 151 | -mod tests { | ||
| 152 | - use super::super::cu_syntax::InterPredIdc; | ||
| 153 | - use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared}; | ||
| 154 | - use super::super::rps::{RefEntry, RefPicLists}; | ||
| 155 | - use super::super::shared::SharedPic; | ||
| 156 | - use super::*; | ||
| 157 | - use std::sync::Arc; | ||
| 158 | - | ||
| 159 | - fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry { | ||
| 160 | - RefEntry { id, poc, long_term } | ||
| 161 | - } | ||
| 162 | - | ||
| 163 | - fn params(temporal: bool) -> MotionParams { | ||
| 164 | - MotionParams { | ||
| 165 | - is_b: false, | ||
| 166 | - max_merge_cand: 5, | ||
| 167 | - log2_par_mrg_level: 2, | ||
| 168 | - ctb_log2: 6, | ||
| 169 | - collocated_from_l0: true, | ||
| 170 | - temporal_mvp: temporal, | ||
| 171 | - no_backward_pred: true, | ||
| 172 | - } | ||
| 173 | - } | ||
| 174 | - | ||
| 175 | - fn l0(ref_idx: i8, mv: [i16; 2]) -> PbMotion { | ||
| 176 | - PbMotion::new([true, false], [ref_idx, -1], [mv, [0, 0]]) | ||
| 177 | - } | ||
| 178 | - | ||
| 179 | - /// An AMVP PU at (16,16) of size 16x16 with list 0, reference `ref_idx` and | ||
| 180 | - /// difference `mvd`, using predictor `flag`. | ||
| 181 | - fn pu(mvd: [i32; 2], flag: u8) -> PredictionUnit { | ||
| 182 | - PredictionUnit { | ||
| 183 | - x: 16, | ||
| 184 | - y: 16, | ||
| 185 | - width: 16, | ||
| 186 | - height: 16, | ||
| 187 | - inter_pred_idc: InterPredIdc::PredL0, | ||
| 188 | - mvp_flag: [flag, 0], | ||
| 189 | - mvd: [mvd, [0, 0]], | ||
| 190 | - ..PredictionUnit::default() | ||
| 191 | - } | ||
| 192 | - } | ||
| 193 | - | ||
| 194 | - /// Run the AMVP derivation for `pu` with `field` as the current motion field. | ||
| 195 | - fn run( | ||
| 196 | - field: &mut MotionField, | ||
| 197 | - lists: &RefPicLists, | ||
| 198 | - cur_poc: i32, | ||
| 199 | - col: Option<Arc<SharedPic>>, | ||
| 200 | - temporal: bool, | ||
| 201 | - pu: &PredictionUnit, | ||
| 202 | - ) -> PbMotion { | ||
| 203 | - let src = SliceMotion { | ||
| 204 | - params: params(temporal), | ||
| 205 | - lists, | ||
| 206 | - cur_poc, | ||
| 207 | - field, | ||
| 208 | - col, | ||
| 209 | - publish: None, | ||
| 210 | - slice: 0, | ||
| 211 | - }; | ||
| 212 | - derive_amvp(&src, pu) | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - fn lists(poc: i32, long_term: bool) -> RefPicLists { | ||
| 216 | - RefPicLists { | ||
| 217 | - l0: vec![entry(0, poc, long_term)], | ||
| 218 | - l1: Vec::new(), | ||
| 219 | - } | ||
| 220 | - } | ||
| 221 | - | ||
| 222 | - #[test] | ||
| 223 | - fn spatial_a_with_the_same_reference_is_used_unscaled() { | ||
| 224 | - // A1 = (15,31) refers to POC 4, the target. Its vector is the predictor. | ||
| 225 | - let mut field = MotionField::new(64, 64); | ||
| 226 | - field.store(0, 16, 16, 16, 0, l0(0, [40, -12])); | ||
| 227 | - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([1, 1], 0)); | ||
| 228 | - assert_eq!(got, l0(0, [41, -11])); | ||
| 229 | - } | ||
| 230 | - | ||
| 231 | - #[test] | ||
| 232 | - fn spatial_a_scales_by_distance() { | ||
| 233 | - // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 0 (td = 8), mv 64: | ||
| 234 | - // tx = (16384 + 4) / 8 = 2048, dsf = (4 * 2048 + 32) >> 6 = 128, mv' = 32. | ||
| 235 | - // L0[0] is the target (POC 4); the neighbour uses L0[1] (POC 0). | ||
| 236 | - let lists = RefPicLists { | ||
| 237 | - l0: vec![entry(0, 4, false), entry(1, 0, false)], | ||
| 238 | - l1: Vec::new(), | ||
| 239 | - }; | ||
| 240 | - let mut field = MotionField::new(64, 64); | ||
| 241 | - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); | ||
| 242 | - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); | ||
| 243 | - assert_eq!(got, l0(0, [32, 0])); | ||
| 244 | - } | ||
| 245 | - | ||
| 246 | - #[test] | ||
| 247 | - fn spatial_a_scales_with_negative_distance() { | ||
| 248 | - // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 12 (td = -4), mv 64: | ||
| 249 | - // tx = (16384 + 2) / -4 = -4096, dsf = (4 * -4096 + 32) >> 6 = -256, | ||
| 250 | - // mv' = -64. | ||
| 251 | - let lists = RefPicLists { | ||
| 252 | - l0: vec![entry(0, 4, false), entry(1, 12, false)], | ||
| 253 | - l1: Vec::new(), | ||
| 254 | - }; | ||
| 255 | - let mut field = MotionField::new(64, 64); | ||
| 256 | - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); | ||
| 257 | - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); | ||
| 258 | - assert_eq!(got, l0(0, [-64, 0])); | ||
| 259 | - } | ||
| 260 | - | ||
| 261 | - #[test] | ||
| 262 | - fn long_term_neighbour_is_not_scaled() { | ||
| 263 | - // The target is long-term (POC 4) and so is the neighbour's reference (POC 0): | ||
| 264 | - // the vector is used as it is. | ||
| 265 | - let lists = RefPicLists { | ||
| 266 | - l0: vec![entry(0, 4, true), entry(1, 0, true)], | ||
| 267 | - l1: Vec::new(), | ||
| 268 | - }; | ||
| 269 | - let mut field = MotionField::new(64, 64); | ||
| 270 | - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); | ||
| 271 | - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); | ||
| 272 | - assert_eq!(got, l0(0, [64, 0])); | ||
| 273 | - } | ||
| 274 | - | ||
| 275 | - #[test] | ||
| 276 | - fn long_term_mismatch_skips_the_neighbour() { | ||
| 277 | - // The target is long-term but the neighbour's reference is short-term: the | ||
| 278 | - // neighbour gives no predictor, and the list is zero-filled. | ||
| 279 | - let lists = RefPicLists { | ||
| 280 | - l0: vec![entry(0, 4, true), entry(1, 0, false)], | ||
| 281 | - l1: Vec::new(), | ||
| 282 | - }; | ||
| 283 | - let mut field = MotionField::new(64, 64); | ||
| 284 | - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); | ||
| 285 | - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); | ||
| 286 | - assert_eq!(got, l0(0, [0, 0])); | ||
| 287 | - } | ||
| 288 | - | ||
| 289 | - #[test] | ||
| 290 | - fn b_candidate_fills_the_a_slot_when_no_a_neighbour() { | ||
| 291 | - // No A neighbour. B1 = (31,15) refers to the target POC 4: it fills the A slot, | ||
| 292 | - // and the second B pass scales it back to itself (td = tb), so the list is | ||
| 293 | - // [B, 0] and flag 0 picks B. | ||
| 294 | - let mut field = MotionField::new(64, 64); | ||
| 295 | - field.store(16, 0, 16, 16, 0, l0(0, [20, 6])); | ||
| 296 | - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0)); | ||
| 297 | - assert_eq!(got, l0(0, [20, 6])); | ||
| 298 | - let other = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1)); | ||
| 299 | - assert_eq!(other, l0(0, [0, 0])); | ||
| 300 | - } | ||
| 301 | - | ||
| 302 | - #[test] | ||
| 303 | - fn equal_a_and_b_collapse_to_one_predictor() { | ||
| 304 | - // A1 and B1 carry the same vector toward the target: the list is [A, 0]. | ||
| 305 | - let mut field = MotionField::new(64, 64); | ||
| 306 | - field.store(0, 16, 16, 16, 0, l0(0, [7, 7])); | ||
| 307 | - field.store(16, 0, 16, 16, 0, l0(0, [7, 7])); | ||
| 308 | - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1)); | ||
| 309 | - assert_eq!(got, l0(0, [0, 0])); | ||
| 310 | - let first = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0)); | ||
| 311 | - assert_eq!(first, l0(0, [7, 7])); | ||
| 312 | - } | ||
| 313 | - | ||
| 314 | - #[test] | ||
| 315 | - fn temporal_fills_the_second_slot() { | ||
| 316 | - // A1 gives one predictor, so the collocated vector is the second. The collocated | ||
| 317 | - // picture is POC 8 with a vector toward POC 4 (td = 4), and the target is POC 4 | ||
| 318 | - // (tb = 4): no scaling. | ||
| 319 | - let mut col_field = MotionField::new(64, 64); | ||
| 320 | - col_field.slices.push(SliceRefs { | ||
| 321 | - poc: [vec![4], vec![]], | ||
| 322 | - long_term: [vec![false], vec![]], | ||
| 323 | - }); | ||
| 324 | - col_field.store(32, 32, 16, 16, 0, l0(0, [-9, 5])); | ||
| 325 | - let col = test_shared(&col_field, 8); | ||
| 326 | - let mut field = MotionField::new(64, 64); | ||
| 327 | - field.store(0, 16, 16, 16, 0, l0(0, [1, 1])); | ||
| 328 | - let got = run( | ||
| 329 | - &mut field, | ||
| 330 | - &lists(4, false), | ||
| 331 | - 8, | ||
| 332 | - Some(col), | ||
| 333 | - true, | ||
| 334 | - &pu([0, 0], 1), | ||
| 335 | - ); | ||
| 336 | - assert_eq!(got, l0(0, [-9, 5])); | ||
| 337 | - } | ||
| 338 | - | ||
| 339 | - #[test] | ||
| 340 | - fn mv_wraps_at_sixteen_bits() { | ||
| 341 | - // mvp 32000 plus mvd 1000 is 33000, which wraps to 33000 - 65536 = -32536. | ||
| 342 | - // mvp -32000 plus mvd -1000 is -33000, which wraps to 32536. | ||
| 343 | - assert_eq!(wrap16(33000), -32536); | ||
| 344 | - assert_eq!(wrap16(-33000), 32536); | ||
| 345 | - // The boundaries: 32767 stays, 32768 becomes -32768. | ||
| 346 | - assert_eq!(wrap16(32767), 32767); | ||
| 347 | - assert_eq!(wrap16(32768), -32768); | ||
| 348 | - assert_eq!(wrap16(-32768), -32768); | ||
| 349 | - assert_eq!(wrap16(-32769), 32767); | ||
| 350 | - } | ||
| 351 | - | ||
| 352 | - #[test] | ||
| 353 | - fn mvd_wrap_through_the_full_derivation() { | ||
| 354 | - let mut field = MotionField::new(64, 64); | ||
| 355 | - field.store(0, 16, 16, 16, 0, l0(0, [32000, -32000])); | ||
| 356 | - let got = run( | ||
| 357 | - &mut field, | ||
| 358 | - &lists(4, false), | ||
| 359 | - 8, | ||
| 360 | - None, | ||
| 361 | - false, | ||
| 362 | - &pu([1000, -1000], 0), | ||
| 363 | - ); | ||
| 364 | - assert_eq!(got, l0(0, [-32536, 32536])); | ||
| 365 | - } | ||
| 366 | - | ||
| 367 | - #[test] | ||
| 368 | - fn scale_mv_with_negative_and_positive_distances() { | ||
| 369 | - // tb / td = 1/2 with td > 0: half the vector. | ||
| 370 | - assert_eq!(scale_mv([64, 0], 4, 2), [32, 0]); | ||
| 371 | - // td < 0, tb > 0: the vector flips. | ||
| 372 | - assert_eq!(scale_mv([64, 0], -4, 4), [-64, 0]); | ||
| 373 | - // Both negative, ratio 1: the vector is unchanged. | ||
| 374 | - assert_eq!(scale_mv([-30, 7], -4, -4), [-30, 7]); | ||
| 375 | - // The result is clipped to 16 bits. | ||
| 376 | - assert_eq!(scale_mv([32767, 0], 1, 127), [32767, 0]); | ||
| 377 | - } | ||
| 378 | -} | ||
crates/ec-h265/src/dec/cu_syntax.rsmodified+25 -144
| @@ -1,14 +1,11 @@ | |||
| 1 | -//! CABAC syntax of slice data for P and B slices (and for I slices when the | 1 | +//! CABAC syntax of slice data for I, P and B slices: coding quadtree, coding units, prediction units, the |
| 2 | -//! syntax check runs): coding quadtree, coding units, prediction units, the | ||
| 3 | //! transform tree, SAO parameters and the slice-segment loop (H.265 7.3.8.1 to | 2 | //! transform tree, SAO parameters and the slice-segment loop (H.265 7.3.8.1 to |
| 4 | //! 7.3.8.12, bin binarisations of 9.3.3 and context selection of 9.3.4.2). | 3 | //! 7.3.8.12, bin binarisations of 9.3.3 and context selection of 9.3.4.2). |
| 5 | //! | 4 | //! |
| 6 | //! The parser reads every bin, keeps the syntax of each coding unit, and turns | 5 | //! The parser reads every bin, keeps the syntax of each coding unit, and turns |
| 7 | //! each transform block's coefficients into residual samples through the same | 6 | //! each transform block's coefficients into residual samples through the same |
| 8 | //! dequantisation and inverse transform the intra path uses. It does not | 7 | //! dequantisation and inverse transform the intra path uses. It does not |
| 9 | -//! predict. Motion for each prediction unit comes from a [`MotionSource`]; the | 8 | +//! predict. Motion for each prediction unit comes from a [`SliceMotion`]. |
| 10 | -//! merge and AMVP lane implements that trait, and [`ZeroMotion`] stands in until | ||
| 11 | -//! then. | ||
| 12 | //! | 9 | //! |
| 13 | //! Slices, slice segments, tiles and wavefront substreams are followed: CTBs | 10 | //! Slices, slice segments, tiles and wavefront substreams are followed: CTBs |
| 14 | //! are visited in tile scan order, contexts are initialised, synced or restored | 11 | //! are visited in tile scan order, contexts are initialised, synced or restored |
| @@ -17,7 +14,7 @@ | |||
| 17 | 14 | ||
| 18 | use super::inter::{self, InterRefs}; | 15 | use super::inter::{self, InterRefs}; |
| 19 | use super::mc::{Block, McScratch}; | 16 | use super::mc::{Block, McScratch}; |
| 20 | -use super::motion_field::MotionField; | 17 | +use super::motion_field::SliceMotion; |
| 21 | use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter}; | 18 | use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter}; |
| 22 | use super::rext; | 19 | use super::rext; |
| 23 | use super::tiles::TileScan; | 20 | use super::tiles::TileScan; |
| @@ -93,7 +90,7 @@ pub struct PredictionUnit { | |||
| 93 | pub mvd: [[i32; 2]; 2], | 90 | pub mvd: [[i32; 2]; 2], |
| 94 | } | 91 | } |
| 95 | 92 | ||
| 96 | -/// Motion of one prediction unit, as a [`MotionSource`] returns it. | 93 | +/// Motion of one prediction unit, as [`SliceMotion::derive_motion`] returns it. |
| 97 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] | 94 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 98 | pub struct Motion { | 95 | pub struct Motion { |
| 99 | /// `predFlagLX` for list 0 and list 1. | 96 | /// `predFlagLX` for list 0 and list 1. |
| @@ -104,75 +101,6 @@ pub struct Motion { | |||
| 104 | pub mv: [[i32; 2]; 2], | 101 | pub mv: [[i32; 2]; 2], |
| 105 | } | 102 | } |
| 106 | 103 | ||
| 107 | -/// The geometry of a coding unit, as a [`MotionSource`] needs it. | ||
| 108 | -#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 109 | -pub struct CuGeometry { | ||
| 110 | - /// Luma position of the coding unit. | ||
| 111 | - pub x: usize, | ||
| 112 | - /// Luma position of the coding unit. | ||
| 113 | - pub y: usize, | ||
| 114 | - /// Luma size of the coding unit. | ||
| 115 | - pub size: usize, | ||
| 116 | - /// The partitioning. | ||
| 117 | - pub part_mode: PartMode, | ||
| 118 | - /// Whether the coding unit is skipped. | ||
| 119 | - pub skip: bool, | ||
| 120 | -} | ||
| 121 | - | ||
| 122 | -/// Derives the motion of each prediction unit. Called once per unit, in decoding | ||
| 123 | -/// order, after the unit's syntax has been parsed (so merge candidates from | ||
| 124 | -/// earlier units are available to the implementation). Merge and AMVP derivation | ||
| 125 | -/// (8.5.3) is the job of the implementation; the parser does not look inside. | ||
| 126 | -pub trait MotionSource { | ||
| 127 | - /// The motion of unit `pu_index` of the coding unit `cu`. | ||
| 128 | - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion; | ||
| 129 | - | ||
| 130 | - /// Called once the CTB row that ends at luma row `row_end` is fully parsed. Only | ||
| 131 | - /// pictures with one tile get the call (their CTBs come in raster order). | ||
| 132 | - fn row_done(&mut self, _pic: &mut PicState, _row_end: usize) {} | ||
| 133 | - | ||
| 134 | - /// The motion field this source writes, when it is a wavefront band (see [`wpp`]). | ||
| 135 | - fn band_cells(&mut self) -> Option<&mut MotionField> { | ||
| 136 | - None | ||
| 137 | - } | ||
| 138 | -} | ||
| 139 | - | ||
| 140 | -/// The placeholder [`MotionSource`]: zero motion vectors and reference index 0 for | ||
| 141 | -/// every list the unit uses. Replace it with the merge/AMVP derivation. | ||
| 142 | -#[derive(Clone, Copy, Debug, Default)] | ||
| 143 | -pub struct ZeroMotion; | ||
| 144 | - | ||
| 145 | -impl MotionSource for ZeroMotion { | ||
| 146 | - fn derive_motion(&mut self, _cu: &CuGeometry, _pu_index: usize, pu: &PredictionUnit) -> Motion { | ||
| 147 | - let pred_flags = if pu.merge_flag { | ||
| 148 | - [true, false] | ||
| 149 | - } else { | ||
| 150 | - match pu.inter_pred_idc { | ||
| 151 | - InterPredIdc::PredL0 => [true, false], | ||
| 152 | - InterPredIdc::PredL1 => [false, true], | ||
| 153 | - InterPredIdc::PredBi => [true, true], | ||
| 154 | - } | ||
| 155 | - }; | ||
| 156 | - let ref_idx = [ | ||
| 157 | - if pred_flags[0] { | ||
| 158 | - i8::try_from(pu.ref_idx[0]).unwrap_or(0) | ||
| 159 | - } else { | ||
| 160 | - -1 | ||
| 161 | - }, | ||
| 162 | - if pred_flags[1] { | ||
| 163 | - i8::try_from(pu.ref_idx[1]).unwrap_or(0) | ||
| 164 | - } else { | ||
| 165 | - -1 | ||
| 166 | - }, | ||
| 167 | - ]; | ||
| 168 | - Motion { | ||
| 169 | - pred_flags, | ||
| 170 | - ref_idx, | ||
| 171 | - mv: [[0, 0], [0, 0]], | ||
| 172 | - } | ||
| 173 | - } | ||
| 174 | -} | ||
| 175 | - | ||
| 176 | /// The residual samples of one transform block, after dequantisation and the | 104 | /// The residual samples of one transform block, after dequantisation and the |
| 177 | /// inverse transform. Samples are row-major, `size * size`. | 105 | /// inverse transform. Samples are row-major, `size * size`. |
| 178 | #[derive(Clone, Debug, PartialEq, Eq)] | 106 | #[derive(Clone, Debug, PartialEq, Eq)] |
| @@ -212,7 +140,7 @@ pub struct CodingUnit { | |||
| 212 | pub chroma_mode: u8, | 140 | pub chroma_mode: u8, |
| 213 | /// The prediction units, in order. | 141 | /// The prediction units, in order. |
| 214 | pub pus: Vec<PredictionUnit>, | 142 | pub pus: Vec<PredictionUnit>, |
| 215 | - /// The motion of each prediction unit, from the [`MotionSource`]. | 143 | + /// The motion of each prediction unit, from [`SliceMotion`]. |
| 216 | pub motion: Vec<Motion>, | 144 | pub motion: Vec<Motion>, |
| 217 | /// `rqt_root_cbf` (inferred 1 for intra). | 145 | /// `rqt_root_cbf` (inferred 1 for intra). |
| 218 | pub rqt_root_cbf: bool, | 146 | pub rqt_root_cbf: bool, |
| @@ -244,38 +172,8 @@ pub struct SliceStats { | |||
| 244 | pub trailing_bits_ok: bool, | 172 | pub trailing_bits_ok: bool, |
| 245 | } | 173 | } |
| 246 | 174 | ||
| 247 | -/// Parse one slice segment's data, from the byte after its header, to | ||
| 248 | -/// `end_of_slice_segment_flag`. `sink` sees every coding unit in decoding order. | ||
| 249 | -/// `motion` derives the motion of each prediction unit. | ||
| 250 | -/// | ||
| 251 | -/// A desync shows up as an `end_of_slice_segment_flag` at the wrong CTB, or as a | ||
| 252 | -/// trailing-bit pattern that is not the stop bit; both are errors. This form | ||
| 253 | -/// keeps only the syntax: no samples are produced. | ||
| 254 | -pub fn parse_slice( | ||
| 255 | - sps: &Sps, | ||
| 256 | - pps: &Pps, | ||
| 257 | - header: &SliceHeader, | ||
| 258 | - data: &[u8], | ||
| 259 | - motion: &mut dyn MotionSource, | ||
| 260 | - sink: &mut dyn FnMut(&CodingUnit), | ||
| 261 | -) -> Result<SliceStats> { | ||
| 262 | - let mut pic = PicState::for_sps_pps(sps, pps, false); | ||
| 263 | - parse_slice_into( | ||
| 264 | - sps, | ||
| 265 | - pps, | ||
| 266 | - header, | ||
| 267 | - data, | ||
| 268 | - motion, | ||
| 269 | - &mut pic, | ||
| 270 | - None, | ||
| 271 | - sink, | ||
| 272 | - &mut |_, _| {}, | ||
| 273 | - ) | ||
| 274 | -} | ||
| 275 | - | ||
| 276 | /// Parse one slice segment's data into `pic`. The block maps are always | 175 | /// Parse one slice segment's data into `pic`. The block maps are always |
| 277 | -/// filled. When `pic` has sample planes (pixel decode), intra coding units are | 176 | +/// filled. Intra coding units are reconstructed in decoding order, and inter coding units are predicted from |
| 278 | -/// reconstructed in decoding order, and inter coding units are predicted from | ||
| 279 | /// `refs` (8.5.3.3) per prediction unit, then get their residual added. | 177 | /// `refs` (8.5.3.3) per prediction unit, then get their residual added. |
| 280 | #[allow(clippy::too_many_arguments)] // the slice, the picture it decodes into, and its references | 178 | #[allow(clippy::too_many_arguments)] // the slice, the picture it decodes into, and its references |
| 281 | pub fn parse_slice_into( | 179 | pub fn parse_slice_into( |
| @@ -283,7 +181,7 @@ pub fn parse_slice_into( | |||
| 283 | pps: &Pps, | 181 | pps: &Pps, |
| 284 | header: &SliceHeader, | 182 | header: &SliceHeader, |
| 285 | data: &[u8], | 183 | data: &[u8], |
| 286 | - motion: &mut dyn MotionSource, | 184 | + motion: &mut SliceMotion<'_>, |
| 287 | pic: &mut PicState, | 185 | pic: &mut PicState, |
| 288 | refs: Option<&InterRefs>, | 186 | refs: Option<&InterRefs>, |
| 289 | sink: &mut dyn FnMut(&CodingUnit), | 187 | sink: &mut dyn FnMut(&CodingUnit), |
| @@ -485,15 +383,15 @@ pub(super) fn trailing_bits_ok(data: &[u8], read: usize) -> bool { | |||
| 485 | } | 383 | } |
| 486 | 384 | ||
| 487 | /// The coding-tree walk of one slice segment, starting with `last_qp` as qPY_PREV. | 385 | /// The coding-tree walk of one slice segment, starting with `last_qp` as qPY_PREV. |
| 488 | -fn new_parser<'a>( | 386 | +fn new_parser<'a, 'm>( |
| 489 | sps: &'a Sps, | 387 | sps: &'a Sps, |
| 490 | pps: &'a Pps, | 388 | pps: &'a Pps, |
| 491 | header: &'a SliceHeader, | 389 | header: &'a SliceHeader, |
| 492 | pic: &'a mut PicState, | 390 | pic: &'a mut PicState, |
| 493 | refs: Option<&'a InterRefs>, | 391 | refs: Option<&'a InterRefs>, |
| 494 | - motion: &'a mut dyn MotionSource, | 392 | + motion: &'a mut SliceMotion<'m>, |
| 495 | last_qp: i32, | 393 | last_qp: i32, |
| 496 | -) -> Parser<'a> { | 394 | +) -> Parser<'a, 'm> { |
| 497 | let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; | 395 | let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; |
| 498 | let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; | 396 | let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; |
| 499 | let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; | 397 | let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; |
| @@ -584,7 +482,7 @@ struct Cbf { | |||
| 584 | } | 482 | } |
| 585 | 483 | ||
| 586 | /// The coding-tree walk state for one slice segment. | 484 | /// The coding-tree walk state for one slice segment. |
| 587 | -struct Parser<'a> { | 485 | +struct Parser<'a, 'm> { |
| 588 | sps: &'a Sps, | 486 | sps: &'a Sps, |
| 589 | pps: &'a Pps, | 487 | pps: &'a Pps, |
| 590 | header: &'a SliceHeader, | 488 | header: &'a SliceHeader, |
| @@ -628,11 +526,11 @@ struct Parser<'a> { | |||
| 628 | cu_bypass: bool, | 526 | cu_bypass: bool, |
| 629 | /// The chroma modes of the intra coding unit being parsed, with their DM flags. | 527 | /// The chroma modes of the intra coding unit being parsed, with their DM flags. |
| 630 | chroma_modes: ([u8; 4], [bool; 4]), | 528 | chroma_modes: ([u8; 4], [bool; 4]), |
| 631 | - motion: &'a mut dyn MotionSource, | 529 | + motion: &'a mut SliceMotion<'m>, |
| 632 | stats: SliceStats, | 530 | stats: SliceStats, |
| 633 | } | 531 | } |
| 634 | 532 | ||
| 635 | -impl Parser<'_> { | 533 | +impl Parser<'_, '_> { |
| 636 | fn info_at(&self, x: usize, y: usize) -> BlockInfo { | 534 | fn info_at(&self, x: usize, y: usize) -> BlockInfo { |
| 637 | self.pic.info[self.pic.unit(x, y)] | 535 | self.pic.info[self.pic.unit(x, y)] |
| 638 | } | 536 | } |
| @@ -794,15 +692,10 @@ impl Parser<'_> { | |||
| 794 | 692 | ||
| 795 | if skip { | 693 | if skip { |
| 796 | self.stats.skip_cus += 1; | 694 | self.stats.skip_cus += 1; |
| 797 | - let geom = CuGeometry { | ||
| 798 | - x: x0, | ||
| 799 | - y: y0, | ||
| 800 | - size: n, | ||
| 801 | - part_mode: PartMode::Part2Nx2N, | ||
| 802 | - skip: true, | ||
| 803 | - }; | ||
| 804 | let pu = self.prediction_unit(dec, x0, y0, n, n, depth, true)?; | 695 | let pu = self.prediction_unit(dec, x0, y0, n, n, depth, true)?; |
| 805 | - let m = self.motion.derive_motion(&geom, 0, &pu); | 696 | + let m = self |
| 697 | + .motion | ||
| 698 | + .derive_motion(x0, y0, n, PartMode::Part2Nx2N, 0, &pu); | ||
| 806 | self.predict_pu(x0, y0, n, n, &m)?; | 699 | self.predict_pu(x0, y0, n, n, &m)?; |
| 807 | cu.motion.push(m); | 700 | cu.motion.push(m); |
| 808 | cu.pus.push(pu); | 701 | cu.pus.push(pu); |
| @@ -852,16 +745,9 @@ impl Parser<'_> { | |||
| 852 | } else { | 745 | } else { |
| 853 | PartMode::Part2Nx2N | 746 | PartMode::Part2Nx2N |
| 854 | }; | 747 | }; |
| 855 | - let geom = CuGeometry { | ||
| 856 | - x: x0, | ||
| 857 | - y: y0, | ||
| 858 | - size: n, | ||
| 859 | - part_mode: cu.part_mode, | ||
| 860 | - skip: false, | ||
| 861 | - }; | ||
| 862 | for (i, (px, py, pw, ph)) in pu_rects(cu.part_mode, x0, y0, n).into_iter().enumerate() { | 748 | for (i, (px, py, pw, ph)) in pu_rects(cu.part_mode, x0, y0, n).into_iter().enumerate() { |
| 863 | let pu = self.prediction_unit(dec, px, py, pw, ph, depth, false)?; | 749 | let pu = self.prediction_unit(dec, px, py, pw, ph, depth, false)?; |
| 864 | - let m = self.motion.derive_motion(&geom, i, &pu); | 750 | + let m = self.motion.derive_motion(x0, y0, n, cu.part_mode, i, &pu); |
| 865 | self.predict_pu(px, py, pw, ph, &m)?; | 751 | self.predict_pu(px, py, pw, ph, &m)?; |
| 866 | self.pic.mark_edges(px, py, pw, ph, EDGE_PU); | 752 | self.pic.mark_edges(px, py, pw, ph, EDGE_PU); |
| 867 | cu.motion.push(m); | 753 | cu.motion.push(m); |
| @@ -890,11 +776,8 @@ impl Parser<'_> { | |||
| 890 | } | 776 | } |
| 891 | 777 | ||
| 892 | /// Motion-compensated prediction of one prediction unit (8.5.3.3) into the | 778 | /// Motion-compensated prediction of one prediction unit (8.5.3.3) into the |
| 893 | - /// picture's samples. Nothing happens without pixel decode. | 779 | + /// picture's samples. |
| 894 | fn predict_pu(&mut self, x: usize, y: usize, w: usize, h: usize, m: &Motion) -> Result<()> { | 780 | fn predict_pu(&mut self, x: usize, y: usize, w: usize, h: usize, m: &Motion) -> Result<()> { |
| 895 | - if !self.pic.has_pixels() { | ||
| 896 | - return Ok(()); | ||
| 897 | - } | ||
| 898 | let Some(refs) = self.refs else { | 781 | let Some(refs) = self.refs else { |
| 899 | return Err(Error::corrupt( | 782 | return Err(Error::corrupt( |
| 900 | "HEVC decode: an inter prediction unit in a slice with no reference lists", | 783 | "HEVC decode: an inter prediction unit in a slice with no reference lists", |
| @@ -1249,7 +1132,7 @@ impl Parser<'_> { | |||
| 1249 | } | 1132 | } |
| 1250 | 1133 | ||
| 1251 | /// The transform unit (7.3.8.10): the QP delta, then each coded block's | 1134 | /// The transform unit (7.3.8.10): the QP delta, then each coded block's |
| 1252 | - /// residual. With pixel decode on, an intra block is predicted and | 1135 | + /// residual. An intra block is predicted and |
| 1253 | /// reconstructed here, in the order luma, Cb, Cr that its neighbours need. | 1136 | /// reconstructed here, in the order luma, Cb, Cr that its neighbours need. |
| 1254 | fn transform_unit( | 1137 | fn transform_unit( |
| 1255 | &mut self, | 1138 | &mut self, |
| @@ -1284,7 +1167,7 @@ impl Parser<'_> { | |||
| 1284 | { | 1167 | { |
| 1285 | self.cu_chroma_qp_offset(dec); | 1168 | self.cu_chroma_qp_offset(dec); |
| 1286 | } | 1169 | } |
| 1287 | - let recon = tx.intra && self.pic.has_pixels(); | 1170 | + let recon = tx.intra; |
| 1288 | let luma_mode = tx | 1171 | let luma_mode = tx |
| 1289 | .intra | 1172 | .intra |
| 1290 | .then(|| self.pic.info[self.pic.unit(x0, y0)].intra_mode); | 1173 | .then(|| self.pic.info[self.pic.unit(x0, y0)].intra_mode); |
| @@ -1680,13 +1563,11 @@ impl Parser<'_> { | |||
| 1680 | } else { | 1563 | } else { |
| 1681 | (x0 >> sx, y0 >> sy) | 1564 | (x0 >> sx, y0 >> sy) |
| 1682 | }; | 1565 | }; |
| 1683 | - if self.pic.has_pixels() { | 1566 | + let origin = self.pic.plane_origin(c); |
| 1684 | - let origin = self.pic.plane_origin(c); | 1567 | + let (stride, plane) = self.pic.plane_view_mut(c); |
| 1685 | - let (stride, plane) = self.pic.plane_view_mut(c); | 1568 | + for j in 0..sh { |
| 1686 | - for j in 0..sh { | 1569 | + let start = (y + j - origin) * stride + x; |
| 1687 | - let start = (y + j - origin) * stride + x; | 1570 | + plane[start..start + sw].copy_from_slice(&samples[j * sw..j * sw + sw]); |
| 1688 | - plane[start..start + sw].copy_from_slice(&samples[j * sw..j * sw + sw]); | ||
| 1689 | - } | ||
| 1690 | } | 1571 | } |
| 1691 | } | 1572 | } |
| 1692 | self.pic.update_info(x0, y0, n, n, |b| b.pcm = true); | 1573 | self.pic.update_info(x0, y0, n, n, |b| b.pcm = true); |
crates/ec-h265/src/dec/cu_syntax/wpp.rsmodified+34 -63
| @@ -18,13 +18,12 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; | |||
| 18 | use std::sync::atomic::{AtomicUsize, Ordering}; | 18 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 19 | use std::sync::{Condvar, Mutex, MutexGuard}; | 19 | use std::sync::{Condvar, Mutex, MutexGuard}; |
| 20 | 20 | ||
| 21 | -use super::{MotionSource, SliceStats, new_parser, trailing_bits_ok}; | 21 | +use super::{SliceStats, new_parser, trailing_bits_ok}; |
| 22 | use crate::cabac::{CabacDecoder, Contexts}; | 22 | use crate::cabac::{CabacDecoder, Contexts}; |
| 23 | use crate::dec::inter::InterRefs; | 23 | use crate::dec::inter::InterRefs; |
| 24 | use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion}; | 24 | use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion}; |
| 25 | use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter}; | 25 | use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter}; |
| 26 | use crate::dec::tiles::TileScan; | 26 | use crate::dec::tiles::TileScan; |
| 27 | -use crate::dec::trace::{self, Phase}; | ||
| 28 | use ec_core::error::{Error, Result}; | 27 | use ec_core::error::{Error, Result}; |
| 29 | use ec_h265_syntax::slice::{SliceHeader, SliceType}; | 28 | use ec_h265_syntax::slice::{SliceHeader, SliceType}; |
| 30 | use ec_h265_syntax::{Pps, Sps}; | 29 | use ec_h265_syntax::{Pps, Sps}; |
| @@ -105,13 +104,11 @@ impl Board { | |||
| 105 | let cw = self.width.div_ceil(1 << self.sub_x); | 104 | let cw = self.width.div_ceil(1 << self.sub_x); |
| 106 | let mut st = lock(&self.state); | 105 | let mut st = lock(&self.state); |
| 107 | let slot = &mut st.slots[ry]; | 106 | let slot = &mut st.slots[ry]; |
| 108 | - if pic.has_pixels() { | 107 | + let lr = (y0 + ctb - 1) - pic.origin_y; |
| 109 | - let lr = (y0 + ctb - 1) - pic.origin_y; | 108 | + slot.luma = pic.planes.y[lr * self.width..(lr + 1) * self.width].to_vec(); |
| 110 | - slot.luma = pic.planes.y[lr * self.width..(lr + 1) * self.width].to_vec(); | 109 | + let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; |
| 111 | - let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; | 110 | + slot.cb = pic.planes.cb[lc * cw..(lc + 1) * cw].to_vec(); |
| 112 | - slot.cb = pic.planes.cb[lc * cw..(lc + 1) * cw].to_vec(); | 111 | + slot.cr = pic.planes.cr[lc * cw..(lc + 1) * cw].to_vec(); |
| 113 | - slot.cr = pic.planes.cr[lc * cw..(lc + 1) * cw].to_vec(); | ||
| 114 | - } | ||
| 115 | let ur = (y0 + ctb - 4) / 4; | 112 | let ur = (y0 + ctb - 4) / 4; |
| 116 | let band_row = ur - pic.origin_unit / 4; | 113 | let band_row = ur - pic.origin_unit / 4; |
| 117 | slot.units = pic.info[band_row * self.w4..(band_row + 1) * self.w4].to_vec(); | 114 | slot.units = pic.info[band_row * self.w4..(band_row + 1) * self.w4].to_vec(); |
| @@ -130,7 +127,7 @@ impl Board { | |||
| 130 | ry: usize, | 127 | ry: usize, |
| 131 | x: usize, | 128 | x: usize, |
| 132 | pic: &mut PicState, | 129 | pic: &mut PicState, |
| 133 | - motion: &mut dyn MotionSource, | 130 | + motion: &mut SliceMotion<'_>, |
| 134 | ) -> Result<Option<Contexts>> { | 131 | ) -> Result<Option<Contexts>> { |
| 135 | if ry == 0 { | 132 | if ry == 0 { |
| 136 | return Ok(None); | 133 | return Ok(None); |
| @@ -139,7 +136,6 @@ impl Board { | |||
| 139 | let cols = self.cols; | 136 | let cols = self.cols; |
| 140 | let need = (x + 2).min(cols); | 137 | let need = (x + 2).min(cols); |
| 141 | let mut st = lock(&self.state); | 138 | let mut st = lock(&self.state); |
| 142 | - let t = trace::now(); | ||
| 143 | loop { | 139 | loop { |
| 144 | if let Some(why) = &st.failed { | 140 | if let Some(why) = &st.failed { |
| 145 | return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}"))); | 141 | return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}"))); |
| @@ -149,7 +145,6 @@ impl Board { | |||
| 149 | } | 145 | } |
| 150 | st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner()); | 146 | st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner()); |
| 151 | } | 147 | } |
| 152 | - trace::since(Phase::WaitSync, t); | ||
| 153 | let slot = &st.slots[ry - 1]; | 148 | let slot = &st.slots[ry - 1]; |
| 154 | let k0 = x.saturating_sub(1); | 149 | let k0 = x.saturating_sub(1); |
| 155 | let k1 = (x + 1).min(cols - 1); | 150 | let k1 = (x + 1).min(cols - 1); |
| @@ -160,19 +155,15 @@ impl Board { | |||
| 160 | (k * ctb) >> self.sub_x, | 155 | (k * ctb) >> self.sub_x, |
| 161 | (((k + 1) * ctb) >> self.sub_x).min(cw), | 156 | (((k + 1) * ctb) >> self.sub_x).min(cw), |
| 162 | ); | 157 | ); |
| 163 | - if pic.has_pixels() { | 158 | + pic.planes.y[a..b].copy_from_slice(&slot.luma[a..b]); |
| 164 | - pic.planes.y[a..b].copy_from_slice(&slot.luma[a..b]); | 159 | + pic.planes.cb[ca..cb_end].copy_from_slice(&slot.cb[ca..cb_end]); |
| 165 | - pic.planes.cb[ca..cb_end].copy_from_slice(&slot.cb[ca..cb_end]); | 160 | + pic.planes.cr[ca..cb_end].copy_from_slice(&slot.cr[ca..cb_end]); |
| 166 | - pic.planes.cr[ca..cb_end].copy_from_slice(&slot.cr[ca..cb_end]); | ||
| 167 | - } | ||
| 168 | let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); | 161 | let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); |
| 169 | pic.info[ua..ub].copy_from_slice(&slot.units[ua..ub]); | 162 | pic.info[ua..ub].copy_from_slice(&slot.units[ua..ub]); |
| 170 | pic.ctb[(ry - 1) * cols + k] = slot.ctb[k]; | 163 | pic.ctb[(ry - 1) * cols + k] = slot.ctb[k]; |
| 171 | } | 164 | } |
| 172 | let unit_row = (ry << self.ctb_log2) / 4 - 1; | 165 | let unit_row = (ry << self.ctb_log2) / 4 - 1; |
| 173 | - let field = motion | 166 | + let field = &mut *motion.field; |
| 174 | - .band_cells() | ||
| 175 | - .ok_or_else(|| Error::corrupt("HEVC slice (wavefront): a row without a motion band"))?; | ||
| 176 | for k in k0..=k1 { | 167 | for k in k0..=k1 { |
| 177 | let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); | 168 | let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); |
| 178 | field.cell_row_mut(unit_row)[ua..ub].copy_from_slice(&slot.cells[ua..ub]); | 169 | field.cell_row_mut(unit_row)[ua..ub].copy_from_slice(&slot.cells[ua..ub]); |
| @@ -187,7 +178,7 @@ impl Board { | |||
| 187 | ry: usize, | 178 | ry: usize, |
| 188 | x: usize, | 179 | x: usize, |
| 189 | pic: &PicState, | 180 | pic: &PicState, |
| 190 | - motion: &mut dyn MotionSource, | 181 | + motion: &mut SliceMotion<'_>, |
| 191 | wpp: Option<&Contexts>, | 182 | wpp: Option<&Contexts>, |
| 192 | ) -> Result<()> { | 183 | ) -> Result<()> { |
| 193 | let ctb = 1usize << self.ctb_log2; | 184 | let ctb = 1usize << self.ctb_log2; |
| @@ -200,13 +191,7 @@ impl Board { | |||
| 200 | (((x + 1) * ctb) >> self.sub_x).min(cw), | 191 | (((x + 1) * ctb) >> self.sub_x).min(cw), |
| 201 | ); | 192 | ); |
| 202 | let (ua, ub) = (x * ctb / 4, ((x + 1) * ctb / 4).min(self.w4)); | 193 | let (ua, ub) = (x * ctb / 4, ((x + 1) * ctb / 4).min(self.w4)); |
| 203 | - let field = if full { | 194 | + let field = if full { Some(&mut *motion.field) } else { None }; |
| 204 | - Some(motion.band_cells().ok_or_else(|| { | ||
| 205 | - Error::corrupt("HEVC slice (wavefront): a row without a motion band") | ||
| 206 | - })?) | ||
| 207 | - } else { | ||
| 208 | - None | ||
| 209 | - }; | ||
| 210 | let mut st = lock(&self.state); | 195 | let mut st = lock(&self.state); |
| 211 | let slot = &mut st.slots[ry]; | 196 | let slot = &mut st.slots[ry]; |
| 212 | if slot.ctb.is_empty() { | 197 | if slot.ctb.is_empty() { |
| @@ -219,14 +204,12 @@ impl Board { | |||
| 219 | } | 204 | } |
| 220 | if full { | 205 | if full { |
| 221 | // Band rows: the sample rows and unit row of the CTB row's last rows. | 206 | // Band rows: the sample rows and unit row of the CTB row's last rows. |
| 222 | - if pic.has_pixels() { | 207 | + let lr = (y0 + ctb - 1) - pic.origin_y; |
| 223 | - let lr = (y0 + ctb - 1) - pic.origin_y; | 208 | + slot.luma[a..b] |
| 224 | - slot.luma[a..b] | 209 | + .copy_from_slice(&pic.planes.y[lr * self.width + a..lr * self.width + b]); |
| 225 | - .copy_from_slice(&pic.planes.y[lr * self.width + a..lr * self.width + b]); | 210 | + let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; |
| 226 | - let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; | 211 | + slot.cb[ca..cb_end].copy_from_slice(&pic.planes.cb[lc * cw + ca..lc * cw + cb_end]); |
| 227 | - slot.cb[ca..cb_end].copy_from_slice(&pic.planes.cb[lc * cw + ca..lc * cw + cb_end]); | 212 | + slot.cr[ca..cb_end].copy_from_slice(&pic.planes.cr[lc * cw + ca..lc * cw + cb_end]); |
| 228 | - slot.cr[ca..cb_end].copy_from_slice(&pic.planes.cr[lc * cw + ca..lc * cw + cb_end]); | ||
| 229 | - } | ||
| 230 | let ur = (y0 + ctb - 4) / 4; | 213 | let ur = (y0 + ctb - 4) / 4; |
| 231 | let band_row = ur - pic.origin_unit / 4; | 214 | let band_row = ur - pic.origin_unit / 4; |
| 232 | slot.units[ua..ub] | 215 | slot.units[ua..ub] |
| @@ -263,13 +246,13 @@ trait RowSync { | |||
| 263 | fn enter( | 246 | fn enter( |
| 264 | &mut self, | 247 | &mut self, |
| 265 | pic: &mut PicState, | 248 | pic: &mut PicState, |
| 266 | - motion: &mut dyn MotionSource, | 249 | + motion: &mut SliceMotion<'_>, |
| 267 | x: usize, | 250 | x: usize, |
| 268 | ) -> Result<Option<Contexts>>; | 251 | ) -> Result<Option<Contexts>>; |
| 269 | fn leave( | 252 | fn leave( |
| 270 | &mut self, | 253 | &mut self, |
| 271 | pic: &PicState, | 254 | pic: &PicState, |
| 272 | - motion: &mut dyn MotionSource, | 255 | + motion: &mut SliceMotion<'_>, |
| 273 | x: usize, | 256 | x: usize, |
| 274 | wpp: Option<&Contexts>, | 257 | wpp: Option<&Contexts>, |
| 275 | ) -> Result<()>; | 258 | ) -> Result<()>; |
| @@ -279,7 +262,7 @@ impl RowSync for Link<'_> { | |||
| 279 | fn enter( | 262 | fn enter( |
| 280 | &mut self, | 263 | &mut self, |
| 281 | pic: &mut PicState, | 264 | pic: &mut PicState, |
| 282 | - motion: &mut dyn MotionSource, | 265 | + motion: &mut SliceMotion<'_>, |
| 283 | x: usize, | 266 | x: usize, |
| 284 | ) -> Result<Option<Contexts>> { | 267 | ) -> Result<Option<Contexts>> { |
| 285 | self.board.enter(self.ry, x, pic, motion) | 268 | self.board.enter(self.ry, x, pic, motion) |
| @@ -288,7 +271,7 @@ impl RowSync for Link<'_> { | |||
| 288 | fn leave( | 271 | fn leave( |
| 289 | &mut self, | 272 | &mut self, |
| 290 | pic: &PicState, | 273 | pic: &PicState, |
| 291 | - motion: &mut dyn MotionSource, | 274 | + motion: &mut SliceMotion<'_>, |
| 292 | x: usize, | 275 | x: usize, |
| 293 | wpp: Option<&Contexts>, | 276 | wpp: Option<&Contexts>, |
| 294 | ) -> Result<()> { | 277 | ) -> Result<()> { |
| @@ -328,7 +311,7 @@ fn parse_row( | |||
| 328 | pps: &Pps, | 311 | pps: &Pps, |
| 329 | header: &SliceHeader, | 312 | header: &SliceHeader, |
| 330 | pic: &mut PicState, | 313 | pic: &mut PicState, |
| 331 | - motion: &mut dyn MotionSource, | 314 | + motion: &mut SliceMotion<'_>, |
| 332 | refs: Option<&InterRefs>, | 315 | refs: Option<&InterRefs>, |
| 333 | seg: &SegConsts, | 316 | seg: &SegConsts, |
| 334 | data: &[u8], | 317 | data: &[u8], |
| @@ -504,7 +487,6 @@ pub(in crate::dec) fn parse_segment( | |||
| 504 | if ry0 > 0 { | 487 | if ry0 > 0 { |
| 505 | board.prefill(ry0 - 1, pic, &*source.field); | 488 | board.prefill(ry0 - 1, pic, &*source.field); |
| 506 | } | 489 | } |
| 507 | - let pixels = pic.has_pixels(); | ||
| 508 | let next = AtomicUsize::new(0); | 490 | let next = AtomicUsize::new(0); |
| 509 | let lists = source.lists; | 491 | let lists = source.lists; |
| 510 | let cur_poc = source.cur_poc; | 492 | let cur_poc = source.cur_poc; |
| @@ -520,7 +502,7 @@ pub(in crate::dec) fn parse_segment( | |||
| 520 | let y0 = ry << ctb_log2; | 502 | let y0 = ry << ctb_log2; |
| 521 | let bound = usize::from(ry > 0); | 503 | let bound = usize::from(ry > 0); |
| 522 | let own = ctb.min(global.height - y0); | 504 | let own = ctb.min(global.height - y0); |
| 523 | - let mut band = global.band(y0, own, pixels); | 505 | + let mut band = global.band(y0, own); |
| 524 | let mut field = field_global.band((y0 - 4 * bound) / 4, bound + own.div_ceil(4)); | 506 | let mut field = field_global.band((y0 - 4 * bound) / 4, bound + own.div_ceil(4)); |
| 525 | let row_start = if i == 0 { 0 } else { starts[i - 1] }; | 507 | let row_start = if i == 0 { 0 } else { starts[i - 1] }; |
| 526 | let row_len = (!last).then(|| starts[i] - row_start); | 508 | let row_len = (!last).then(|| starts[i] - row_start); |
| @@ -569,9 +551,7 @@ pub(in crate::dec) fn parse_segment( | |||
| 569 | break; | 551 | break; |
| 570 | } | 552 | } |
| 571 | let ry = ry0 + i; | 553 | let ry = ry0 + i; |
| 572 | - let t = trace::now(); | ||
| 573 | let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry))); | 554 | let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry))); |
| 574 | - trace::since(Phase::Decode, t); | ||
| 575 | match outcome { | 555 | match outcome { |
| 576 | Ok(Ok(row)) => done.push(row), | 556 | Ok(Ok(row)) => done.push(row), |
| 577 | Ok(Err(e)) => { | 557 | Ok(Err(e)) => { |
| @@ -587,14 +567,7 @@ pub(in crate::dec) fn parse_segment( | |||
| 587 | Ok(done) | 567 | Ok(done) |
| 588 | }; | 568 | }; |
| 589 | let results: Vec<Result<Vec<RowDone>>> = std::thread::scope(|s| { | 569 | let results: Vec<Result<Vec<RowDone>>> = std::thread::scope(|s| { |
| 590 | - let helpers: Vec<_> = (1..workers.clamp(1, nrows)) | 570 | + let helpers: Vec<_> = (1..workers.clamp(1, nrows)).map(|_| s.spawn(run)).collect(); |
| 591 | - .map(|_| { | ||
| 592 | - s.spawn(|| { | ||
| 593 | - trace::set_role("wpp-helper"); | ||
| 594 | - run() | ||
| 595 | - }) | ||
| 596 | - }) | ||
| 597 | - .collect(); | ||
| 598 | let mut all = vec![run()]; | 571 | let mut all = vec![run()]; |
| 599 | for h in helpers { | 572 | for h in helpers { |
| 600 | all.push(h.join().unwrap_or_else(|_| { | 573 | all.push(h.join().unwrap_or_else(|_| { |
| @@ -625,16 +598,14 @@ pub(in crate::dec) fn parse_segment( | |||
| 625 | let (sx, sy) = (pic.sub_x(), pic.sub_y()); | 598 | let (sx, sy) = (pic.sub_x(), pic.sub_y()); |
| 626 | let own_c = own.div_ceil(1 << sy); | 599 | let own_c = own.div_ceil(1 << sy); |
| 627 | let cw = pic.width.div_ceil(1 << sx); | 600 | let cw = pic.width.div_ceil(1 << sx); |
| 628 | - if pixels { | 601 | + let w = pic.width; |
| 629 | - let w = pic.width; | 602 | + pic.planes.y[y0 * w..(y0 + own) * w] |
| 630 | - pic.planes.y[y0 * w..(y0 + own) * w] | 603 | + .copy_from_slice(&done.band.planes.y[bound * w..(bound + own) * w]); |
| 631 | - .copy_from_slice(&done.band.planes.y[bound * w..(bound + own) * w]); | 604 | + let (c0, c1) = (y0 >> sy, (y0 >> sy) + own_c); |
| 632 | - let (c0, c1) = (y0 >> sy, (y0 >> sy) + own_c); | 605 | + pic.planes.cb[c0 * cw..c1 * cw] |
| 633 | - pic.planes.cb[c0 * cw..c1 * cw] | 606 | + .copy_from_slice(&done.band.planes.cb[bound * cw..(bound + own_c) * cw]); |
| 634 | - .copy_from_slice(&done.band.planes.cb[bound * cw..(bound + own_c) * cw]); | 607 | + pic.planes.cr[c0 * cw..c1 * cw] |
| 635 | - pic.planes.cr[c0 * cw..c1 * cw] | 608 | + .copy_from_slice(&done.band.planes.cr[bound * cw..(bound + own_c) * cw]); |
| 636 | - .copy_from_slice(&done.band.planes.cr[bound * cw..(bound + own_c) * cw]); | ||
| 637 | - } | ||
| 638 | let u0 = y0 / 4; | 609 | let u0 = y0 / 4; |
| 639 | let units = own.div_ceil(4); | 610 | let units = own.div_ceil(4); |
| 640 | pic.info[u0 * pic.w4..(u0 + units) * pic.w4] | 611 | pic.info[u0 * pic.w4..(u0 + units) * pic.w4] |
crates/ec-h265/src/dec/deblock.rsmodified+1 -4
| @@ -432,9 +432,6 @@ pub fn deblock_picture(pic: &mut PicState) { | |||
| 432 | /// side is in the rows above are filtered after those rows' own vertical edges, which | 432 | /// side is in the rows above are filtered after those rows' own vertical edges, which |
| 433 | /// is the order 8.7.2 gives for the whole picture. | 433 | /// is the order 8.7.2 gives for the whole picture. |
| 434 | pub fn deblock_rows(pic: &mut PicState, rows: Range<usize>) { | 434 | pub fn deblock_rows(pic: &mut PicState, rows: Range<usize>) { |
| 435 | - if !pic.has_pixels() { | ||
| 436 | - return; | ||
| 437 | - } | ||
| 438 | let (w, h) = (pic.width, pic.height); | 435 | let (w, h) = (pic.width, pic.height); |
| 439 | let (sx, sy) = (pic.sub_x(), pic.sub_y()); | 436 | let (sx, sy) = (pic.sub_x(), pic.sub_y()); |
| 440 | let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy)); | 437 | let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy)); |
| @@ -484,7 +481,7 @@ mod tests { | |||
| 484 | /// A 16x16 picture whose luma column `x` holds `value(x)`, with flat chroma, | 481 | /// A 16x16 picture whose luma column `x` holds `value(x)`, with flat chroma, |
| 485 | /// every unit intra at QP 37 and an edge on every unit. | 482 | /// every unit intra at QP 37 and an edge on every unit. |
| 486 | fn picture(value: impl Fn(usize) -> u16) -> PicState { | 483 | fn picture(value: impl Fn(usize) -> u16) -> PicState { |
| 487 | - let mut pic = PicState::new(16, 16, 4, 2, 8, 8, true); | 484 | + let mut pic = PicState::new(16, 16, 4, 2, 8, 8); |
| 488 | for y in 0..16 { | 485 | for y in 0..16 { |
| 489 | for x in 0..16 { | 486 | for x in 0..16 { |
| 490 | pic.planes.y[y * 16 + x] = value(x); | 487 | pic.planes.y[y * 16 + x] = value(x); |
crates/ec-h265/src/dec/dpb.rsmodified+5 -3
| @@ -40,8 +40,7 @@ pub struct DpbPicture { | |||
| 40 | pub au_index: u32, | 40 | pub au_index: u32, |
| 41 | /// Cropping of the SPS the picture was decoded under. | 41 | /// Cropping of the SPS the picture was decoded under. |
| 42 | pub window: ConformanceWindow, | 42 | pub window: ConformanceWindow, |
| 43 | - /// The samples and the collocated motion (8.5.3.2.8). Empty samples when the decoder | 43 | + /// The samples and the collocated motion (8.5.3.2.8). The samples may still be being decoded. |
| 44 | - /// runs without pixel decode. The samples may still be being decoded. | ||
| 45 | pub picture: Arc<SharedPic>, | 44 | pub picture: Arc<SharedPic>, |
| 46 | /// HDR, colour and hash metadata of the picture. | 45 | /// HDR, colour and hash metadata of the picture. |
| 47 | pub meta: Arc<PictureMeta>, | 46 | pub meta: Arc<PictureMeta>, |
| @@ -97,7 +96,10 @@ impl Frame { | |||
| 97 | pub fn cropped(&self) -> DecodedPicture { | 96 | pub fn cropped(&self) -> DecodedPicture { |
| 98 | let p = &self.picture; | 97 | let p = &self.picture; |
| 99 | let (sx, sy) = crate::decode::chroma_shifts(p.chroma_format_idc); | 98 | let (sx, sy) = crate::decode::chroma_shifts(p.chroma_format_idc); |
| 100 | - let (left, top) = ((self.window.left << sx) as usize, (self.window.top << sy) as usize); | 99 | + let (left, top) = ( |
| 100 | + (self.window.left << sx) as usize, | ||
| 101 | + (self.window.top << sy) as usize, | ||
| 102 | + ); | ||
| 101 | let width = p.width - left - ((self.window.right << sx) as usize); | 103 | let width = p.width - left - ((self.window.right << sx) as usize); |
| 102 | let height = p.height - top - ((self.window.bottom << sy) as usize); | 104 | let height = p.height - top - ((self.window.bottom << sy) as usize); |
| 103 | let crop = |plane: &[u16], stride: usize, x: usize, y: usize, w: usize, h: usize| { | 105 | let crop = |plane: &[u16], stride: usize, x: usize, y: usize, w: usize, h: usize| { |
crates/ec-h265/src/dec/inter.rsmodified+1 -4
| @@ -168,9 +168,6 @@ fn ref_picture(pic: &DecodedPicture) -> RefPicture<'_> { | |||
| 168 | /// Add the residual blocks of an inter coding unit to the samples its prediction | 168 | /// Add the residual blocks of an inter coding unit to the samples its prediction |
| 169 | /// units already wrote. | 169 | /// units already wrote. |
| 170 | pub fn add_residuals(pic: &mut PicState, residuals: &[ResidualBlock]) { | 170 | pub fn add_residuals(pic: &mut PicState, residuals: &[ResidualBlock]) { |
| 171 | - if !pic.has_pixels() { | ||
| 172 | - return; | ||
| 173 | - } | ||
| 174 | for block in residuals { | 171 | for block in residuals { |
| 175 | pic.add_residual( | 172 | pic.add_residual( |
| 176 | block.component, | 173 | block.component, |
| @@ -196,7 +193,7 @@ mod tests { | |||
| 196 | let (tx, rx) = mpsc::channel(); | 193 | let (tx, rx) = mpsc::channel(); |
| 197 | std::thread::spawn(move || { | 194 | std::thread::spawn(move || { |
| 198 | let (w, h) = (64usize, 64usize); | 195 | let (w, h) = (64usize, 64usize); |
| 199 | - let pic = Arc::new(SharedPic::new(0, w, h, (8, 8), true, 1)); | 196 | + let pic = Arc::new(SharedPic::new(0, w, h, (8, 8), 1)); |
| 200 | let src = DecodedPicture { | 197 | let src = DecodedPicture { |
| 201 | width: w, | 198 | width: w, |
| 202 | height: h, | 199 | height: h, |
crates/ec-h265/src/dec/mc.rsmodified+0 -4
| @@ -474,7 +474,3 @@ pub(super) fn check_out(dst: &PlaneMut<'_>, blk: Block) -> Result<()> { | |||
| 474 | } | 474 | } |
| 475 | check_depth(dst.bit_depth) | 475 | check_depth(dst.bit_depth) |
| 476 | } | 476 | } |
| 477 | - | ||
| 478 | -#[cfg(test)] | ||
| 479 | -#[path = "mc_tests.rs"] | ||
| 480 | -mod tests; | ||
crates/ec-h265/src/dec/mc_tests.rsdeleted+0 -1137
| @@ -1,1137 +0,0 @@ | |||
| 1 | -//! Tests of the motion compensation: hand-computed values for every fraction, | ||
| 2 | -//! edge clamping, weighted prediction, a per-sample reference model compared on | ||
| 3 | -//! random blocks, and a 1080p timing run. | ||
| 4 | - | ||
| 5 | -use crate::dec::cu_syntax::Motion; | ||
| 6 | -use crate::dec::mc::{ | ||
| 7 | - Block, McScratch, PlaneMut, PlaneRef, RefPicture, interp_chroma, interp_luma, predict_pu, | ||
| 8 | -}; | ||
| 9 | -use crate::dec::weighted::{ExplicitWeights, Weight, store}; | ||
| 10 | -use ec_h265_syntax::{PredWeightTable, WeightEntry}; | ||
| 11 | - | ||
| 12 | -/// A plane of `w x h` samples from `f(x, y)`, stride `w`. | ||
| 13 | -fn plane_from(w: usize, h: usize, bd: u32, f: impl Fn(usize, usize) -> u16) -> Vec<u16> { | ||
| 14 | - (0..h) | ||
| 15 | - .flat_map(|y| (0..w).map(move |x| (x, y))) | ||
| 16 | - .map(|(x, y)| f(x, y)) | ||
| 17 | - .map(|v| v.min((1 << bd) - 1)) | ||
| 18 | - .collect() | ||
| 19 | -} | ||
| 20 | - | ||
| 21 | -fn view(samples: &[u16], w: usize, h: usize, bd: u32) -> PlaneRef<'_> { | ||
| 22 | - PlaneRef { | ||
| 23 | - samples, | ||
| 24 | - stride: w, | ||
| 25 | - width: w, | ||
| 26 | - height: h, | ||
| 27 | - bit_depth: bd, | ||
| 28 | - } | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -fn motion(pred_flags: [bool; 2], ref_idx: [i8; 2], mv: [[i32; 2]; 2]) -> Motion { | ||
| 32 | - Motion { | ||
| 33 | - pred_flags, | ||
| 34 | - ref_idx, | ||
| 35 | - mv, | ||
| 36 | - } | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -/// A 16x16 luma plane that is zero except for `value` at (8, 8). | ||
| 40 | -fn impulse16(value: u16) -> Vec<u16> { | ||
| 41 | - plane_from(16, 16, 10, |x, y| if (x, y) == (8, 8) { value } else { 0 }) | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -#[test] | ||
| 45 | -fn luma_impulse_fractions_8bit_hand_values() { | ||
| 46 | - // Impulse of 100 at column 8; the block starts at column 4 on row 8, so output | ||
| 47 | - // j reads the impulse with tap index 7 - j. shift1 = 0 at 8 bits. | ||
| 48 | - let p = impulse16(100); | ||
| 49 | - let pl = view(&p, 16, 16, 8); | ||
| 50 | - let blk = Block { | ||
| 51 | - x: 4, | ||
| 52 | - y: 8, | ||
| 53 | - width: 4, | ||
| 54 | - height: 1, | ||
| 55 | - }; | ||
| 56 | - let mut scratch = McScratch::new(); | ||
| 57 | - let mut out = [0i32; 4]; | ||
| 58 | - let cases: [(i32, [i32; 4]); 3] = [ | ||
| 59 | - (1, [0, 100, -500, 1700]), | ||
| 60 | - (2, [-100, 400, -1100, 4000]), | ||
| 61 | - (3, [-100, 400, -1000, 5800]), | ||
| 62 | - ]; | ||
| 63 | - for (frac, want) in cases { | ||
| 64 | - interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); | ||
| 65 | - assert_eq!(out, want, "luma horizontal fraction {frac}"); | ||
| 66 | - } | ||
| 67 | - // Full-sample position: the impulse shifted by shift3 = 14 - 8 = 6. | ||
| 68 | - let full = Block { | ||
| 69 | - x: 8, | ||
| 70 | - y: 8, | ||
| 71 | - width: 1, | ||
| 72 | - height: 1, | ||
| 73 | - }; | ||
| 74 | - interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); | ||
| 75 | - assert_eq!(out[0], 100 << 6); | ||
| 76 | -} | ||
| 77 | - | ||
| 78 | -#[test] | ||
| 79 | -fn luma_impulse_fractions_10bit_hand_values() { | ||
| 80 | - // shift1 = 2 at 10 bits, so each tap sum is divided by 4 (exact here). | ||
| 81 | - let p = impulse16(1000); | ||
| 82 | - let pl = view(&p, 16, 16, 10); | ||
| 83 | - let blk = Block { | ||
| 84 | - x: 4, | ||
| 85 | - y: 8, | ||
| 86 | - width: 4, | ||
| 87 | - height: 1, | ||
| 88 | - }; | ||
| 89 | - let mut scratch = McScratch::new(); | ||
| 90 | - let mut out = [0i32; 4]; | ||
| 91 | - let cases: [(i32, [i32; 4]); 3] = [ | ||
| 92 | - (1, [0, 250, -1250, 4250]), | ||
| 93 | - (2, [-250, 1000, -2750, 10000]), | ||
| 94 | - (3, [-250, 1000, -2500, 14500]), | ||
| 95 | - ]; | ||
| 96 | - for (frac, want) in cases { | ||
| 97 | - interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); | ||
| 98 | - assert_eq!(out, want, "10-bit luma horizontal fraction {frac}"); | ||
| 99 | - } | ||
| 100 | - let full = Block { | ||
| 101 | - x: 8, | ||
| 102 | - y: 8, | ||
| 103 | - width: 1, | ||
| 104 | - height: 1, | ||
| 105 | - }; | ||
| 106 | - interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); | ||
| 107 | - assert_eq!(out[0], 1000 << 4, "10-bit full sample shift3 = 4"); | ||
| 108 | -} | ||
| 109 | - | ||
| 110 | -#[test] | ||
| 111 | -fn luma_vertical_only_matches_horizontal_by_symmetry() { | ||
| 112 | - let p = impulse16(100); | ||
| 113 | - let pl = view(&p, 16, 16, 8); | ||
| 114 | - // Block column 8, rows 4..8: output row k reads the impulse at tap 7 - k. | ||
| 115 | - let blk = Block { | ||
| 116 | - x: 8, | ||
| 117 | - y: 4, | ||
| 118 | - width: 1, | ||
| 119 | - height: 4, | ||
| 120 | - }; | ||
| 121 | - let mut scratch = McScratch::new(); | ||
| 122 | - let mut out = [0i32; 4]; | ||
| 123 | - interp_luma(&pl, blk, [0, 1], &mut scratch, &mut out).unwrap(); | ||
| 124 | - assert_eq!(out, [0, 100, -500, 1700]); | ||
| 125 | - interp_luma(&pl, blk, [0, 3], &mut scratch, &mut out).unwrap(); | ||
| 126 | - assert_eq!(out, [-100, 400, -1000, 5800]); | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -#[test] | ||
| 130 | -fn luma_two_dimensional_hand_values() { | ||
| 131 | - // 10 bits, impulse 4096 at (8, 8), block at (4, 4), fractions (2, 2). | ||
| 132 | - // Horizontal pass on the impulse row gives tmp = [-1024, 4096, -11264, 40960] | ||
| 133 | - // (shift1 = 2), and the vertical pass with shift2 = 6 yields the 4x4 block. | ||
| 134 | - // Built raw: plane_from would clamp the impulse to the 10-bit range. | ||
| 135 | - let mut p = vec![0u16; 16 * 16]; | ||
| 136 | - p[8 * 16 + 8] = 4096; | ||
| 137 | - let pl = view(&p, 16, 16, 10); | ||
| 138 | - let blk = Block { | ||
| 139 | - x: 4, | ||
| 140 | - y: 4, | ||
| 141 | - width: 4, | ||
| 142 | - height: 4, | ||
| 143 | - }; | ||
| 144 | - let mut scratch = McScratch::new(); | ||
| 145 | - let mut out = [0i32; 16]; | ||
| 146 | - interp_luma(&pl, blk, [2, 2], &mut scratch, &mut out).unwrap(); | ||
| 147 | - assert_eq!( | ||
| 148 | - out, | ||
| 149 | - [ | ||
| 150 | - 16, -64, 176, -640, // | ||
| 151 | - -64, 256, -704, 2560, // | ||
| 152 | - 176, -704, 1936, -7040, // | ||
| 153 | - -640, 2560, -7040, 25600, | ||
| 154 | - ] | ||
| 155 | - ); | ||
| 156 | -} | ||
| 157 | - | ||
| 158 | -#[test] | ||
| 159 | -fn chroma_impulse_fractions_hand_values() { | ||
| 160 | - // 8 bits, impulse 100 at (8, 8) in the chroma plane; block at column 5 (so | ||
| 161 | - // output j reads tap 4 - j), the four taps that land in range being j = 1..=3. | ||
| 162 | - let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 }); | ||
| 163 | - let pl = view(&p, 16, 16, 8); | ||
| 164 | - let blk = Block { | ||
| 165 | - x: 5, | ||
| 166 | - y: 8, | ||
| 167 | - width: 4, | ||
| 168 | - height: 1, | ||
| 169 | - }; | ||
| 170 | - let mut scratch = McScratch::new(); | ||
| 171 | - let mut out = [0i32; 4]; | ||
| 172 | - let cases: [(i32, [i32; 4]); 7] = [ | ||
| 173 | - (1, [0, -200, 1000, 5800]), | ||
| 174 | - (2, [0, -200, 1600, 5400]), | ||
| 175 | - (3, [0, -400, 2800, 4600]), | ||
| 176 | - (4, [0, -400, 3600, 3600]), | ||
| 177 | - (5, [0, -600, 4600, 2800]), | ||
| 178 | - (6, [0, -400, 5400, 1600]), | ||
| 179 | - (7, [0, -200, 5800, 1000]), | ||
| 180 | - ]; | ||
| 181 | - for (frac, want) in cases { | ||
| 182 | - interp_chroma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); | ||
| 183 | - assert_eq!(out, want, "chroma horizontal eighth {frac}"); | ||
| 184 | - } | ||
| 185 | - let full = Block { | ||
| 186 | - x: 8, | ||
| 187 | - y: 8, | ||
| 188 | - width: 1, | ||
| 189 | - height: 1, | ||
| 190 | - }; | ||
| 191 | - interp_chroma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); | ||
| 192 | - assert_eq!(out[0], 100 << 6); | ||
| 193 | -} | ||
| 194 | - | ||
| 195 | -#[test] | ||
| 196 | -fn chroma_motion_vector_splits_integer_and_eighth() { | ||
| 197 | - // A chroma mv of 8 + 3 eighths moves one whole sample plus the eighth-3 filter. | ||
| 198 | - let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 }); | ||
| 199 | - let pl = view(&p, 16, 16, 8); | ||
| 200 | - let mut scratch = McScratch::new(); | ||
| 201 | - let mut a = [0i32; 4]; | ||
| 202 | - let mut b = [0i32; 4]; | ||
| 203 | - let start = Block { | ||
| 204 | - x: 4, | ||
| 205 | - y: 8, | ||
| 206 | - width: 4, | ||
| 207 | - height: 1, | ||
| 208 | - }; | ||
| 209 | - interp_chroma(&pl, start, [11, 0], &mut scratch, &mut a).unwrap(); | ||
| 210 | - let shifted = Block { | ||
| 211 | - x: 5, | ||
| 212 | - y: 8, | ||
| 213 | - width: 4, | ||
| 214 | - height: 1, | ||
| 215 | - }; | ||
| 216 | - interp_chroma(&pl, shifted, [3, 0], &mut scratch, &mut b).unwrap(); | ||
| 217 | - assert_eq!(a, b); | ||
| 218 | -} | ||
| 219 | - | ||
| 220 | -#[test] | ||
| 221 | -fn luma_edges_clamp_at_all_four_borders() { | ||
| 222 | - // v(x, y) = 10 * y + x on an 8x8 plane: every border has distinct values. | ||
| 223 | - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); | ||
| 224 | - let pl = view(&p, 8, 8, 8); | ||
| 225 | - let mut scratch = McScratch::new(); | ||
| 226 | - let mut out = [0i32; 16]; | ||
| 227 | - // Far left: every column reads column 0, so each row is v(0, y) << 6. | ||
| 228 | - let blk = Block { | ||
| 229 | - x: 0, | ||
| 230 | - y: 0, | ||
| 231 | - width: 4, | ||
| 232 | - height: 4, | ||
| 233 | - }; | ||
| 234 | - interp_luma(&pl, blk, [-4000, 0], &mut scratch, &mut out).unwrap(); | ||
| 235 | - for r in 0..4 { | ||
| 236 | - for c in 0..4 { | ||
| 237 | - assert_eq!(out[r * 4 + c], (10 * r as i32) << 6, "far left"); | ||
| 238 | - } | ||
| 239 | - } | ||
| 240 | - // Far right: every column reads column 7. | ||
| 241 | - let blk = Block { | ||
| 242 | - x: 4, | ||
| 243 | - y: 0, | ||
| 244 | - width: 4, | ||
| 245 | - height: 4, | ||
| 246 | - }; | ||
| 247 | - interp_luma(&pl, blk, [4000, 0], &mut scratch, &mut out).unwrap(); | ||
| 248 | - for r in 0..4 { | ||
| 249 | - for c in 0..4 { | ||
| 250 | - assert_eq!(out[r * 4 + c], (10 * r as i32 + 7) << 6, "far right"); | ||
| 251 | - } | ||
| 252 | - } | ||
| 253 | - // Far up: every row reads row 0, so each column is v(x, 0) = x. | ||
| 254 | - let blk = Block { | ||
| 255 | - x: 4, | ||
| 256 | - y: 0, | ||
| 257 | - width: 4, | ||
| 258 | - height: 4, | ||
| 259 | - }; | ||
| 260 | - interp_luma(&pl, blk, [0, -4000], &mut scratch, &mut out).unwrap(); | ||
| 261 | - for r in 0..4 { | ||
| 262 | - for c in 0..4 { | ||
| 263 | - assert_eq!(out[r * 4 + c], (4 + c as i32) << 6, "far up"); | ||
| 264 | - } | ||
| 265 | - } | ||
| 266 | - // Far down: every row reads row 7. | ||
| 267 | - let blk = Block { | ||
| 268 | - x: 4, | ||
| 269 | - y: 4, | ||
| 270 | - width: 4, | ||
| 271 | - height: 4, | ||
| 272 | - }; | ||
| 273 | - interp_luma(&pl, blk, [0, 4000], &mut scratch, &mut out).unwrap(); | ||
| 274 | - for r in 0..4 { | ||
| 275 | - for c in 0..4 { | ||
| 276 | - assert_eq!(out[r * 4 + c], ((70 + 4 + c) as i32) << 6, "far down"); | ||
| 277 | - } | ||
| 278 | - } | ||
| 279 | - // Far outside in both directions, to each corner. | ||
| 280 | - let corners = [ | ||
| 281 | - (0, 0, -4000, -4000, 0), | ||
| 282 | - (4, 0, 4000, -4000, 7), | ||
| 283 | - (0, 4, -4000, 4000, 70), | ||
| 284 | - (4, 4, 4000, 4000, 77), | ||
| 285 | - ]; | ||
| 286 | - for (x, y, mx, my, want) in corners { | ||
| 287 | - let blk = Block { | ||
| 288 | - x, | ||
| 289 | - y, | ||
| 290 | - width: 4, | ||
| 291 | - height: 4, | ||
| 292 | - }; | ||
| 293 | - interp_luma(&pl, blk, [mx, my], &mut scratch, &mut out).unwrap(); | ||
| 294 | - assert!(out.iter().all(|&v| v == want << 6), "corner {want}"); | ||
| 295 | - } | ||
| 296 | -} | ||
| 297 | - | ||
| 298 | -#[test] | ||
| 299 | -fn luma_fractional_edges_clamp_to_the_border_sample() { | ||
| 300 | - // A fractional mv far outside reads one border column (or row) only, so the | ||
| 301 | - // filter sums to 64 times that border sample. | ||
| 302 | - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); | ||
| 303 | - let pl = view(&p, 8, 8, 8); | ||
| 304 | - let mut scratch = McScratch::new(); | ||
| 305 | - let mut out = [0i32; 16]; | ||
| 306 | - let blk = Block { | ||
| 307 | - x: 0, | ||
| 308 | - y: 0, | ||
| 309 | - width: 4, | ||
| 310 | - height: 4, | ||
| 311 | - }; | ||
| 312 | - // -4001 quarter samples: integer part -1001, fraction 3. | ||
| 313 | - interp_luma(&pl, blk, [-4001, 0], &mut scratch, &mut out).unwrap(); | ||
| 314 | - for r in 0..4 { | ||
| 315 | - assert!( | ||
| 316 | - out[r * 4..r * 4 + 4] | ||
| 317 | - .iter() | ||
| 318 | - .all(|&v| v == 64 * 10 * r as i32) | ||
| 319 | - ); | ||
| 320 | - } | ||
| 321 | - interp_luma(&pl, blk, [0, -4001], &mut scratch, &mut out).unwrap(); | ||
| 322 | - for c in 0..4 { | ||
| 323 | - assert!((0..4).all(|r| out[r * 4 + c] == 64 * c as i32)); | ||
| 324 | - } | ||
| 325 | -} | ||
| 326 | - | ||
| 327 | -#[test] | ||
| 328 | -fn chroma_edges_clamp_at_all_four_borders() { | ||
| 329 | - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); | ||
| 330 | - let pl = view(&p, 8, 8, 8); | ||
| 331 | - let mut scratch = McScratch::new(); | ||
| 332 | - let mut out = [0i32; 4]; | ||
| 333 | - let blk = Block { | ||
| 334 | - x: 0, | ||
| 335 | - y: 0, | ||
| 336 | - width: 2, | ||
| 337 | - height: 2, | ||
| 338 | - }; | ||
| 339 | - // Eighth-sample mv of -8001: integer part -1001, fraction 7. | ||
| 340 | - interp_chroma(&pl, blk, [-8001, 0], &mut scratch, &mut out).unwrap(); | ||
| 341 | - assert_eq!(out, [0, 0, 640, 640]); | ||
| 342 | - let blk = Block { | ||
| 343 | - x: 6, | ||
| 344 | - y: 6, | ||
| 345 | - width: 2, | ||
| 346 | - height: 2, | ||
| 347 | - }; | ||
| 348 | - interp_chroma(&pl, blk, [8000, 8000], &mut scratch, &mut out).unwrap(); | ||
| 349 | - assert!(out.iter().all(|&v| v == 77 << 6)); | ||
| 350 | -} | ||
| 351 | - | ||
| 352 | -#[test] | ||
| 353 | -fn default_uni_and_bi_hand_values() { | ||
| 354 | - let mut buf = [0u16; 4]; | ||
| 355 | - let blk = Block { | ||
| 356 | - x: 0, | ||
| 357 | - y: 0, | ||
| 358 | - width: 4, | ||
| 359 | - height: 1, | ||
| 360 | - }; | ||
| 361 | - // 8 bits: shift1 = 6 for uni, shift2 = 7 for bi. | ||
| 362 | - let mut dst = PlaneMut { | ||
| 363 | - samples: &mut buf, | ||
| 364 | - stride: 4, | ||
| 365 | - bit_depth: 8, | ||
| 366 | - origin: 0, | ||
| 367 | - }; | ||
| 368 | - store( | ||
| 369 | - &mut dst, | ||
| 370 | - blk, | ||
| 371 | - [Some(&[6400, -100, 16320, 16384]), None], | ||
| 372 | - None, | ||
| 373 | - ) | ||
| 374 | - .unwrap(); | ||
| 375 | - assert_eq!(buf, [100, 0, 255, 255]); | ||
| 376 | - | ||
| 377 | - let mut buf = [0u16; 2]; | ||
| 378 | - let blk2 = Block { | ||
| 379 | - x: 0, | ||
| 380 | - y: 0, | ||
| 381 | - width: 2, | ||
| 382 | - height: 1, | ||
| 383 | - }; | ||
| 384 | - let mut dst = PlaneMut { | ||
| 385 | - samples: &mut buf, | ||
| 386 | - stride: 2, | ||
| 387 | - bit_depth: 8, | ||
| 388 | - origin: 0, | ||
| 389 | - }; | ||
| 390 | - store( | ||
| 391 | - &mut dst, | ||
| 392 | - blk2, | ||
| 393 | - [Some(&[6400, 6400]), Some(&[6400, 6464])], | ||
| 394 | - None, | ||
| 395 | - ) | ||
| 396 | - .unwrap(); | ||
| 397 | - assert_eq!(buf, [100, 101]); | ||
| 398 | - | ||
| 399 | - // 10 bits: shift1 = 4 for uni, shift2 = 5 for bi. | ||
| 400 | - let mut buf = [0u16; 3]; | ||
| 401 | - let blk3 = Block { | ||
| 402 | - x: 0, | ||
| 403 | - y: 0, | ||
| 404 | - width: 3, | ||
| 405 | - height: 1, | ||
| 406 | - }; | ||
| 407 | - let mut dst = PlaneMut { | ||
| 408 | - samples: &mut buf, | ||
| 409 | - stride: 3, | ||
| 410 | - bit_depth: 10, | ||
| 411 | - origin: 0, | ||
| 412 | - }; | ||
| 413 | - store(&mut dst, blk3, [Some(&[6400, 16368, 16384]), None], None).unwrap(); | ||
| 414 | - assert_eq!(buf, [400, 1023, 1023]); | ||
| 415 | - let mut dst = PlaneMut { | ||
| 416 | - samples: &mut buf, | ||
| 417 | - stride: 3, | ||
| 418 | - bit_depth: 10, | ||
| 419 | - origin: 0, | ||
| 420 | - }; | ||
| 421 | - store( | ||
| 422 | - &mut dst, | ||
| 423 | - blk3, | ||
| 424 | - [Some(&[6400, 0, 0]), Some(&[12800, 0, 0])], | ||
| 425 | - None, | ||
| 426 | - ) | ||
| 427 | - .unwrap(); | ||
| 428 | - assert_eq!(buf[0], 600); | ||
| 429 | -} | ||
| 430 | - | ||
| 431 | -#[test] | ||
| 432 | -fn explicit_uni_and_bi_hand_values_8bit() { | ||
| 433 | - let blk = Block { | ||
| 434 | - x: 0, | ||
| 435 | - y: 0, | ||
| 436 | - width: 1, | ||
| 437 | - height: 1, | ||
| 438 | - }; | ||
| 439 | - let mut buf = [0u16; 1]; | ||
| 440 | - // denom 2, w = 3, o = 5: ((6400*3 + 128) >> 8) + 5 = 75 + 5. | ||
| 441 | - let mut dst = PlaneMut { | ||
| 442 | - samples: &mut buf, | ||
| 443 | - stride: 1, | ||
| 444 | - bit_depth: 8, | ||
| 445 | - origin: 0, | ||
| 446 | - }; | ||
| 447 | - let w = [Weight { w: 3, o: 5 }, Weight::default()]; | ||
| 448 | - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); | ||
| 449 | - assert_eq!(buf[0], 80); | ||
| 450 | - | ||
| 451 | - // Negative weight -1 and offset 200: ((-6400 + 128) >> 8) + 200 = -25 + 200. | ||
| 452 | - let w = [Weight { w: -1, o: 200 }, Weight::default()]; | ||
| 453 | - let mut dst = PlaneMut { | ||
| 454 | - samples: &mut buf, | ||
| 455 | - stride: 1, | ||
| 456 | - bit_depth: 8, | ||
| 457 | - origin: 0, | ||
| 458 | - }; | ||
| 459 | - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); | ||
| 460 | - assert_eq!(buf[0], 175); | ||
| 461 | - | ||
| 462 | - // Negative offset clipping at zero: w = -1, o = -200 gives -225 -> 0. | ||
| 463 | - let w = [Weight { w: -1, o: -200 }, Weight::default()]; | ||
| 464 | - let mut dst = PlaneMut { | ||
| 465 | - samples: &mut buf, | ||
| 466 | - stride: 1, | ||
| 467 | - bit_depth: 8, | ||
| 468 | - origin: 0, | ||
| 469 | - }; | ||
| 470 | - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); | ||
| 471 | - assert_eq!(buf[0], 0); | ||
| 472 | - | ||
| 473 | - // Bi: w0 = -2, o0 = -3 with p0 = 6400; w1 = 6, o1 = 7 with p1 = 12800. | ||
| 474 | - // (-12800 + 76800 + ((-3 + 7 + 1) << 8)) >> 9 = 127. | ||
| 475 | - let w = [Weight { w: -2, o: -3 }, Weight { w: 6, o: 7 }]; | ||
| 476 | - let mut dst = PlaneMut { | ||
| 477 | - samples: &mut buf, | ||
| 478 | - stride: 1, | ||
| 479 | - bit_depth: 8, | ||
| 480 | - origin: 0, | ||
| 481 | - }; | ||
| 482 | - store(&mut dst, blk, [Some(&[6400]), Some(&[12800])], Some((2, w))).unwrap(); | ||
| 483 | - assert_eq!(buf[0], 127); | ||
| 484 | -} | ||
| 485 | - | ||
| 486 | -#[test] | ||
| 487 | -fn explicit_uni_hand_value_10bit_with_scaled_offset() { | ||
| 488 | - // The caller scales offsets by 1 << (BitDepth - 8); 5 << 2 = 20. | ||
| 489 | - // shift1 = 4 at 10 bits, log2WD = 2 + 4 = 6: ((6400*3 + 32) >> 6) + 20 = 300 + 20. | ||
| 490 | - let blk = Block { | ||
| 491 | - x: 0, | ||
| 492 | - y: 0, | ||
| 493 | - width: 1, | ||
| 494 | - height: 1, | ||
| 495 | - }; | ||
| 496 | - let mut buf = [0u16; 1]; | ||
| 497 | - let mut dst = PlaneMut { | ||
| 498 | - samples: &mut buf, | ||
| 499 | - stride: 1, | ||
| 500 | - bit_depth: 10, | ||
| 501 | - origin: 0, | ||
| 502 | - }; | ||
| 503 | - let w = [Weight { w: 3, o: 20 }, Weight::default()]; | ||
| 504 | - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); | ||
| 505 | - assert_eq!(buf[0], 320); | ||
| 506 | -} | ||
| 507 | - | ||
| 508 | -#[test] | ||
| 509 | -fn weight_table_derivation_with_chroma_offsets() { | ||
| 510 | - // luma denom 2, chroma denom 3. Entry 0: luma delta -1 offset 5; chroma deltas | ||
| 511 | - // 3 and -2 with the ChromaOffset values the parser already derived (-7, 9). | ||
| 512 | - // Entry 1 has no flags, so every weight is the default and offsets are 0. | ||
| 513 | - let table = PredWeightTable { | ||
| 514 | - luma_log2_weight_denom: 2, | ||
| 515 | - delta_chroma_log2_weight_denom: 1, | ||
| 516 | - l0: vec![ | ||
| 517 | - WeightEntry { | ||
| 518 | - luma: Some((-1, 5)), | ||
| 519 | - chroma: Some([(3, -7), (-2, 9)]), | ||
| 520 | - }, | ||
| 521 | - WeightEntry::default(), | ||
| 522 | - ], | ||
| 523 | - l1: vec![], | ||
| 524 | - }; | ||
| 525 | - let ew = ExplicitWeights::from_table(&table, 8, 8, false).unwrap(); | ||
| 526 | - assert_eq!(ew.log2_denom, [2, 3, 3]); | ||
| 527 | - assert_eq!( | ||
| 528 | - ew.entries[0][0], | ||
| 529 | - [ | ||
| 530 | - Weight { w: 3, o: 5 }, | ||
| 531 | - Weight { w: 11, o: -7 }, | ||
| 532 | - Weight { w: 6, o: 9 }, | ||
| 533 | - ] | ||
| 534 | - ); | ||
| 535 | - assert_eq!( | ||
| 536 | - ew.entries[0][1], | ||
| 537 | - [ | ||
| 538 | - Weight { w: 4, o: 0 }, | ||
| 539 | - Weight { w: 8, o: 0 }, | ||
| 540 | - Weight { w: 8, o: 0 } | ||
| 541 | - ] | ||
| 542 | - ); | ||
| 543 | - // At 10 bits every offset is scaled by 4. | ||
| 544 | - let ew10 = ExplicitWeights::from_table(&table, 10, 10, false).unwrap(); | ||
| 545 | - assert_eq!(ew10.entries[0][0][0], Weight { w: 3, o: 20 }); | ||
| 546 | - assert_eq!(ew10.entries[0][0][1].o, -28); | ||
| 547 | - assert_eq!(ew10.entries[0][0][2].o, 36); | ||
| 548 | - // A coded weight delta outside -128..=127 is corrupt. | ||
| 549 | - let bad = PredWeightTable { | ||
| 550 | - luma_log2_weight_denom: 0, | ||
| 551 | - delta_chroma_log2_weight_denom: 0, | ||
| 552 | - l0: vec![WeightEntry { | ||
| 553 | - luma: Some((200, 0)), | ||
| 554 | - chroma: None, | ||
| 555 | - }], | ||
| 556 | - l1: vec![], | ||
| 557 | - }; | ||
| 558 | - assert!(ExplicitWeights::from_table(&bad, 8, 8, false).is_err()); | ||
| 559 | -} | ||
| 560 | - | ||
| 561 | -#[test] | ||
| 562 | -fn predict_pu_constant_planes_recover_the_value() { | ||
| 563 | - // A constant picture predicts itself for any motion and any weighting that is | ||
| 564 | - // the identity: default bi of 100 and 100 gives 100. | ||
| 565 | - let bd = 8; | ||
| 566 | - let luma = plane_from(64, 64, bd, |_, _| 100); | ||
| 567 | - let chroma = plane_from(32, 32, bd, |_, _| 100); | ||
| 568 | - let pic: RefPicture<'_> = [ | ||
| 569 | - view(&luma, 64, 64, bd), | ||
| 570 | - view(&chroma, 32, 32, bd), | ||
| 571 | - view(&chroma, 32, 32, bd), | ||
| 572 | - ]; | ||
| 573 | - let refs = [&[pic][..], &[pic][..]]; | ||
| 574 | - let mut oy = vec![0u16; 64 * 64]; | ||
| 575 | - let mut ou = vec![0u16; 32 * 32]; | ||
| 576 | - let mut ov = vec![0u16; 32 * 32]; | ||
| 577 | - let mut out = [ | ||
| 578 | - PlaneMut { | ||
| 579 | - samples: &mut oy, | ||
| 580 | - stride: 64, | ||
| 581 | - bit_depth: bd, | ||
| 582 | - origin: 0, | ||
| 583 | - }, | ||
| 584 | - PlaneMut { | ||
| 585 | - samples: &mut ou, | ||
| 586 | - stride: 32, | ||
| 587 | - bit_depth: bd, | ||
| 588 | - origin: 0, | ||
| 589 | - }, | ||
| 590 | - PlaneMut { | ||
| 591 | - samples: &mut ov, | ||
| 592 | - stride: 32, | ||
| 593 | - bit_depth: bd, | ||
| 594 | - origin: 0, | ||
| 595 | - }, | ||
| 596 | - ]; | ||
| 597 | - let mut scratch = McScratch::new(); | ||
| 598 | - let pu = Block { | ||
| 599 | - x: 16, | ||
| 600 | - y: 8, | ||
| 601 | - width: 8, | ||
| 602 | - height: 4, | ||
| 603 | - }; | ||
| 604 | - let m = motion([true, true], [0, 0], [[-13, 7], [22, -5]]); | ||
| 605 | - predict_pu(refs, &m, None, pu, &mut out, &mut scratch).unwrap(); | ||
| 606 | - for (plane, stride, w, h, x, y) in [ | ||
| 607 | - (&oy, 64, 8, 4, 16, 8), | ||
| 608 | - (&ou, 32, 4, 2, 8, 4), | ||
| 609 | - (&ov, 32, 4, 2, 8, 4), | ||
| 610 | - ] { | ||
| 611 | - for r in 0..h { | ||
| 612 | - for c in 0..w { | ||
| 613 | - assert_eq!(plane[(y + r) * stride + x + c], 100); | ||
| 614 | - } | ||
| 615 | - } | ||
| 616 | - } | ||
| 617 | -} | ||
| 618 | - | ||
| 619 | -#[test] | ||
| 620 | -fn predict_pu_rejects_bad_input() { | ||
| 621 | - let bd = 8; | ||
| 622 | - let luma = plane_from(16, 16, bd, |_, _| 1); | ||
| 623 | - let chroma = plane_from(8, 8, bd, |_, _| 1); | ||
| 624 | - let pic: RefPicture<'_> = [ | ||
| 625 | - view(&luma, 16, 16, bd), | ||
| 626 | - view(&chroma, 8, 8, bd), | ||
| 627 | - view(&chroma, 8, 8, bd), | ||
| 628 | - ]; | ||
| 629 | - let refs = [&[pic][..], &[][..]]; | ||
| 630 | - let mut oy = vec![0u16; 16 * 16]; | ||
| 631 | - let mut ou = vec![0u16; 8 * 8]; | ||
| 632 | - let mut ov = vec![0u16; 8 * 8]; | ||
| 633 | - let mut out = [ | ||
| 634 | - PlaneMut { | ||
| 635 | - samples: &mut oy, | ||
| 636 | - stride: 16, | ||
| 637 | - bit_depth: bd, | ||
| 638 | - origin: 0, | ||
| 639 | - }, | ||
| 640 | - PlaneMut { | ||
| 641 | - samples: &mut ou, | ||
| 642 | - stride: 8, | ||
| 643 | - bit_depth: bd, | ||
| 644 | - origin: 0, | ||
| 645 | - }, | ||
| 646 | - PlaneMut { | ||
| 647 | - samples: &mut ov, | ||
| 648 | - stride: 8, | ||
| 649 | - bit_depth: bd, | ||
| 650 | - origin: 0, | ||
| 651 | - }, | ||
| 652 | - ]; | ||
| 653 | - let mut scratch = McScratch::new(); | ||
| 654 | - let pu = Block { | ||
| 655 | - x: 0, | ||
| 656 | - y: 0, | ||
| 657 | - width: 8, | ||
| 658 | - height: 8, | ||
| 659 | - }; | ||
| 660 | - // No list in use. | ||
| 661 | - let none = motion([false, false], [0, 0], [[0; 2]; 2]); | ||
| 662 | - assert!(predict_pu(refs, &none, None, pu, &mut out, &mut scratch).is_err()); | ||
| 663 | - // refIdxL1 names a picture list 1 does not have. | ||
| 664 | - let l1 = motion([false, true], [0, 0], [[0; 2]; 2]); | ||
| 665 | - assert!(predict_pu(refs, &l1, None, pu, &mut out, &mut scratch).is_err()); | ||
| 666 | - // A rectangle past the plane edge. | ||
| 667 | - let off = Block { | ||
| 668 | - x: 12, | ||
| 669 | - y: 0, | ||
| 670 | - width: 8, | ||
| 671 | - height: 8, | ||
| 672 | - }; | ||
| 673 | - let ok = motion([true, false], [0, 0], [[0; 2]; 2]); | ||
| 674 | - assert!(predict_pu(refs, &ok, None, off, &mut out, &mut scratch).is_err()); | ||
| 675 | -} | ||
| 676 | - | ||
| 677 | -// --------------------------------------------------------------------------- | ||
| 678 | -// Reference model: a deliberately naive transcription of 8.5.3.3 per sample. | ||
| 679 | -// It shares no code with the optimised path and copies the filter tables from | ||
| 680 | -// the spec again, so a transcription error in either shows up as a mismatch. | ||
| 681 | -// --------------------------------------------------------------------------- | ||
| 682 | - | ||
| 683 | -mod naive { | ||
| 684 | - use crate::dec::cu_syntax::Motion; | ||
| 685 | - use crate::dec::mc::{Block, PlaneRef, RefPicture}; | ||
| 686 | - use crate::dec::weighted::ExplicitWeights; | ||
| 687 | - | ||
| 688 | - /// Table 8-11, luma. Row 0 is unused. | ||
| 689 | - const LUMA: [[i64; 8]; 4] = [ | ||
| 690 | - [0, 0, 0, 64, 0, 0, 0, 0], | ||
| 691 | - [-1, 4, -10, 58, 17, -5, 1, 0], | ||
| 692 | - [-1, 4, -11, 40, 40, -11, 4, -1], | ||
| 693 | - [0, 1, -5, 17, 58, -10, 4, -1], | ||
| 694 | - ]; | ||
| 695 | - /// Table 8-12, chroma. Row 0 is unused. | ||
| 696 | - const CHROMA: [[i64; 4]; 8] = [ | ||
| 697 | - [0, 64, 0, 0], | ||
| 698 | - [-2, 58, 10, -2], | ||
| 699 | - [-4, 54, 16, -2], | ||
| 700 | - [-6, 46, 28, -4], | ||
| 701 | - [-4, 36, 36, -4], | ||
| 702 | - [-4, 28, 46, -6], | ||
| 703 | - [-2, 16, 54, -4], | ||
| 704 | - [-2, 10, 58, -2], | ||
| 705 | - ]; | ||
| 706 | - | ||
| 707 | - /// `ref[Clip3(0, W-1, x)][Clip3(0, H-1, y)]`, one sample. | ||
| 708 | - fn sample(p: &PlaneRef<'_>, x: i64, y: i64) -> i64 { | ||
| 709 | - let cx = x.clamp(0, p.width as i64 - 1) as usize; | ||
| 710 | - let cy = y.clamp(0, p.height as i64 - 1) as usize; | ||
| 711 | - i64::from(p.samples[cy * p.stride + cx]) | ||
| 712 | - } | ||
| 713 | - | ||
| 714 | - /// One predSampleLX at integer position (xi, yi) with fractions (fx, fy). | ||
| 715 | - fn interp(p: &PlaneRef<'_>, xi: i64, yi: i64, fx: usize, fy: usize, luma: bool) -> i64 { | ||
| 716 | - let bd = i64::from(p.bit_depth); | ||
| 717 | - let shift1 = (bd - 8).min(4); | ||
| 718 | - let shift2 = 6; | ||
| 719 | - let shift3 = (14 - bd).max(2); | ||
| 720 | - let taps: i64 = if luma { 8 } else { 4 }; | ||
| 721 | - let pad = taps / 2 - 1; | ||
| 722 | - let coef = |frac: usize, i: i64| -> i64 { | ||
| 723 | - if luma { | ||
| 724 | - LUMA[frac][i as usize] | ||
| 725 | - } else { | ||
| 726 | - CHROMA[frac][i as usize] | ||
| 727 | - } | ||
| 728 | - }; | ||
| 729 | - if fx == 0 && fy == 0 { | ||
| 730 | - return sample(p, xi, yi) << shift3; | ||
| 731 | - } | ||
| 732 | - if fy == 0 { | ||
| 733 | - let mut s = 0; | ||
| 734 | - for i in 0..taps { | ||
| 735 | - s += coef(fx, i) * sample(p, xi + i - pad, yi); | ||
| 736 | - } | ||
| 737 | - return s >> shift1; | ||
| 738 | - } | ||
| 739 | - if fx == 0 { | ||
| 740 | - let mut s = 0; | ||
| 741 | - for i in 0..taps { | ||
| 742 | - s += coef(fy, i) * sample(p, xi, yi + i - pad); | ||
| 743 | - } | ||
| 744 | - return s >> shift1; | ||
| 745 | - } | ||
| 746 | - let mut s = 0; | ||
| 747 | - for n in 0..taps { | ||
| 748 | - let mut temp = 0; | ||
| 749 | - for i in 0..taps { | ||
| 750 | - temp += coef(fx, i) * sample(p, xi + i - pad, yi + n - pad); | ||
| 751 | - } | ||
| 752 | - s += coef(fy, n) * (temp >> shift1); | ||
| 753 | - } | ||
| 754 | - s >> shift2 | ||
| 755 | - } | ||
| 756 | - | ||
| 757 | - /// The weighted sample prediction of 8.5.3.3.4 for one sample. | ||
| 758 | - /// `preds[list]` is `Some(predSamplesLX)` for each list in use. | ||
| 759 | - fn weight(bd: i64, preds: [Option<i64>; 2], explicit: Option<(i64, [(i64, i64); 2])>) -> i64 { | ||
| 760 | - let max = (1 << bd) - 1; | ||
| 761 | - let shift1 = 14 - bd; | ||
| 762 | - let clip = |v: i64| v.clamp(0, max); | ||
| 763 | - match (preds, explicit) { | ||
| 764 | - ([Some(p0), Some(p1)], None) => { | ||
| 765 | - let shift2 = 15 - bd; | ||
| 766 | - clip((p0 + p1 + (1 << (shift2 - 1))) >> shift2) | ||
| 767 | - } | ||
| 768 | - ([Some(p0), Some(p1)], Some((denom, [(w0, o0), (w1, o1)]))) => { | ||
| 769 | - let log2wd = denom + shift1; | ||
| 770 | - clip((p0 * w0 + p1 * w1 + ((o0 + o1 + 1) << log2wd)) >> (log2wd + 1)) | ||
| 771 | - } | ||
| 772 | - ([Some(p), None], None) | ([None, Some(p)], None) => { | ||
| 773 | - clip((p + (1 << (shift1 - 1))) >> shift1) | ||
| 774 | - } | ||
| 775 | - ([Some(p), None], Some((denom, [(w, o), _]))) => { | ||
| 776 | - let log2wd = denom + shift1; | ||
| 777 | - clip(if log2wd >= 1 { | ||
| 778 | - ((p * w + (1 << (log2wd - 1))) >> log2wd) + o | ||
| 779 | - } else { | ||
| 780 | - p * w + o | ||
| 781 | - }) | ||
| 782 | - } | ||
| 783 | - ([None, Some(p)], Some((denom, [_, (w, o)]))) => { | ||
| 784 | - let log2wd = denom + shift1; | ||
| 785 | - clip(if log2wd >= 1 { | ||
| 786 | - ((p * w + (1 << (log2wd - 1))) >> log2wd) + o | ||
| 787 | - } else { | ||
| 788 | - p * w + o | ||
| 789 | - }) | ||
| 790 | - } | ||
| 791 | - _ => panic!("naive model: no prediction"), | ||
| 792 | - } | ||
| 793 | - } | ||
| 794 | - | ||
| 795 | - /// The final samples of one PU component, row-major `blk.width * blk.height`. | ||
| 796 | - pub fn predict_component( | ||
| 797 | - refs: [&[RefPicture<'_>]; 2], | ||
| 798 | - motion: &Motion, | ||
| 799 | - weights: Option<&ExplicitWeights>, | ||
| 800 | - blk: Block, | ||
| 801 | - comp: usize, | ||
| 802 | - ) -> Vec<i64> { | ||
| 803 | - let luma = comp == 0; | ||
| 804 | - let bd = i64::from( | ||
| 805 | - refs.iter() | ||
| 806 | - .enumerate() | ||
| 807 | - .find_map(|(l, r)| { | ||
| 808 | - motion.pred_flags[l].then(|| r[motion.ref_idx[l] as usize][comp].bit_depth) | ||
| 809 | - }) | ||
| 810 | - .unwrap(), | ||
| 811 | - ); | ||
| 812 | - let mut out = Vec::with_capacity(blk.width * blk.height); | ||
| 813 | - for r in 0..blk.height { | ||
| 814 | - for c in 0..blk.width { | ||
| 815 | - let mut preds = [None, None]; | ||
| 816 | - let mut wts = [(0i64, 0i64); 2]; | ||
| 817 | - for list in 0..2 { | ||
| 818 | - if !motion.pred_flags[list] { | ||
| 819 | - continue; | ||
| 820 | - } | ||
| 821 | - let pic = &refs[list][motion.ref_idx[list] as usize]; | ||
| 822 | - let p = &pic[comp]; | ||
| 823 | - let mv = motion.mv[list]; | ||
| 824 | - let (xi, yi, fx, fy) = if luma { | ||
| 825 | - ( | ||
| 826 | - blk.x as i64 + i64::from(mv[0] >> 2) + c as i64, | ||
| 827 | - blk.y as i64 + i64::from(mv[1] >> 2) + r as i64, | ||
| 828 | - (mv[0] & 3) as usize, | ||
| 829 | - (mv[1] & 3) as usize, | ||
| 830 | - ) | ||
| 831 | - } else { | ||
| 832 | - ( | ||
| 833 | - blk.x as i64 + i64::from(mv[0] >> 3) + c as i64, | ||
| 834 | - blk.y as i64 + i64::from(mv[1] >> 3) + r as i64, | ||
| 835 | - (mv[0] & 7) as usize, | ||
| 836 | - (mv[1] & 7) as usize, | ||
| 837 | - ) | ||
| 838 | - }; | ||
| 839 | - preds[list] = Some(interp(p, xi, yi, fx, fy, luma)); | ||
| 840 | - if let Some(ew) = weights { | ||
| 841 | - let w = ew.entries[list][motion.ref_idx[list] as usize][comp]; | ||
| 842 | - wts[list] = (i64::from(w.w), i64::from(w.o)); | ||
| 843 | - } | ||
| 844 | - } | ||
| 845 | - let explicit = weights.map(|ew| (i64::from(ew.log2_denom[comp]), wts)); | ||
| 846 | - out.push(weight(bd, preds, explicit)); | ||
| 847 | - } | ||
| 848 | - } | ||
| 849 | - out | ||
| 850 | - } | ||
| 851 | -} | ||
| 852 | - | ||
| 853 | -/// SplitMix64: a fixed-seed generator, so every run sees the same blocks. | ||
| 854 | -struct Rng(u64); | ||
| 855 | - | ||
| 856 | -impl Rng { | ||
| 857 | - fn next_u64(&mut self) -> u64 { | ||
| 858 | - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); | ||
| 859 | - let mut z = self.0; | ||
| 860 | - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); | ||
| 861 | - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); | ||
| 862 | - z ^ (z >> 31) | ||
| 863 | - } | ||
| 864 | - | ||
| 865 | - fn below(&mut self, n: u64) -> u64 { | ||
| 866 | - self.next_u64() % n | ||
| 867 | - } | ||
| 868 | - | ||
| 869 | - fn range(&mut self, lo: i64, hi: i64) -> i64 { | ||
| 870 | - lo + (self.next_u64() % (hi - lo + 1) as u64) as i64 | ||
| 871 | - } | ||
| 872 | -} | ||
| 873 | - | ||
| 874 | -/// An owned picture: Y, Cb, Cr planes at the 4:2:0 sizes of a `w x h` luma picture. | ||
| 875 | -struct Pic { | ||
| 876 | - planes: [Vec<u16>; 3], | ||
| 877 | - w: usize, | ||
| 878 | - h: usize, | ||
| 879 | - bd: u32, | ||
| 880 | -} | ||
| 881 | - | ||
| 882 | -impl Pic { | ||
| 883 | - fn random(rng: &mut Rng, w: usize, h: usize, bd: u32) -> Pic { | ||
| 884 | - let max = (1u64 << bd) - 1; | ||
| 885 | - let mut fill = | ||
| 886 | - |n: usize| -> Vec<u16> { (0..n).map(|_| rng.below(max + 1) as u16).collect() }; | ||
| 887 | - let planes = [fill(w * h), fill(w * h / 4), fill(w * h / 4)]; | ||
| 888 | - Pic { planes, w, h, bd } | ||
| 889 | - } | ||
| 890 | - | ||
| 891 | - fn view(&self) -> RefPicture<'_> { | ||
| 892 | - let dims = [ | ||
| 893 | - (self.w, self.h), | ||
| 894 | - (self.w / 2, self.h / 2), | ||
| 895 | - (self.w / 2, self.h / 2), | ||
| 896 | - ]; | ||
| 897 | - std::array::from_fn(|c| PlaneRef { | ||
| 898 | - samples: &self.planes[c], | ||
| 899 | - stride: dims[c].0, | ||
| 900 | - width: dims[c].0, | ||
| 901 | - height: dims[c].1, | ||
| 902 | - bit_depth: self.bd, | ||
| 903 | - }) | ||
| 904 | - } | ||
| 905 | -} | ||
| 906 | - | ||
| 907 | -#[test] | ||
| 908 | -fn random_blocks_match_the_reference_model() { | ||
| 909 | - let mut rng = Rng(0x5eed_1234_abcd_0001); | ||
| 910 | - let mut scratch = McScratch::new(); | ||
| 911 | - let mut checked = 0usize; | ||
| 912 | - let mut sizes_8x4_or_4x8 = 0usize; | ||
| 913 | - let mut uni = 0usize; | ||
| 914 | - let mut bi = 0usize; | ||
| 915 | - let mut explicit = 0usize; | ||
| 916 | - for case in 0..10_000 { | ||
| 917 | - let bd = if rng.below(2) == 0 { 8 } else { 10 }; | ||
| 918 | - let pw = 8 * rng.range(8, 28) as usize; | ||
| 919 | - let ph = 8 * rng.range(8, 28) as usize; | ||
| 920 | - // Sizes 4..=64 in steps of 4; every eighth case is forced to 8x4 or 4x8. | ||
| 921 | - let (w, h) = if case % 8 == 0 { | ||
| 922 | - if rng.below(2) == 0 { (8, 4) } else { (4, 8) } | ||
| 923 | - } else { | ||
| 924 | - (4 * rng.range(1, 16) as usize, 4 * rng.range(1, 16) as usize) | ||
| 925 | - }; | ||
| 926 | - if (w, h) == (8, 4) || (w, h) == (4, 8) { | ||
| 927 | - sizes_8x4_or_4x8 += 1; | ||
| 928 | - } | ||
| 929 | - let x = 4 * rng.below(((pw - w) / 4 + 1) as u64) as usize; | ||
| 930 | - let y = 4 * rng.below(((ph - h) / 4 + 1) as u64) as usize; | ||
| 931 | - | ||
| 932 | - let lists: [Vec<Pic>; 2] = [ | ||
| 933 | - (0..rng.range(1, 3)) | ||
| 934 | - .map(|_| Pic::random(&mut rng, pw, ph, bd)) | ||
| 935 | - .collect(), | ||
| 936 | - (0..rng.range(1, 3)) | ||
| 937 | - .map(|_| Pic::random(&mut rng, pw, ph, bd)) | ||
| 938 | - .collect(), | ||
| 939 | - ]; | ||
| 940 | - let views: [Vec<RefPicture<'_>>; 2] = [ | ||
| 941 | - lists[0].iter().map(Pic::view).collect(), | ||
| 942 | - lists[1].iter().map(Pic::view).collect(), | ||
| 943 | - ]; | ||
| 944 | - | ||
| 945 | - let pred_flags = match rng.below(3) { | ||
| 946 | - 0 => [true, false], | ||
| 947 | - 1 => [false, true], | ||
| 948 | - _ => [true, true], | ||
| 949 | - }; | ||
| 950 | - if pred_flags[0] && pred_flags[1] { | ||
| 951 | - bi += 1; | ||
| 952 | - } else { | ||
| 953 | - uni += 1; | ||
| 954 | - } | ||
| 955 | - let mut ref_idx = [0i8; 2]; | ||
| 956 | - let mut mv = [[0i32; 2]; 2]; | ||
| 957 | - let reach = 4 * (pw.max(ph) as i64 + 96); | ||
| 958 | - for (list, mv_list) in mv.iter_mut().enumerate() { | ||
| 959 | - ref_idx[list] = rng.below(lists[list].len() as u64) as i8; | ||
| 960 | - *mv_list = std::array::from_fn(|_| { | ||
| 961 | - if rng.below(2) == 0 { | ||
| 962 | - rng.range(-reach, reach) as i32 | ||
| 963 | - } else { | ||
| 964 | - rng.range(-40, 40) as i32 | ||
| 965 | - } | ||
| 966 | - }); | ||
| 967 | - } | ||
| 968 | - let m = Motion { | ||
| 969 | - pred_flags, | ||
| 970 | - ref_idx, | ||
| 971 | - mv, | ||
| 972 | - }; | ||
| 973 | - | ||
| 974 | - let weights = if rng.below(2) == 0 { | ||
| 975 | - None | ||
| 976 | - } else { | ||
| 977 | - explicit += 1; | ||
| 978 | - let shift = bd - 8; | ||
| 979 | - let denom: [u32; 3] = [ | ||
| 980 | - rng.below(8) as u32, | ||
| 981 | - rng.below(8) as u32, | ||
| 982 | - rng.below(8) as u32, | ||
| 983 | - ]; | ||
| 984 | - let mut entries: [Vec<[Weight; 3]>; 2] = [Vec::new(), Vec::new()]; | ||
| 985 | - for (list, slot) in entries.iter_mut().enumerate() { | ||
| 986 | - *slot = (0..lists[list].len()) | ||
| 987 | - .map(|_| { | ||
| 988 | - std::array::from_fn(|_| Weight { | ||
| 989 | - w: rng.range(-128, 127) as i32, | ||
| 990 | - o: (rng.range(-128, 127) as i32) << shift, | ||
| 991 | - }) | ||
| 992 | - }) | ||
| 993 | - .collect(); | ||
| 994 | - } | ||
| 995 | - Some(ExplicitWeights { | ||
| 996 | - log2_denom: denom, | ||
| 997 | - entries, | ||
| 998 | - }) | ||
| 999 | - }; | ||
| 1000 | - | ||
| 1001 | - let pu = Block { | ||
| 1002 | - x, | ||
| 1003 | - y, | ||
| 1004 | - width: w, | ||
| 1005 | - height: h, | ||
| 1006 | - }; | ||
| 1007 | - let mut planes = [ | ||
| 1008 | - vec![0u16; pw * ph], | ||
| 1009 | - vec![0u16; pw * ph / 4], | ||
| 1010 | - vec![0u16; pw * ph / 4], | ||
| 1011 | - ]; | ||
| 1012 | - let dims = [(pw, ph), (pw / 2, ph / 2), (pw / 2, ph / 2)]; | ||
| 1013 | - { | ||
| 1014 | - let [a, b, c] = &mut planes; | ||
| 1015 | - let mut out = [ | ||
| 1016 | - PlaneMut { | ||
| 1017 | - samples: a, | ||
| 1018 | - stride: pw, | ||
| 1019 | - bit_depth: bd, | ||
| 1020 | - origin: 0, | ||
| 1021 | - }, | ||
| 1022 | - PlaneMut { | ||
| 1023 | - samples: b, | ||
| 1024 | - stride: pw / 2, | ||
| 1025 | - bit_depth: bd, | ||
| 1026 | - origin: 0, | ||
| 1027 | - }, | ||
| 1028 | - PlaneMut { | ||
| 1029 | - samples: c, | ||
| 1030 | - stride: pw / 2, | ||
| 1031 | - bit_depth: bd, | ||
| 1032 | - origin: 0, | ||
| 1033 | - }, | ||
| 1034 | - ]; | ||
| 1035 | - let refs = [&views[0][..], &views[1][..]]; | ||
| 1036 | - predict_pu(refs, &m, weights.as_ref(), pu, &mut out, &mut scratch).unwrap(); | ||
| 1037 | - } | ||
| 1038 | - | ||
| 1039 | - let refs = [&views[0][..], &views[1][..]]; | ||
| 1040 | - for comp in 0..3 { | ||
| 1041 | - let blk = if comp == 0 { | ||
| 1042 | - pu | ||
| 1043 | - } else { | ||
| 1044 | - Block { | ||
| 1045 | - x: x / 2, | ||
| 1046 | - y: y / 2, | ||
| 1047 | - width: w / 2, | ||
| 1048 | - height: h / 2, | ||
| 1049 | - } | ||
| 1050 | - }; | ||
| 1051 | - let want = naive::predict_component(refs, &m, weights.as_ref(), blk, comp); | ||
| 1052 | - let stride = dims[comp].0; | ||
| 1053 | - for r in 0..blk.height { | ||
| 1054 | - for c in 0..blk.width { | ||
| 1055 | - let got = i64::from(planes[comp][(blk.y + r) * stride + blk.x + c]); | ||
| 1056 | - assert_eq!( | ||
| 1057 | - got, | ||
| 1058 | - want[r * blk.width + c], | ||
| 1059 | - "case {case} bd {bd} comp {comp} pu {pu:?} mv {mv:?} refs {ref_idx:?} flags {pred_flags:?} r {r} c {c}" | ||
| 1060 | - ); | ||
| 1061 | - } | ||
| 1062 | - } | ||
| 1063 | - } | ||
| 1064 | - checked += 1; | ||
| 1065 | - } | ||
| 1066 | - assert_eq!(checked, 10_000); | ||
| 1067 | - eprintln!( | ||
| 1068 | - "mc reference model: {checked} random PUs agree ({uni} uni, {bi} bi, {explicit} explicit weighted, {sizes_8x4_or_4x8} of 8x4/4x8)" | ||
| 1069 | - ); | ||
| 1070 | -} | ||
| 1071 | - | ||
| 1072 | -/// One 1080p frame of 8x8 bi-predicted PUs, luma and 4:2:0 chroma. Timing only; | ||
| 1073 | -/// run with `--release --nocapture` to see the figure. | ||
| 1074 | -#[test] | ||
| 1075 | -fn bench_1080p_bipred_8x8_frame() { | ||
| 1076 | - let (pw, ph, bd) = (1920usize, 1080usize, 10u32); | ||
| 1077 | - let mut rng = Rng(42); | ||
| 1078 | - let pic0 = Pic::random(&mut rng, pw, ph, bd); | ||
| 1079 | - let pic1 = Pic::random(&mut rng, pw, ph, bd); | ||
| 1080 | - let l0 = [pic0.view()]; | ||
| 1081 | - let l1 = [pic1.view()]; | ||
| 1082 | - let mut planes = [ | ||
| 1083 | - vec![0u16; pw * ph], | ||
| 1084 | - vec![0u16; pw * ph / 4], | ||
| 1085 | - vec![0u16; pw * ph / 4], | ||
| 1086 | - ]; | ||
| 1087 | - let [a, b, c] = &mut planes; | ||
| 1088 | - let mut out = [ | ||
| 1089 | - PlaneMut { | ||
| 1090 | - samples: a, | ||
| 1091 | - stride: pw, | ||
| 1092 | - bit_depth: bd, | ||
| 1093 | - origin: 0, | ||
| 1094 | - }, | ||
| 1095 | - PlaneMut { | ||
| 1096 | - samples: b, | ||
| 1097 | - stride: pw / 2, | ||
| 1098 | - bit_depth: bd, | ||
| 1099 | - origin: 0, | ||
| 1100 | - }, | ||
| 1101 | - PlaneMut { | ||
| 1102 | - samples: c, | ||
| 1103 | - stride: pw / 2, | ||
| 1104 | - bit_depth: bd, | ||
| 1105 | - origin: 0, | ||
| 1106 | - }, | ||
| 1107 | - ]; | ||
| 1108 | - let mut scratch = McScratch::new(); | ||
| 1109 | - let start = std::time::Instant::now(); | ||
| 1110 | - for by in 0..ph / 8 { | ||
| 1111 | - for bx in 0..pw / 8 { | ||
| 1112 | - let m = Motion { | ||
| 1113 | - pred_flags: [true, true], | ||
| 1114 | - ref_idx: [0, 0], | ||
| 1115 | - mv: [ | ||
| 1116 | - [(bx as i32 * 7 % 61) - 30, (by as i32 * 5 % 53) - 26], | ||
| 1117 | - [(by as i32 * 3 % 47) - 23, (bx as i32 * 11 % 59) - 29], | ||
| 1118 | - ], | ||
| 1119 | - }; | ||
| 1120 | - let pu = Block { | ||
| 1121 | - x: bx * 8, | ||
| 1122 | - y: by * 8, | ||
| 1123 | - width: 8, | ||
| 1124 | - height: 8, | ||
| 1125 | - }; | ||
| 1126 | - predict_pu([&l0, &l1], &m, None, pu, &mut out, &mut scratch).unwrap(); | ||
| 1127 | - } | ||
| 1128 | - } | ||
| 1129 | - let elapsed = start.elapsed(); | ||
| 1130 | - let checksum: u64 = planes.iter().flatten().map(|&v| u64::from(v)).sum(); | ||
| 1131 | - assert!(checksum > 0); | ||
| 1132 | - eprintln!( | ||
| 1133 | - "bench: 1080p frame, {} bi-pred 8x8 PUs (luma + 4:2:0 chroma): {:.2} ms (checksum {checksum})", | ||
| 1134 | - (pw / 8) * (ph / 8), | ||
| 1135 | - elapsed.as_secs_f64() * 1e3 | ||
| 1136 | - ); | ||
| 1137 | -} | ||
crates/ec-h265/src/dec/merge.rsmodified+8 -367
| @@ -3,7 +3,7 @@ | |||
| 3 | //! temporal candidate, combined bi-predictive candidates for B slices, zero | 3 | //! temporal candidate, combined bi-predictive candidates for B slices, zero |
| 4 | //! candidates, and the 8x4 / 4x8 restriction on bi-prediction. | 4 | //! candidates, and the 8x4 / 4x8 restriction on bi-prediction. |
| 5 | 5 | ||
| 6 | -use super::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; | 6 | +use super::cu_syntax::{PartMode, PredictionUnit}; |
| 7 | use super::motion_field::{PbMotion, SliceMotion, to16}; | 7 | use super::motion_field::{PbMotion, SliceMotion, to16}; |
| 8 | 8 | ||
| 9 | /// Table 8-7: `l0CandIdx` for `combIdx` 0 to 11. | 9 | /// Table 8-7: `l0CandIdx` for `combIdx` 0 to 11. |
| @@ -15,21 +15,24 @@ const COMB_L1: [usize; 12] = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]; | |||
| 15 | /// the merge candidate list (8.5.3.2.2). | 15 | /// the merge candidate list (8.5.3.2.2). |
| 16 | pub fn derive_merge( | 16 | pub fn derive_merge( |
| 17 | src: &SliceMotion<'_>, | 17 | src: &SliceMotion<'_>, |
| 18 | - cu: &CuGeometry, | 18 | + cu_x: usize, |
| 19 | + cu_y: usize, | ||
| 20 | + cu_size: usize, | ||
| 21 | + part_mode: PartMode, | ||
| 19 | pu_index: usize, | 22 | pu_index: usize, |
| 20 | pu: &PredictionUnit, | 23 | pu: &PredictionUnit, |
| 21 | ) -> PbMotion { | 24 | ) -> PbMotion { |
| 22 | let params = src.params; | 25 | let params = src.params; |
| 23 | // 8.5.3.2.2: with a parallel merge level above 4x4, every 8x8 coding unit shares | 26 | // 8.5.3.2.2: with a parallel merge level above 4x4, every 8x8 coding unit shares |
| 24 | // one merge list, derived as if it were a single prediction unit. | 27 | // one merge list, derived as if it were a single prediction unit. |
| 25 | - let single_list = params.log2_par_mrg_level > 2 && cu.size == 8; | 28 | + let single_list = params.log2_par_mrg_level > 2 && cu_size == 8; |
| 26 | let (x, y, w, h, part_idx) = if single_list { | 29 | let (x, y, w, h, part_idx) = if single_list { |
| 27 | - (cu.x, cu.y, cu.size, cu.size, 0) | 30 | + (cu_x, cu_y, cu_size, cu_size, 0) |
| 28 | } else { | 31 | } else { |
| 29 | (pu.x, pu.y, pu.width, pu.height, pu_index) | 32 | (pu.x, pu.y, pu.width, pu.height, pu_index) |
| 30 | }; | 33 | }; |
| 31 | 34 | ||
| 32 | - let mut cands = spatial_candidates(src, cu.part_mode, x, y, w, h, part_idx); | 35 | + let mut cands = spatial_candidates(src, part_mode, x, y, w, h, part_idx); |
| 33 | if let Some(col) = temporal_candidate(src, x, y, w, h) { | 36 | if let Some(col) = temporal_candidate(src, x, y, w, h) { |
| 34 | cands.push(col); | 37 | cands.push(col); |
| 35 | } | 38 | } |
| @@ -193,365 +196,3 @@ fn zero_candidate(is_b: bool, ref_idx: usize) -> PbMotion { | |||
| 193 | PbMotion::new([true, false], [r, -1], [[0, 0], [0, 0]]) | 196 | PbMotion::new([true, false], [r, -1], [[0, 0], [0, 0]]) |
| 194 | } | 197 | } |
| 195 | } | 198 | } |
| 196 | - | ||
| 197 | -#[cfg(test)] | ||
| 198 | -mod tests { | ||
| 199 | - use super::super::cu_syntax::InterPredIdc; | ||
| 200 | - use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared}; | ||
| 201 | - use super::super::rps::{RefEntry, RefPicLists}; | ||
| 202 | - use super::super::shared::SharedPic; | ||
| 203 | - use super::*; | ||
| 204 | - use std::sync::Arc; | ||
| 205 | - | ||
| 206 | - fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry { | ||
| 207 | - RefEntry { id, poc, long_term } | ||
| 208 | - } | ||
| 209 | - | ||
| 210 | - fn params(is_b: bool, max: usize, par: u32) -> MotionParams { | ||
| 211 | - MotionParams { | ||
| 212 | - is_b, | ||
| 213 | - max_merge_cand: max, | ||
| 214 | - log2_par_mrg_level: par, | ||
| 215 | - ctb_log2: 6, | ||
| 216 | - collocated_from_l0: true, | ||
| 217 | - temporal_mvp: false, | ||
| 218 | - no_backward_pred: false, | ||
| 219 | - } | ||
| 220 | - } | ||
| 221 | - | ||
| 222 | - fn uni(list: usize, ref_idx: i8, mv: [i16; 2]) -> PbMotion { | ||
| 223 | - let mut pred = [false, false]; | ||
| 224 | - pred[list] = true; | ||
| 225 | - let mut r = [-1, -1]; | ||
| 226 | - r[list] = ref_idx; | ||
| 227 | - let mut m = [[0i16; 2]; 2]; | ||
| 228 | - m[list] = mv; | ||
| 229 | - PbMotion::new(pred, r, m) | ||
| 230 | - } | ||
| 231 | - | ||
| 232 | - fn pu_at(x: usize, y: usize, w: usize, h: usize, merge_idx: u8) -> PredictionUnit { | ||
| 233 | - PredictionUnit { | ||
| 234 | - x, | ||
| 235 | - y, | ||
| 236 | - width: w, | ||
| 237 | - height: h, | ||
| 238 | - merge_flag: true, | ||
| 239 | - merge_idx, | ||
| 240 | - inter_pred_idc: InterPredIdc::PredL0, | ||
| 241 | - ..PredictionUnit::default() | ||
| 242 | - } | ||
| 243 | - } | ||
| 244 | - | ||
| 245 | - fn cu(x: usize, y: usize, size: usize, part: PartMode) -> CuGeometry { | ||
| 246 | - CuGeometry { | ||
| 247 | - x, | ||
| 248 | - y, | ||
| 249 | - size, | ||
| 250 | - part_mode: part, | ||
| 251 | - skip: false, | ||
| 252 | - } | ||
| 253 | - } | ||
| 254 | - | ||
| 255 | - fn p_lists() -> RefPicLists { | ||
| 256 | - RefPicLists { | ||
| 257 | - l0: vec![entry(0, 0, false)], | ||
| 258 | - l1: Vec::new(), | ||
| 259 | - } | ||
| 260 | - } | ||
| 261 | - | ||
| 262 | - /// The merge result for one PU, in a 64x64 picture with `field` as the current | ||
| 263 | - /// motion field and `col` as the collocated picture. | ||
| 264 | - fn merge_with( | ||
| 265 | - field: &mut MotionField, | ||
| 266 | - lists: &RefPicLists, | ||
| 267 | - p: MotionParams, | ||
| 268 | - col: Option<Arc<SharedPic>>, | ||
| 269 | - geom: CuGeometry, | ||
| 270 | - pu: PredictionUnit, | ||
| 271 | - pu_index: usize, | ||
| 272 | - ) -> PbMotion { | ||
| 273 | - let src = SliceMotion { | ||
| 274 | - params: p, | ||
| 275 | - lists, | ||
| 276 | - cur_poc: 4, | ||
| 277 | - field, | ||
| 278 | - col, | ||
| 279 | - publish: None, | ||
| 280 | - slice: 0, | ||
| 281 | - }; | ||
| 282 | - derive_merge(&src, &geom, pu_index, &pu) | ||
| 283 | - } | ||
| 284 | - | ||
| 285 | - #[test] | ||
| 286 | - fn no_neighbours_gives_zero_candidate() { | ||
| 287 | - let mut field = MotionField::new(64, 64); | ||
| 288 | - let got = merge_with( | ||
| 289 | - &mut field, | ||
| 290 | - &p_lists(), | ||
| 291 | - params(false, 5, 2), | ||
| 292 | - None, | ||
| 293 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 294 | - pu_at(16, 16, 16, 16, 0), | ||
| 295 | - 0, | ||
| 296 | - ); | ||
| 297 | - assert_eq!(got, uni(0, 0, [0, 0])); | ||
| 298 | - } | ||
| 299 | - | ||
| 300 | - #[test] | ||
| 301 | - fn a1_is_first_and_intra_or_missing_neighbour_is_skipped() { | ||
| 302 | - let mut field = MotionField::new(64, 64); | ||
| 303 | - // A1 of the 16x16 block at (16,16) is (15,31): store motion there. | ||
| 304 | - let m = uni(0, 0, [12, -7]); | ||
| 305 | - field.store(0, 16, 16, 16, 0, m); | ||
| 306 | - // B1 (31,15) stays missing (intra or not decoded). | ||
| 307 | - let got = merge_with( | ||
| 308 | - &mut field, | ||
| 309 | - &p_lists(), | ||
| 310 | - params(false, 5, 2), | ||
| 311 | - None, | ||
| 312 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 313 | - pu_at(16, 16, 16, 16, 0), | ||
| 314 | - 0, | ||
| 315 | - ); | ||
| 316 | - assert_eq!(got, m); | ||
| 317 | - } | ||
| 318 | - | ||
| 319 | - #[test] | ||
| 320 | - fn neighbour_in_other_slice_is_unavailable() { | ||
| 321 | - let mut field = MotionField::new(64, 64); | ||
| 322 | - field.store(0, 16, 16, 16, 1, uni(0, 0, [12, -7])); | ||
| 323 | - let got = merge_with( | ||
| 324 | - &mut field, | ||
| 325 | - &p_lists(), | ||
| 326 | - params(false, 5, 2), | ||
| 327 | - None, | ||
| 328 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 329 | - pu_at(16, 16, 16, 16, 0), | ||
| 330 | - 0, | ||
| 331 | - ); | ||
| 332 | - assert_eq!(got, uni(0, 0, [0, 0])); | ||
| 333 | - } | ||
| 334 | - | ||
| 335 | - #[test] | ||
| 336 | - fn b1_identical_to_a1_is_pruned() { | ||
| 337 | - let mut field = MotionField::new(64, 64); | ||
| 338 | - let a = uni(0, 0, [1, 2]); | ||
| 339 | - let n = uni(0, 0, [5, 6]); | ||
| 340 | - field.store(0, 16, 16, 16, 0, a); // A1 | ||
| 341 | - field.store(16, 0, 16, 16, 0, a); // B1 (31,15): same as A1, pruned | ||
| 342 | - field.store(32, 0, 16, 16, 0, n); // B0 (32,15) | ||
| 343 | - // merge_idx 1 is B0, since B1 is pruned. | ||
| 344 | - let got = merge_with( | ||
| 345 | - &mut field, | ||
| 346 | - &p_lists(), | ||
| 347 | - params(false, 5, 2), | ||
| 348 | - None, | ||
| 349 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 350 | - pu_at(16, 16, 16, 16, 1), | ||
| 351 | - 0, | ||
| 352 | - ); | ||
| 353 | - assert_eq!(got, n); | ||
| 354 | - } | ||
| 355 | - | ||
| 356 | - #[test] | ||
| 357 | - fn parallel_merge_level_hides_neighbours_in_the_same_region() { | ||
| 358 | - // Log2ParMrgLevel 4 (16x16 regions). The 8x8 CU at (8,8) shares one list | ||
| 359 | - // (singleMCLFlag), so A1 (7,15) and B1 (15,7) are in its own region and gone. | ||
| 360 | - let mut field = MotionField::new(64, 64); | ||
| 361 | - field.store(0, 8, 8, 8, 0, uni(0, 0, [9, 9])); // A1 position, same region | ||
| 362 | - field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8])); // B1 position, same region | ||
| 363 | - let far = uni(0, 0, [-3, 4]); | ||
| 364 | - field.store(16, 0, 8, 8, 0, far); // B0 (16,7), another region | ||
| 365 | - let got = merge_with( | ||
| 366 | - &mut field, | ||
| 367 | - &p_lists(), | ||
| 368 | - params(false, 5, 4), | ||
| 369 | - None, | ||
| 370 | - cu(8, 8, 8, PartMode::Part2Nx2N), | ||
| 371 | - pu_at(8, 8, 8, 8, 0), | ||
| 372 | - 0, | ||
| 373 | - ); | ||
| 374 | - assert_eq!(got, far); | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - #[test] | ||
| 378 | - fn parallel_merge_level_two_uses_the_neighbour() { | ||
| 379 | - // The same layout with Log2ParMrgLevel 2: nothing is in the same region, so A1 is used. | ||
| 380 | - let mut field = MotionField::new(64, 64); | ||
| 381 | - let a = uni(0, 0, [9, 9]); | ||
| 382 | - field.store(0, 8, 8, 8, 0, a); | ||
| 383 | - field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8])); | ||
| 384 | - let got = merge_with( | ||
| 385 | - &mut field, | ||
| 386 | - &p_lists(), | ||
| 387 | - params(false, 5, 2), | ||
| 388 | - None, | ||
| 389 | - cu(8, 8, 8, PartMode::Part2Nx2N), | ||
| 390 | - pu_at(8, 8, 8, 8, 0), | ||
| 391 | - 0, | ||
| 392 | - ); | ||
| 393 | - assert_eq!(got, a); | ||
| 394 | - } | ||
| 395 | - | ||
| 396 | - #[test] | ||
| 397 | - fn second_vertical_partition_skips_a1() { | ||
| 398 | - // Nx2N, partIdx 1 at (x+8,y): A1 is the first partition, so it is not a candidate. | ||
| 399 | - let mut field = MotionField::new(64, 64); | ||
| 400 | - field.store(16, 16, 8, 16, 0, uni(0, 0, [1, 1])); // the first partition | ||
| 401 | - let got = merge_with( | ||
| 402 | - &mut field, | ||
| 403 | - &p_lists(), | ||
| 404 | - params(false, 5, 2), | ||
| 405 | - None, | ||
| 406 | - cu(16, 16, 16, PartMode::PartNx2N), | ||
| 407 | - pu_at(24, 16, 8, 16, 0), | ||
| 408 | - 1, | ||
| 409 | - ); | ||
| 410 | - assert_eq!(got, uni(0, 0, [0, 0])); | ||
| 411 | - } | ||
| 412 | - | ||
| 413 | - #[test] | ||
| 414 | - fn temporal_candidate_scales_with_negative_distance() { | ||
| 415 | - // Current POC 2; the collocated picture is POC 8 and its vector points to POC 4. | ||
| 416 | - // The current L0[0] is POC 6, after the current picture: tb = -4, td = 4. | ||
| 417 | - // mv 64: tx = (16384 + 2) / 4 = 4096, dsf = (-4 * 4096 + 32) >> 6 = -256, | ||
| 418 | - // mv' = Sign(-256 * 64) * ((16384 + 127) >> 8) = -64. | ||
| 419 | - let mut col_field = MotionField::new(64, 64); | ||
| 420 | - col_field.slices.push(SliceRefs { | ||
| 421 | - poc: [vec![4], vec![]], | ||
| 422 | - long_term: [vec![false], vec![]], | ||
| 423 | - }); | ||
| 424 | - col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0])); | ||
| 425 | - let col = test_shared(&col_field, 8); | ||
| 426 | - let lists = RefPicLists { | ||
| 427 | - l0: vec![entry(0, 6, false)], | ||
| 428 | - l1: Vec::new(), | ||
| 429 | - }; | ||
| 430 | - let mut field = MotionField::new(64, 64); | ||
| 431 | - let mut p = params(false, 5, 2); | ||
| 432 | - p.temporal_mvp = true; | ||
| 433 | - let src = SliceMotion { | ||
| 434 | - params: p, | ||
| 435 | - lists: &lists, | ||
| 436 | - cur_poc: 2, | ||
| 437 | - field: &mut field, | ||
| 438 | - col: Some(col), | ||
| 439 | - publish: None, | ||
| 440 | - slice: 0, | ||
| 441 | - }; | ||
| 442 | - // A 16x16 block at (16,16): bottom-right (32,32) is inside the picture and CTB row. | ||
| 443 | - let got = derive_merge( | ||
| 444 | - &src, | ||
| 445 | - &cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 446 | - 0, | ||
| 447 | - &pu_at(16, 16, 16, 16, 0), | ||
| 448 | - ); | ||
| 449 | - assert_eq!(got, uni(0, 0, [-64, 0])); | ||
| 450 | - } | ||
| 451 | - | ||
| 452 | - #[test] | ||
| 453 | - fn temporal_candidate_with_long_term_mismatch_is_unavailable() { | ||
| 454 | - // The current L0[0] is long-term, the collocated reference is short-term: | ||
| 455 | - // the candidate is unavailable and the zero candidate is used. | ||
| 456 | - let mut col_field = MotionField::new(64, 64); | ||
| 457 | - col_field.slices.push(SliceRefs { | ||
| 458 | - poc: [vec![4], vec![]], | ||
| 459 | - long_term: [vec![false], vec![]], | ||
| 460 | - }); | ||
| 461 | - col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0])); | ||
| 462 | - let col = test_shared(&col_field, 8); | ||
| 463 | - let lists = RefPicLists { | ||
| 464 | - l0: vec![entry(0, 0, true)], | ||
| 465 | - l1: Vec::new(), | ||
| 466 | - }; | ||
| 467 | - let mut field = MotionField::new(64, 64); | ||
| 468 | - let mut p = params(false, 5, 2); | ||
| 469 | - p.temporal_mvp = true; | ||
| 470 | - let src = SliceMotion { | ||
| 471 | - params: p, | ||
| 472 | - lists: &lists, | ||
| 473 | - cur_poc: 4, | ||
| 474 | - field: &mut field, | ||
| 475 | - col: Some(col), | ||
| 476 | - publish: None, | ||
| 477 | - slice: 0, | ||
| 478 | - }; | ||
| 479 | - let got = derive_merge( | ||
| 480 | - &src, | ||
| 481 | - &cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 482 | - 0, | ||
| 483 | - &pu_at(16, 16, 16, 16, 0), | ||
| 484 | - ); | ||
| 485 | - assert_eq!(got, uni(0, 0, [0, 0])); | ||
| 486 | - } | ||
| 487 | - | ||
| 488 | - #[test] | ||
| 489 | - fn combined_bi_candidate_from_l0_and_l1_neighbours() { | ||
| 490 | - // A1 is L0-only (POC 0), B1 is L1-only (POC 6): they pair into a bi candidate. | ||
| 491 | - let lists = RefPicLists { | ||
| 492 | - l0: vec![entry(0, 0, false)], | ||
| 493 | - l1: vec![entry(1, 6, false)], | ||
| 494 | - }; | ||
| 495 | - let mut field = MotionField::new(64, 64); | ||
| 496 | - let m0 = uni(0, 0, [2, 2]); | ||
| 497 | - let m1 = uni(1, 0, [-5, 9]); | ||
| 498 | - field.store(0, 16, 16, 16, 0, m0); // A1 | ||
| 499 | - field.store(16, 0, 16, 16, 0, m1); // B1 (31,15) | ||
| 500 | - let got = merge_with( | ||
| 501 | - &mut field, | ||
| 502 | - &lists, | ||
| 503 | - params(true, 5, 2), | ||
| 504 | - None, | ||
| 505 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 506 | - pu_at(16, 16, 16, 16, 2), | ||
| 507 | - 0, | ||
| 508 | - ); | ||
| 509 | - let expect = PbMotion::new([true, true], [0, 0], [[2, 2], [-5, 9]]); | ||
| 510 | - assert_eq!(got, expect); | ||
| 511 | - } | ||
| 512 | - | ||
| 513 | - #[test] | ||
| 514 | - fn bi_candidate_becomes_uni_for_an_8x4_block() { | ||
| 515 | - // A B slice whose A1 is bi-predicted: an 8x4 block keeps only L0. | ||
| 516 | - let lists = RefPicLists { | ||
| 517 | - l0: vec![entry(0, 0, false)], | ||
| 518 | - l1: vec![entry(1, 8, false)], | ||
| 519 | - }; | ||
| 520 | - let mut field = MotionField::new(64, 64); | ||
| 521 | - let bi = PbMotion::new([true, true], [0, 0], [[3, -3], [4, 4]]); | ||
| 522 | - field.store(0, 16, 16, 16, 0, bi); // A1 of an 8x4 PU at (16,16) | ||
| 523 | - let got = merge_with( | ||
| 524 | - &mut field, | ||
| 525 | - &lists, | ||
| 526 | - params(true, 5, 2), | ||
| 527 | - None, | ||
| 528 | - cu(16, 16, 8, PartMode::Part2Nx2N), | ||
| 529 | - pu_at(16, 16, 8, 4, 0), | ||
| 530 | - 0, | ||
| 531 | - ); | ||
| 532 | - assert_eq!( | ||
| 533 | - got, | ||
| 534 | - PbMotion::new([true, false], [0, -1], [[3, -3], [0, 0]]) | ||
| 535 | - ); | ||
| 536 | - } | ||
| 537 | - | ||
| 538 | - #[test] | ||
| 539 | - fn zero_candidates_use_increasing_reference_indices() { | ||
| 540 | - // Two L0 references and merge_idx 1 with no spatial candidates: zero ref 1. | ||
| 541 | - let lists = RefPicLists { | ||
| 542 | - l0: vec![entry(0, 0, false), entry(1, 2, false)], | ||
| 543 | - l1: Vec::new(), | ||
| 544 | - }; | ||
| 545 | - let mut field = MotionField::new(64, 64); | ||
| 546 | - let got = merge_with( | ||
| 547 | - &mut field, | ||
| 548 | - &lists, | ||
| 549 | - params(false, 5, 2), | ||
| 550 | - None, | ||
| 551 | - cu(16, 16, 16, PartMode::Part2Nx2N), | ||
| 552 | - pu_at(16, 16, 16, 16, 1), | ||
| 553 | - 0, | ||
| 554 | - ); | ||
| 555 | - assert_eq!(got, uni(0, 1, [0, 0])); | ||
| 556 | - } | ||
| 557 | -} | ||
crates/ec-h265/src/dec/mod.rsmodified+14 -112
| @@ -5,12 +5,7 @@ | |||
| 5 | //! Scope is the base layer of Main, Main 10 and range extension streams. Every slice | 5 | //! Scope is the base layer of Main, Main 10 and range extension streams. Every slice |
| 6 | //! goes through [`cu_syntax::parse_slice_into`], which parses the slice data | 6 | //! goes through [`cu_syntax::parse_slice_into`], which parses the slice data |
| 7 | //! and pixel-decodes it. Inter slices write placeholder samples (see | 7 | //! and pixel-decodes it. Inter slices write placeholder samples (see |
| 8 | -//! [`inter::placeholder_cu`]) until motion compensation lands. With pixel | 8 | +//! [`inter::placeholder_cu`]) until motion compensation lands. |
| 9 | -//! decode off ([`Decoder::set_pixel_decode`]) every slice is | ||
| 10 | -//! parsed and every picture is managed, but no samples are produced; that is | ||
| 11 | -//! the mode the picture-management tests use. [`Decoder::set_syntax_check`] | ||
| 12 | -//! adds the slice-data parse ([`cu_syntax::parse_slice`]) to that mode, for | ||
| 13 | -//! every slice type. | ||
| 14 | //! | 9 | //! |
| 15 | //! Decoded: Main, Main 10 and the range extension formats (4:0:0, 4:2:0, 4:2:2, 4:4:4 at | 10 | //! Decoded: Main, Main 10 and the range extension formats (4:0:0, 4:2:0, 4:2:2, 4:4:4 at |
| 16 | //! 8 to 12 bits) with transform-skip extensions, implicit and explicit RDPCM, persistent | 11 | //! 8 to 12 bits) with transform-skip extensions, implicit and explicit RDPCM, persistent |
| @@ -47,7 +42,6 @@ pub mod sao; | |||
| 47 | pub mod shared; | 42 | pub mod shared; |
| 48 | pub mod slice_seg; | 43 | pub mod slice_seg; |
| 49 | pub mod tiles; | 44 | pub mod tiles; |
| 50 | -pub mod trace; | ||
| 51 | pub mod weighted; | 45 | pub mod weighted; |
| 52 | 46 | ||
| 53 | use std::collections::VecDeque; | 47 | use std::collections::VecDeque; |
| @@ -65,9 +59,8 @@ pub use meta::PictureMeta; | |||
| 65 | use picjob::{PicJob, SliceJob}; | 59 | use picjob::{PicJob, SliceJob}; |
| 66 | use rps::RpsInput; | 60 | use rps::RpsInput; |
| 67 | pub use rps::{RefEntry, RefPicLists, RefPicSet}; | 61 | pub use rps::{RefEntry, RefPicLists, RefPicSet}; |
| 68 | -use runner::{Budget, Checksum, Runner}; | 62 | +use runner::{Budget, Runner}; |
| 69 | use shared::SharedPic; | 63 | use shared::SharedPic; |
| 70 | -use std::sync::Mutex; | ||
| 71 | use std::thread::JoinHandle; | 64 | use std::thread::JoinHandle; |
| 72 | 65 | ||
| 73 | /// What [`Decoder::push_nal`] did with a NAL unit. | 66 | /// What [`Decoder::push_nal`] did with a NAL unit. |
| @@ -100,8 +93,6 @@ struct CurPicture { | |||
| 100 | runner: Runner, | 93 | runner: Runner, |
| 101 | /// The published picture (the samples and collocated motion that later pictures read). | 94 | /// The published picture (the samples and collocated motion that later pictures read). |
| 102 | shared: Arc<SharedPic>, | 95 | shared: Arc<SharedPic>, |
| 103 | - /// The motion checksum, set when the picture finishes. | ||
| 104 | - checksum: Arc<Checksum>, | ||
| 105 | /// The header of the picture's latest independent slice segment; the | 96 | /// The header of the picture's latest independent slice segment; the |
| 106 | /// dependent segments after it take their values from it. | 97 | /// dependent segments after it take their values from it. |
| 107 | header: Option<SliceHeader>, | 98 | header: Option<SliceHeader>, |
| @@ -132,15 +123,11 @@ fn picture_limit(threads: usize) -> usize { | |||
| 132 | } | 123 | } |
| 133 | } | 124 | } |
| 134 | 125 | ||
| 135 | -/// The worker-thread budget: `EC_H265_THREADS` when it is a positive number, else | 126 | +/// The worker-thread budget: the machine's available parallelism, capped at [`MAX_THREADS`]. |
| 136 | -/// the machine's available parallelism. Either way capped at [`MAX_THREADS`]. | ||
| 137 | pub fn configured_threads() -> usize { | 127 | pub fn configured_threads() -> usize { |
| 138 | - let requested = std::env::var("EC_H265_THREADS") | 128 | + std::thread::available_parallelism() |
| 139 | - .ok() | 129 | + .map_or(1, |n| n.get()) |
| 140 | - .and_then(|v| v.trim().parse::<usize>().ok()) | 130 | + .min(MAX_THREADS) |
| 141 | - .filter(|&n| n > 0) | ||
| 142 | - .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); | ||
| 143 | - requested.min(MAX_THREADS) | ||
| 144 | } | 131 | } |
| 145 | 132 | ||
| 146 | /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL | 133 | /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL |
| @@ -149,13 +136,10 @@ pub struct Decoder { | |||
| 149 | vps: Vec<Option<Vps>>, | 136 | vps: Vec<Option<Vps>>, |
| 150 | sps: Vec<Option<Arc<Sps>>>, | 137 | sps: Vec<Option<Arc<Sps>>>, |
| 151 | pps: Vec<Option<Arc<Pps>>>, | 138 | pps: Vec<Option<Arc<Pps>>>, |
| 152 | - pixel_decode: bool, | ||
| 153 | /// Worker threads for the in-loop filters (see [`configured_threads`]). | 139 | /// Worker threads for the in-loop filters (see [`configured_threads`]). |
| 154 | threads: usize, | 140 | threads: usize, |
| 155 | /// The worker threads the pictures and their wavefront rows share. | 141 | /// The worker threads the pictures and their wavefront rows share. |
| 156 | budget: Arc<Budget>, | 142 | budget: Arc<Budget>, |
| 157 | - /// Parse every slice's data (all types) with [`cu_syntax`] when pixel decode is off. | ||
| 158 | - syntax_check: bool, | ||
| 159 | dpb: Dpb, | 143 | dpb: Dpb, |
| 160 | cur: Option<CurPicture>, | 144 | cur: Option<CurPicture>, |
| 161 | /// Set while the slices of a skipped RASL picture go by. | 145 | /// Set while the slices of a skipped RASL picture go by. |
| @@ -174,23 +158,12 @@ pub struct Decoder { | |||
| 174 | hdr_pending: PictureMeta, | 158 | hdr_pending: PictureMeta, |
| 175 | /// The HDR SEI in force in the current coded video sequence. | 159 | /// The HDR SEI in force in the current coded video sequence. |
| 176 | hdr_persist: PictureMeta, | 160 | hdr_persist: PictureMeta, |
| 177 | - /// The motion checksum of the finished pictures (see [`Decoder::motion_checksum`]). | ||
| 178 | - checksums: Mutex<ChecksumFold>, | ||
| 179 | /// Worker threads of the pictures that finished but may still run, oldest first. | 161 | /// Worker threads of the pictures that finished but may still run, oldest first. |
| 180 | in_flight: VecDeque<JoinHandle<()>>, | 162 | in_flight: VecDeque<JoinHandle<()>>, |
| 181 | /// The most pictures in flight (see [`picture_limit`]). | 163 | /// The most pictures in flight (see [`picture_limit`]). |
| 182 | max_in_flight: usize, | 164 | max_in_flight: usize, |
| 183 | } | 165 | } |
| 184 | 166 | ||
| 185 | -/// The motion checksum folded over the finished pictures in decoding order. | ||
| 186 | -#[derive(Default)] | ||
| 187 | -struct ChecksumFold { | ||
| 188 | - /// The fold of every picture whose checksum has been waited for. | ||
| 189 | - fold: u64, | ||
| 190 | - /// The checksums of the finished pictures not yet folded, in decoding order. | ||
| 191 | - pending: VecDeque<Arc<Checksum>>, | ||
| 192 | -} | ||
| 193 | - | ||
| 194 | impl Default for Decoder { | 167 | impl Default for Decoder { |
| 195 | fn default() -> Self { | 168 | fn default() -> Self { |
| 196 | Decoder::new() | 169 | Decoder::new() |
| @@ -198,16 +171,14 @@ impl Default for Decoder { | |||
| 198 | } | 171 | } |
| 199 | 172 | ||
| 200 | impl Decoder { | 173 | impl Decoder { |
| 201 | - /// A decoder with no parameter sets and pixel decode on. | 174 | + /// A decoder with no parameter sets. |
| 202 | pub fn new() -> Decoder { | 175 | pub fn new() -> Decoder { |
| 203 | Decoder { | 176 | Decoder { |
| 204 | vps: vec![None; 16], | 177 | vps: vec![None; 16], |
| 205 | sps: vec![None; 16], | 178 | sps: vec![None; 16], |
| 206 | pps: vec![None; 64], | 179 | pps: vec![None; 64], |
| 207 | - pixel_decode: true, | ||
| 208 | threads: configured_threads(), | 180 | threads: configured_threads(), |
| 209 | budget: Budget::new(configured_threads()), | 181 | budget: Budget::new(configured_threads()), |
| 210 | - syntax_check: false, | ||
| 211 | dpb: Dpb::new(), | 182 | dpb: Dpb::new(), |
| 212 | cur: None, | 183 | cur: None, |
| 213 | skipping: false, | 184 | skipping: false, |
| @@ -219,7 +190,6 @@ impl Decoder { | |||
| 219 | out: VecDeque::new(), | 190 | out: VecDeque::new(), |
| 220 | hdr_pending: PictureMeta::default(), | 191 | hdr_pending: PictureMeta::default(), |
| 221 | hdr_persist: PictureMeta::default(), | 192 | hdr_persist: PictureMeta::default(), |
| 222 | - checksums: Mutex::new(ChecksumFold::default()), | ||
| 223 | in_flight: VecDeque::new(), | 193 | in_flight: VecDeque::new(), |
| 224 | max_in_flight: picture_limit(configured_threads()), | 194 | max_in_flight: picture_limit(configured_threads()), |
| 225 | } | 195 | } |
| @@ -232,38 +202,6 @@ impl Decoder { | |||
| 232 | self.budget = Budget::new(self.threads); | 202 | self.budget = Budget::new(self.threads); |
| 233 | } | 203 | } |
| 234 | 204 | ||
| 235 | - /// Turn pixel decode on or off. Off parses every slice and manages every | ||
| 236 | - /// picture (RPS, POC, bumping) without producing samples; inter slices are | ||
| 237 | - /// accepted in that mode. | ||
| 238 | - pub fn set_pixel_decode(&mut self, on: bool) { | ||
| 239 | - self.pixel_decode = on; | ||
| 240 | - } | ||
| 241 | - | ||
| 242 | - /// Whether pixel decode is on. | ||
| 243 | - pub fn pixel_decode(&self) -> bool { | ||
| 244 | - self.pixel_decode | ||
| 245 | - } | ||
| 246 | - | ||
| 247 | - /// A hash of the motion field of every picture finished so far, in decoding order. | ||
| 248 | - /// Two decodes of the same stream give the same value; a change in any derived | ||
| 249 | - /// motion vector, reference index or prediction flag changes it. | ||
| 250 | - pub fn motion_checksum(&self) -> u64 { | ||
| 251 | - let mut fold = self.checksums.lock().unwrap_or_else(|e| e.into_inner()); | ||
| 252 | - while let Some(slot) = fold.pending.pop_front() { | ||
| 253 | - if let Some(sum) = slot.wait() { | ||
| 254 | - fold.fold = (fold.fold ^ sum).wrapping_mul(0x0000_0100_0000_01b3); | ||
| 255 | - } | ||
| 256 | - } | ||
| 257 | - fold.fold | ||
| 258 | - } | ||
| 259 | - | ||
| 260 | - /// With pixel decode off, also parse every slice's data with the CU syntax | ||
| 261 | - /// parser. A parse that does not reach `end_of_slice_segment_flag` at the | ||
| 262 | - /// end of the slice is an error from [`Decoder::push_nal`]. | ||
| 263 | - pub fn set_syntax_check(&mut self, on: bool) { | ||
| 264 | - self.syntax_check = on; | ||
| 265 | - } | ||
| 266 | - | ||
| 267 | /// The VPS stored under `id`. | 205 | /// The VPS stored under `id`. |
| 268 | pub fn vps(&self, id: u32) -> Option<&Vps> { | 206 | pub fn vps(&self, id: u32) -> Option<&Vps> { |
| 269 | self.vps.get(id as usize)?.as_ref() | 207 | self.vps.get(id as usize)?.as_ref() |
| @@ -279,17 +217,6 @@ impl Decoder { | |||
| 279 | self.pps.get(id as usize)?.as_deref() | 217 | self.pps.get(id as usize)?.as_deref() |
| 280 | } | 218 | } |
| 281 | 219 | ||
| 282 | - /// `RefPicList0` and `RefPicList1` of the most recent slice of the picture | ||
| 283 | - /// being decoded. | ||
| 284 | - pub fn ref_pic_lists(&self) -> Option<&RefPicLists> { | ||
| 285 | - self.cur.as_ref().map(|c| &c.lists) | ||
| 286 | - } | ||
| 287 | - | ||
| 288 | - /// The reference picture set of the picture being decoded. | ||
| 289 | - pub fn ref_pic_set(&self) -> Option<&RefPicSet> { | ||
| 290 | - self.cur.as_ref().map(|c| &c.rps) | ||
| 291 | - } | ||
| 292 | - | ||
| 293 | /// A picture in the decoded picture buffer, by id. | 220 | /// A picture in the decoded picture buffer, by id. |
| 294 | pub fn picture(&self, id: u32) -> Option<&DpbPicture> { | 221 | pub fn picture(&self, id: u32) -> Option<&DpbPicture> { |
| 295 | self.dpb.get(id) | 222 | self.dpb.get(id) |
| @@ -324,12 +251,9 @@ impl Decoder { | |||
| 324 | for pending in &self.out { | 251 | for pending in &self.out { |
| 325 | pending.picture.wait_done()?; | 252 | pending.picture.wait_done()?; |
| 326 | } | 253 | } |
| 327 | - let t = trace::now(); | ||
| 328 | for handle in self.in_flight.drain(..) { | 254 | for handle in self.in_flight.drain(..) { |
| 329 | let _ = handle.join(); | 255 | let _ = handle.join(); |
| 330 | } | 256 | } |
| 331 | - trace::since(trace::Phase::WaitJoin, t); | ||
| 332 | - trace::report(); | ||
| 333 | Ok(()) | 257 | Ok(()) |
| 334 | } | 258 | } |
| 335 | 259 | ||
| @@ -531,10 +455,10 @@ impl Decoder { | |||
| 531 | irap_no_rasl: irap && no_rasl, | 455 | irap_no_rasl: irap && no_rasl, |
| 532 | width: sps.pic_width_in_luma_samples as usize, | 456 | width: sps.pic_width_in_luma_samples as usize, |
| 533 | height: sps.pic_height_in_luma_samples as usize, | 457 | height: sps.pic_height_in_luma_samples as usize, |
| 534 | - fill: self.pixel_decode.then_some(( | 458 | + fill: ( |
| 535 | sps.bit_depth_luma_minus8 + 8, | 459 | sps.bit_depth_luma_minus8 + 8, |
| 536 | sps.bit_depth_chroma_minus8 + 8, | 460 | sps.bit_depth_chroma_minus8 + 8, |
| 537 | - )), | 461 | + ), |
| 538 | chroma_format_idc: sps.chroma_format_idc, | 462 | chroma_format_idc: sps.chroma_format_idc, |
| 539 | }; | 463 | }; |
| 540 | let rps = self.dpb.apply_rps(&input); | 464 | let rps = self.dpb.apply_rps(&input); |
| @@ -569,15 +493,13 @@ impl Decoder { | |||
| 569 | } | 493 | } |
| 570 | 494 | ||
| 571 | // Frame threads: at most `threads` pictures in flight, so wait for the oldest. | 495 | // Frame threads: at most `threads` pictures in flight, so wait for the oldest. |
| 572 | - let threaded = self.threads > 1 && self.pixel_decode; | 496 | + let threaded = self.threads > 1; |
| 573 | if threaded { | 497 | if threaded { |
| 574 | - let t = trace::now(); | ||
| 575 | while self.in_flight.len() >= self.max_in_flight { | 498 | while self.in_flight.len() >= self.max_in_flight { |
| 576 | if let Some(handle) = self.in_flight.pop_front() { | 499 | if let Some(handle) = self.in_flight.pop_front() { |
| 577 | let _ = handle.join(); | 500 | let _ = handle.join(); |
| 578 | } | 501 | } |
| 579 | } | 502 | } |
| 580 | - trace::since(trace::Phase::WaitAdmit, t); | ||
| 581 | } | 503 | } |
| 582 | let shared = Arc::new(SharedPic::new( | 504 | let shared = Arc::new(SharedPic::new( |
| 583 | poc, | 505 | poc, |
| @@ -587,13 +509,10 @@ impl Decoder { | |||
| 587 | 8 + sps.bit_depth_luma_minus8, | 509 | 8 + sps.bit_depth_luma_minus8, |
| 588 | 8 + sps.bit_depth_chroma_minus8, | 510 | 8 + sps.bit_depth_chroma_minus8, |
| 589 | ), | 511 | ), |
| 590 | - self.pixel_decode, | ||
| 591 | sps.chroma_format_idc, | 512 | sps.chroma_format_idc, |
| 592 | )); | 513 | )); |
| 593 | - let checksum = Arc::new(Checksum::default()); | ||
| 594 | let runner = Runner::start( | 514 | let runner = Runner::start( |
| 595 | PicJob::new(Arc::clone(&shared), Arc::clone(&self.budget)), | 515 | PicJob::new(Arc::clone(&shared), Arc::clone(&self.budget)), |
| 596 | - Arc::clone(&checksum), | ||
| 597 | threaded, | 516 | threaded, |
| 598 | ); | 517 | ); |
| 599 | self.cur = Some(CurPicture { | 518 | self.cur = Some(CurPicture { |
| @@ -606,7 +525,6 @@ impl Decoder { | |||
| 606 | lists: RefPicLists::default(), | 525 | lists: RefPicLists::default(), |
| 607 | runner, | 526 | runner, |
| 608 | shared, | 527 | shared, |
| 609 | - checksum, | ||
| 610 | all_intra: true, | 528 | all_intra: true, |
| 611 | meta, | 529 | meta, |
| 612 | }); | 530 | }); |
| @@ -614,7 +532,7 @@ impl Decoder { | |||
| 614 | } | 532 | } |
| 615 | 533 | ||
| 616 | /// Build the slice's reference lists, then hand the slice data to the picture's | 534 | /// Build the slice's reference lists, then hand the slice data to the picture's |
| 617 | - /// job. Nothing runs when pixel decode and the syntax check are both off. | 535 | + /// job. |
| 618 | fn decode_slice( | 536 | fn decode_slice( |
| 619 | &mut self, | 537 | &mut self, |
| 620 | slice: &SliceHeader, | 538 | slice: &SliceHeader, |
| @@ -624,7 +542,6 @@ impl Decoder { | |||
| 624 | sps: &Arc<Sps>, | 542 | sps: &Arc<Sps>, |
| 625 | pps: &Arc<Pps>, | 543 | pps: &Arc<Pps>, |
| 626 | ) -> Result<()> { | 544 | ) -> Result<()> { |
| 627 | - let pixel = self.pixel_decode; | ||
| 628 | let dpb = &self.dpb; | 545 | let dpb = &self.dpb; |
| 629 | let cur = self | 546 | let cur = self |
| 630 | .cur | 547 | .cur |
| @@ -636,9 +553,6 @@ impl Decoder { | |||
| 636 | if slice.slice_type != SliceType::I { | 553 | if slice.slice_type != SliceType::I { |
| 637 | cur.all_intra = false; | 554 | cur.all_intra = false; |
| 638 | } | 555 | } |
| 639 | - if !pixel && !self.syntax_check { | ||
| 640 | - return Ok(()); | ||
| 641 | - } | ||
| 642 | let data_off = (pos.header_bits / 8) as usize; | 556 | let data_off = (pos.header_bits / 8) as usize; |
| 643 | if data_off > rbsp.len() { | 557 | if data_off > rbsp.len() { |
| 644 | return Err(Error::corrupt( | 558 | return Err(Error::corrupt( |
| @@ -660,14 +574,13 @@ impl Decoder { | |||
| 660 | }) | 574 | }) |
| 661 | .collect() | 575 | .collect() |
| 662 | }; | 576 | }; |
| 663 | - let refs = if pixel && slice.slice_type != SliceType::I { | 577 | + let refs = if slice.slice_type != SliceType::I { |
| 664 | [lookup(&cur.lists.l0)?, lookup(&cur.lists.l1)?] | 578 | [lookup(&cur.lists.l0)?, lookup(&cur.lists.l1)?] |
| 665 | } else { | 579 | } else { |
| 666 | [Vec::new(), Vec::new()] | 580 | [Vec::new(), Vec::new()] |
| 667 | }; | 581 | }; |
| 668 | let col = motion_field::collocated(dpb, slice, &cur.lists); | 582 | let col = motion_field::collocated(dpb, slice, &cur.lists); |
| 669 | - let t = trace::now(); | 583 | + cur.runner.submit(SliceJob { |
| 670 | - let submitted = cur.runner.submit(SliceJob { | ||
| 671 | rbsp, | 584 | rbsp, |
| 672 | data_off, | 585 | data_off, |
| 673 | header: slice.clone(), | 586 | header: slice.clone(), |
| @@ -677,20 +590,15 @@ impl Decoder { | |||
| 677 | refs, | 590 | refs, |
| 678 | col, | 591 | col, |
| 679 | cur_poc: cur.poc, | 592 | cur_poc: cur.poc, |
| 680 | - pixel, | ||
| 681 | substreams, | 593 | substreams, |
| 682 | - }); | 594 | + }) |
| 683 | - trace::since(trace::Phase::Decode, t); | ||
| 684 | - submitted | ||
| 685 | } | 595 | } |
| 686 | 596 | ||
| 687 | /// C.5.2.3: store the open picture in the buffer and run the additional | 597 | /// C.5.2.3: store the open picture in the buffer and run the additional |
| 688 | /// bumping. Idempotent when no picture is open. The picture's samples may still be | 598 | /// bumping. Idempotent when no picture is open. The picture's samples may still be |
| 689 | /// being decoded (on its worker); output waits for them. | 599 | /// being decoded (on its worker); output waits for them. |
| 690 | fn finish_picture(&mut self) { | 600 | fn finish_picture(&mut self) { |
| 691 | - let t = trace::now(); | ||
| 692 | self.finish_picture_inner(); | 601 | self.finish_picture_inner(); |
| 693 | - trace::since(trace::Phase::Serial, t); | ||
| 694 | } | 602 | } |
| 695 | 603 | ||
| 696 | fn finish_picture_inner(&mut self) { | 604 | fn finish_picture_inner(&mut self) { |
| @@ -704,17 +612,11 @@ impl Decoder { | |||
| 704 | output, | 612 | output, |
| 705 | runner, | 613 | runner, |
| 706 | shared, | 614 | shared, |
| 707 | - checksum, | ||
| 708 | all_intra, | 615 | all_intra, |
| 709 | mut meta, | 616 | mut meta, |
| 710 | .. | 617 | .. |
| 711 | } = cur; | 618 | } = cur; |
| 712 | meta.intra_only = all_intra; | 619 | meta.intra_only = all_intra; |
| 713 | - self.checksums | ||
| 714 | - .lock() | ||
| 715 | - .unwrap_or_else(|e| e.into_inner()) | ||
| 716 | - .pending | ||
| 717 | - .push_back(checksum); | ||
| 718 | if let Some(handle) = runner.finish() { | 620 | if let Some(handle) = runner.finish() { |
| 719 | self.in_flight.push_back(handle); | 621 | self.in_flight.push_back(handle); |
| 720 | } | 622 | } |
crates/ec-h265/src/dec/motion_field.rsmodified+23 -78
| @@ -15,7 +15,7 @@ | |||
| 15 | 15 | ||
| 16 | use std::sync::Arc; | 16 | use std::sync::Arc; |
| 17 | 17 | ||
| 18 | -use super::cu_syntax::{CuGeometry, Motion, MotionSource, PredictionUnit}; | 18 | +use super::cu_syntax::{Motion, PartMode, PredictionUnit}; |
| 19 | use super::dpb::Dpb; | 19 | use super::dpb::Dpb; |
| 20 | use super::pic::{PicState, PuMotion}; | 20 | use super::pic::{PicState, PuMotion}; |
| 21 | use super::rps::{RefEntry, RefPicLists}; | 21 | use super::rps::{RefEntry, RefPicLists}; |
| @@ -24,9 +24,6 @@ use super::{amvp, merge}; | |||
| 24 | use ec_h265_syntax::slice::{SliceHeader, SliceType}; | 24 | use ec_h265_syntax::slice::{SliceHeader, SliceType}; |
| 25 | use ec_h265_syntax::{Pps, Sps}; | 25 | use ec_h265_syntax::{Pps, Sps}; |
| 26 | 26 | ||
| 27 | -const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; | ||
| 28 | -const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; | ||
| 29 | - | ||
| 30 | /// The motion of one prediction block: `predFlagLX`, `refIdxLX` and `mvLX` for both | 27 | /// The motion of one prediction block: `predFlagLX`, `refIdxLX` and `mvLX` for both |
| 31 | /// lists. An unused list has reference index -1 and a zero vector, so two blocks | 28 | /// lists. An unused list has reference index -1 and a zero vector, so two blocks |
| 32 | /// with the same motion compare equal. | 29 | /// with the same motion compare equal. |
| @@ -58,7 +55,7 @@ impl PbMotion { | |||
| 58 | PbMotion::new(m.pred_flags, m.ref_idx, [to16(m.mv[0]), to16(m.mv[1])]) | 55 | PbMotion::new(m.pred_flags, m.ref_idx, [to16(m.mv[0]), to16(m.mv[1])]) |
| 59 | } | 56 | } |
| 60 | 57 | ||
| 61 | - /// The [`Motion`] a [`MotionSource`] returns for this block. | 58 | + /// The [`Motion`] [`SliceMotion::derive_motion`] returns for this block. |
| 62 | pub fn to_motion(self) -> Motion { | 59 | pub fn to_motion(self) -> Motion { |
| 63 | Motion { | 60 | Motion { |
| 64 | pred_flags: self.pred, | 61 | pred_flags: self.pred, |
| @@ -116,7 +113,6 @@ pub struct MotionField { | |||
| 116 | cells: Vec<Option<FieldCell>>, | 113 | cells: Vec<Option<FieldCell>>, |
| 117 | /// The reference lists of each slice of the picture, indexed by `FieldCell::slice`. | 114 | /// The reference lists of each slice of the picture, indexed by `FieldCell::slice`. |
| 118 | pub slices: Vec<SliceRefs>, | 115 | pub slices: Vec<SliceRefs>, |
| 119 | - checksum: u64, | ||
| 120 | /// `TileId` of each CTB, raster order; empty when the picture has one tile. | 116 | /// `TileId` of each CTB, raster order; empty when the picture has one tile. |
| 121 | tiles: Vec<u16>, | 117 | tiles: Vec<u16>, |
| 122 | /// `CtbLog2SizeY` and the CTBs per row, for the tile lookup. | 118 | /// `CtbLog2SizeY` and the CTBs per row, for the tile lookup. |
| @@ -127,18 +123,6 @@ pub struct MotionField { | |||
| 127 | /// The 4x4 unit row of `cells[0..width4]`: zero for a whole picture, and the row above | 123 | /// The 4x4 unit row of `cells[0..width4]`: zero for a whole picture, and the row above |
| 128 | /// the band for a wavefront row band (see [`MotionField::band`]). | 124 | /// the band for a wavefront row band (see [`MotionField::band`]). |
| 129 | origin4: usize, | 125 | origin4: usize, |
| 130 | - /// A wavefront band: its stores are kept in `words` for the picture's checksum, which | ||
| 131 | - /// folds them in decoding order once the band is merged. | ||
| 132 | - band: bool, | ||
| 133 | - words: Vec<u64>, | ||
| 134 | -} | ||
| 135 | - | ||
| 136 | -/// The collocated view of a finished test field, as a picture of its own. | ||
| 137 | -#[cfg(test)] | ||
| 138 | -pub fn test_shared(field: &MotionField, poc: i32) -> Arc<SharedPic> { | ||
| 139 | - let shared = SharedPic::new(poc, field.width(), field.height(), (8, 8), false, 1); | ||
| 140 | - shared.publish_col(field, field.height()); | ||
| 141 | - Arc::new(shared) | ||
| 142 | } | 126 | } |
| 143 | 127 | ||
| 144 | impl MotionField { | 128 | impl MotionField { |
| @@ -152,14 +136,11 @@ impl MotionField { | |||
| 152 | width4, | 136 | width4, |
| 153 | cells: vec![None; width4 * height4], | 137 | cells: vec![None; width4 * height4], |
| 154 | slices: Vec::new(), | 138 | slices: Vec::new(), |
| 155 | - checksum: FNV_OFFSET, | ||
| 156 | tiles: Vec::new(), | 139 | tiles: Vec::new(), |
| 157 | ctb_log2: 0, | 140 | ctb_log2: 0, |
| 158 | ctb_cols: 0, | 141 | ctb_cols: 0, |
| 159 | cur_tile: 0, | 142 | cur_tile: 0, |
| 160 | origin4: 0, | 143 | origin4: 0, |
| 161 | - band: false, | ||
| 162 | - words: Vec::new(), | ||
| 163 | } | 144 | } |
| 164 | } | 145 | } |
| 165 | 146 | ||
| @@ -173,14 +154,11 @@ impl MotionField { | |||
| 173 | width4: self.width4, | 154 | width4: self.width4, |
| 174 | cells: vec![None; unit_rows * self.width4], | 155 | cells: vec![None; unit_rows * self.width4], |
| 175 | slices: Vec::new(), | 156 | slices: Vec::new(), |
| 176 | - checksum: FNV_OFFSET, | ||
| 177 | tiles: self.tiles.clone(), | 157 | tiles: self.tiles.clone(), |
| 178 | ctb_log2: self.ctb_log2, | 158 | ctb_log2: self.ctb_log2, |
| 179 | ctb_cols: self.ctb_cols, | 159 | ctb_cols: self.ctb_cols, |
| 180 | cur_tile: 0, | 160 | cur_tile: 0, |
| 181 | origin4, | 161 | origin4, |
| 182 | - band: true, | ||
| 183 | - words: Vec::new(), | ||
| 184 | } | 162 | } |
| 185 | } | 163 | } |
| 186 | 164 | ||
| @@ -206,18 +184,12 @@ impl MotionField { | |||
| 206 | } | 184 | } |
| 207 | 185 | ||
| 208 | /// Merge a finished band into this field: its cells from unit row `first_unit_row` on | 186 | /// Merge a finished band into this field: its cells from unit row `first_unit_row` on |
| 209 | - /// are copied, and its stores are folded into the checksum in decoding order. Bands | 187 | + /// are copied. |
| 210 | - /// merged in decoding order give the checksum a whole-picture decode would give. | ||
| 211 | pub fn merge_band(&mut self, band: &MotionField, first_unit_row: usize) { | 188 | pub fn merge_band(&mut self, band: &MotionField, first_unit_row: usize) { |
| 212 | let from = (first_unit_row - band.origin4) * self.width4; | 189 | let from = (first_unit_row - band.origin4) * self.width4; |
| 213 | let to = first_unit_row - self.origin4; | 190 | let to = first_unit_row - self.origin4; |
| 214 | let n = band.cells.len() - from; | 191 | let n = band.cells.len() - from; |
| 215 | self.cells[to * self.width4..to * self.width4 + n].copy_from_slice(&band.cells[from..]); | 192 | self.cells[to * self.width4..to * self.width4 + n].copy_from_slice(&band.cells[from..]); |
| 216 | - for words in band.words.as_chunks::<8>().0 { | ||
| 217 | - for &word in words { | ||
| 218 | - self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME); | ||
| 219 | - } | ||
| 220 | - } | ||
| 221 | } | 193 | } |
| 222 | 194 | ||
| 223 | /// The tile of each CTB (raster order), so that a neighbour in another tile is | 195 | /// The tile of each CTB (raster order), so that a neighbour in another tile is |
| @@ -321,30 +293,6 @@ impl MotionField { | |||
| 321 | Some(FieldCell { motion, slice }); | 293 | Some(FieldCell { motion, slice }); |
| 322 | } | 294 | } |
| 323 | } | 295 | } |
| 324 | - let mut words = [0u64; 8]; | ||
| 325 | - words[0] = x as u64; | ||
| 326 | - words[1] = y as u64; | ||
| 327 | - words[2] = w as u64; | ||
| 328 | - words[3] = h as u64; | ||
| 329 | - words[4] = u64::from(slice); | ||
| 330 | - words[5] = u64::from(motion.pred[0]) | (u64::from(motion.pred[1]) << 1); | ||
| 331 | - words[6] = (motion.ref_idx[0] as u8 as u64) | ((motion.ref_idx[1] as u8 as u64) << 8); | ||
| 332 | - words[7] = (motion.mv[0][0] as u16 as u64) | ||
| 333 | - | ((motion.mv[0][1] as u16 as u64) << 16) | ||
| 334 | - | ((motion.mv[1][0] as u16 as u64) << 32) | ||
| 335 | - | ((motion.mv[1][1] as u16 as u64) << 48); | ||
| 336 | - if self.band { | ||
| 337 | - self.words.extend_from_slice(&words); | ||
| 338 | - return; | ||
| 339 | - } | ||
| 340 | - for word in words { | ||
| 341 | - self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME); | ||
| 342 | - } | ||
| 343 | - } | ||
| 344 | - | ||
| 345 | - /// A hash of every stored block, in decoding order. Equal for equal derivations. | ||
| 346 | - pub fn checksum(&self) -> u64 { | ||
| 347 | - self.checksum | ||
| 348 | } | 296 | } |
| 349 | 297 | ||
| 350 | /// The motion of every 4x4 unit in the form the deblocking filter reads (8.7.2.4). | 298 | /// The motion of every 4x4 unit in the form the deblocking filter reads (8.7.2.4). |
| @@ -479,7 +427,7 @@ pub struct MotionParams { | |||
| 479 | pub no_backward_pred: bool, | 427 | pub no_backward_pred: bool, |
| 480 | } | 428 | } |
| 481 | 429 | ||
| 482 | -/// The [`MotionSource`] of the decoder: derives each prediction unit's motion with | 430 | +/// The motion source of the decoder: derives each prediction unit's motion with |
| 483 | /// the merge or AMVP process and stores it in the picture's motion field. | 431 | /// the merge or AMVP process and stores it in the picture's motion field. |
| 484 | pub struct SliceMotion<'a> { | 432 | pub struct SliceMotion<'a> { |
| 485 | /// Slice parameters. | 433 | /// Slice parameters. |
| @@ -493,7 +441,7 @@ pub struct SliceMotion<'a> { | |||
| 493 | /// The collocated picture, if temporal prediction applies. | 441 | /// The collocated picture, if temporal prediction applies. |
| 494 | pub col: Option<Arc<SharedPic>>, | 442 | pub col: Option<Arc<SharedPic>>, |
| 495 | /// The picture this slice belongs to, when its rows are published as they are | 443 | /// The picture this slice belongs to, when its rows are published as they are |
| 496 | - /// decoded (see [`MotionSource::row_done`]). | 444 | + /// decoded (see [`SliceMotion::row_done`]). |
| 497 | pub publish: Option<Arc<SharedPic>>, | 445 | pub publish: Option<Arc<SharedPic>>, |
| 498 | /// Index of this slice in the picture's slice list. | 446 | /// Index of this slice in the picture's slice list. |
| 499 | pub slice: u16, | 447 | pub slice: u16, |
| @@ -586,9 +534,7 @@ impl<'a> SliceMotion<'a> { | |||
| 586 | // Both candidates lie in the CTB row of `y` (the bottom-right one only when it | 534 | // Both candidates lie in the CTB row of `y` (the bottom-right one only when it |
| 587 | // stays in that row), so the collocated rows up to the end of that row suffice. | 535 | // stays in that row), so the collocated rows up to the end of that row suffice. |
| 588 | let need = (((y >> ctb) + 1) << ctb).min(self.field.height()); | 536 | let need = (((y >> ctb) + 1) << ctb).min(self.field.height()); |
| 589 | - let t = super::trace::now(); | ||
| 590 | let waited = shared.wait_col_rows(need); | 537 | let waited = shared.wait_col_rows(need); |
| 591 | - super::trace::since(super::trace::Phase::WaitCol, t); | ||
| 592 | waited.ok()?; | 538 | waited.ok()?; |
| 593 | let col = shared.read_col(); | 539 | let col = shared.read_col(); |
| 594 | if (y >> ctb) == (ybr >> ctb) && ybr < self.field.height() && xbr < self.field.width() { | 540 | if (y >> ctb) == (ybr >> ctb) && ybr < self.field.height() && xbr < self.field.width() { |
| @@ -643,28 +589,33 @@ impl<'a> SliceMotion<'a> { | |||
| 643 | } | 589 | } |
| 644 | } | 590 | } |
| 645 | 591 | ||
| 646 | -impl MotionSource for SliceMotion<'_> { | 592 | +impl SliceMotion<'_> { |
| 647 | - fn row_done(&mut self, pic: &mut PicState, row_end: usize) { | 593 | + /// Called once the CTB row that ends at luma row `row_end` is fully parsed. |
| 594 | + pub fn row_done(&mut self, pic: &mut PicState, row_end: usize) { | ||
| 648 | // The CTB row that ended is `row_end - ctb`; its motion is final. | 595 | // The CTB row that ended is `row_end - ctb`; its motion is final. |
| 649 | let ctb = 1usize << self.params.ctb_log2; | 596 | let ctb = 1usize << self.params.ctb_log2; |
| 650 | let y0 = row_end.saturating_sub(ctb); | 597 | let y0 = row_end.saturating_sub(ctb); |
| 651 | - if pic.has_pixels() { | 598 | + let (u0, u1) = (y0, row_end.min(self.field.height())); |
| 652 | - let (u0, u1) = (y0, row_end.min(self.field.height())); | 599 | + self.field.deblock_rows(&mut pic.motion, u0, u1); |
| 653 | - self.field.deblock_rows(&mut pic.motion, u0, u1); | ||
| 654 | - } | ||
| 655 | if let Some(shared) = &self.publish { | 600 | if let Some(shared) = &self.publish { |
| 656 | shared.publish_col(self.field, row_end); | 601 | shared.publish_col(self.field, row_end); |
| 657 | } | 602 | } |
| 658 | } | 603 | } |
| 659 | 604 | ||
| 660 | - fn band_cells(&mut self) -> Option<&mut MotionField> { | 605 | + /// The motion of unit `pu_index` of the coding unit at `(x, y)`, `size` luma samples |
| 661 | - Some(&mut *self.field) | 606 | + /// square, derived and stored. |
| 662 | - } | 607 | + pub fn derive_motion( |
| 663 | - | 608 | + &mut self, |
| 664 | - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion { | 609 | + x: usize, |
| 665 | - self.field.cur_tile = self.field.tile_at(cu.x, cu.y); | 610 | + y: usize, |
| 611 | + size: usize, | ||
| 612 | + part_mode: PartMode, | ||
| 613 | + pu_index: usize, | ||
| 614 | + pu: &PredictionUnit, | ||
| 615 | + ) -> Motion { | ||
| 616 | + self.field.cur_tile = self.field.tile_at(x, y); | ||
| 666 | let derived = if pu.merge_flag { | 617 | let derived = if pu.merge_flag { |
| 667 | - merge::derive_merge(self, cu, pu_index, pu) | 618 | + merge::derive_merge(self, x, y, size, part_mode, pu_index, pu) |
| 668 | } else { | 619 | } else { |
| 669 | amvp::derive_amvp(self, pu) | 620 | amvp::derive_amvp(self, pu) |
| 670 | }; | 621 | }; |
| @@ -692,12 +643,6 @@ pub fn scale_mv(mv: [i32; 2], td: i32, tb: i32) -> [i32; 2] { | |||
| 692 | }) | 643 | }) |
| 693 | } | 644 | } |
| 694 | 645 | ||
| 695 | -/// The chroma vector of 4:2:0 content, in 1/8 chroma sample units (8.5.3.2.10): | ||
| 696 | -/// the luma quarter-sample vector, unchanged in value. | ||
| 697 | -pub fn chroma_mv_420(mv: [i16; 2]) -> [i32; 2] { | ||
| 698 | - to32(mv) | ||
| 699 | -} | ||
| 700 | - | ||
| 701 | /// A vector widened to `i32`. | 646 | /// A vector widened to `i32`. |
| 702 | pub fn to32(mv: [i16; 2]) -> [i32; 2] { | 647 | pub fn to32(mv: [i16; 2]) -> [i32; 2] { |
| 703 | [i32::from(mv[0]), i32::from(mv[1])] | 648 | [i32::from(mv[0]), i32::from(mv[1])] |
crates/ec-h265/src/dec/pic.rsmodified+16 -52
| @@ -163,7 +163,7 @@ pub struct PicState { | |||
| 163 | pub pps_cb_qp_offset: i32, | 163 | pub pps_cb_qp_offset: i32, |
| 164 | /// See `pps_cb_qp_offset`. | 164 | /// See `pps_cb_qp_offset`. |
| 165 | pub pps_cr_qp_offset: i32, | 165 | pub pps_cr_qp_offset: i32, |
| 166 | - /// The samples. Empty planes when the decoder runs without pixel decode. | 166 | + /// The samples. |
| 167 | pub planes: DecodedPicture, | 167 | pub planes: DecodedPicture, |
| 168 | /// Per 4x4 unit, `w4 * h4`. | 168 | /// Per 4x4 unit, `w4 * h4`. |
| 169 | pub info: Vec<BlockInfo>, | 169 | pub info: Vec<BlockInfo>, |
| @@ -189,8 +189,7 @@ pub struct PicState { | |||
| 189 | } | 189 | } |
| 190 | 190 | ||
| 191 | impl PicState { | 191 | impl PicState { |
| 192 | - /// The state of a `width` x `height` picture. With `pixels` false the | 192 | + /// The state of a `width` x `height` picture. |
| 193 | - /// sample planes are left empty and only the maps are kept. | ||
| 194 | #[allow(clippy::too_many_arguments)] // one value per picture-level SPS/PPS fact | 193 | #[allow(clippy::too_many_arguments)] // one value per picture-level SPS/PPS fact |
| 195 | pub fn new( | 194 | pub fn new( |
| 196 | width: usize, | 195 | width: usize, |
| @@ -199,27 +198,13 @@ impl PicState { | |||
| 199 | min_tb_log2: u32, | 198 | min_tb_log2: u32, |
| 200 | bit_depth_y: u32, | 199 | bit_depth_y: u32, |
| 201 | bit_depth_c: u32, | 200 | bit_depth_c: u32, |
| 202 | - pixels: bool, | ||
| 203 | ) -> PicState { | 201 | ) -> PicState { |
| 204 | let ctb = 1usize << ctb_log2; | 202 | let ctb = 1usize << ctb_log2; |
| 205 | let ctb_cols = width.div_ceil(ctb); | 203 | let ctb_cols = width.div_ceil(ctb); |
| 206 | let ctb_rows = height.div_ceil(ctb); | 204 | let ctb_rows = height.div_ceil(ctb); |
| 207 | let w4 = width.div_ceil(4); | 205 | let w4 = width.div_ceil(4); |
| 208 | let h4 = height.div_ceil(4); | 206 | let h4 = height.div_ceil(4); |
| 209 | - let planes = if pixels { | 207 | + let planes = DecodedPicture::grey_planes(width, height, bit_depth_y, bit_depth_c, 1); |
| 210 | - DecodedPicture::grey_planes(width, height, bit_depth_y, bit_depth_c) | ||
| 211 | - } else { | ||
| 212 | - DecodedPicture { | ||
| 213 | - width, | ||
| 214 | - height, | ||
| 215 | - bit_depth: bit_depth_y, | ||
| 216 | - bit_depth_c, | ||
| 217 | - chroma_format_idc: 1, | ||
| 218 | - y: Vec::new(), | ||
| 219 | - cb: Vec::new(), | ||
| 220 | - cr: Vec::new(), | ||
| 221 | - } | ||
| 222 | - }; | ||
| 223 | PicState { | 208 | PicState { |
| 224 | width, | 209 | width, |
| 225 | height, | 210 | height, |
| @@ -262,11 +247,6 @@ impl PicState { | |||
| 262 | crate::decode::chroma_shifts(self.chroma_format_idc).1 | 247 | crate::decode::chroma_shifts(self.chroma_format_idc).1 |
| 263 | } | 248 | } |
| 264 | 249 | ||
| 265 | - /// Whether the sample planes are allocated (pixel decode is on). | ||
| 266 | - pub fn has_pixels(&self) -> bool { | ||
| 267 | - !self.planes.y.is_empty() | ||
| 268 | - } | ||
| 269 | - | ||
| 270 | /// The three writable sample planes, for motion compensation. | 250 | /// The three writable sample planes, for motion compensation. |
| 271 | pub fn planes_mut(&mut self) -> [PlaneMut<'_>; 3] { | 251 | pub fn planes_mut(&mut self) -> [PlaneMut<'_>; 3] { |
| 272 | let (bd_y, bd_c) = (self.bit_depth_y, self.bit_depth_c); | 252 | let (bd_y, bd_c) = (self.bit_depth_y, self.bit_depth_c); |
| @@ -384,9 +364,8 @@ impl PicState { | |||
| 384 | } | 364 | } |
| 385 | } | 365 | } |
| 386 | 366 | ||
| 387 | - /// The state of a picture of `sps` and `pps`. With `pixels` on, the sample | 367 | + /// The state of a picture of `sps` and `pps`, its sample planes grey. |
| 388 | - /// planes are allocated, grey. | 368 | + pub fn for_sps_pps(sps: &Sps, pps: &Pps) -> PicState { |
| 389 | - pub fn for_sps_pps(sps: &Sps, pps: &Pps, pixels: bool) -> PicState { | ||
| 390 | let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; | 369 | let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; |
| 391 | let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; | 370 | let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; |
| 392 | let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; | 371 | let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; |
| @@ -397,19 +376,16 @@ impl PicState { | |||
| 397 | min_tb_log2, | 376 | min_tb_log2, |
| 398 | 8 + sps.bit_depth_luma_minus8, | 377 | 8 + sps.bit_depth_luma_minus8, |
| 399 | 8 + sps.bit_depth_chroma_minus8, | 378 | 8 + sps.bit_depth_chroma_minus8, |
| 400 | - pixels, | ||
| 401 | ); | 379 | ); |
| 402 | if sps.chroma_format_idc != 1 { | 380 | if sps.chroma_format_idc != 1 { |
| 403 | pic.chroma_format_idc = sps.chroma_format_idc; | 381 | pic.chroma_format_idc = sps.chroma_format_idc; |
| 404 | - if pixels { | 382 | + pic.planes = DecodedPicture::grey_planes( |
| 405 | - pic.planes = DecodedPicture::grey_planes_fmt( | 383 | + pic.width, |
| 406 | - pic.width, | 384 | + pic.height, |
| 407 | - pic.height, | 385 | + pic.bit_depth_y, |
| 408 | - pic.bit_depth_y, | 386 | + pic.bit_depth_c, |
| 409 | - pic.bit_depth_c, | 387 | + sps.chroma_format_idc, |
| 410 | - sps.chroma_format_idc, | 388 | + ); |
| 411 | - ); | ||
| 412 | - } | ||
| 413 | } | 389 | } |
| 414 | pic.constrained_intra_pred = pps.constrained_intra_pred; | 390 | pic.constrained_intra_pred = pps.constrained_intra_pred; |
| 415 | pic.strong_intra_smoothing = sps.strong_intra_smoothing; | 391 | pic.strong_intra_smoothing = sps.strong_intra_smoothing; |
| @@ -426,7 +402,7 @@ impl PicState { | |||
| 426 | /// first, so the band's first sample, unit and CTB rows are that row (copied in by | 402 | /// first, so the band's first sample, unit and CTB rows are that row (copied in by |
| 427 | /// the wavefront driver). The maps cover only the band; the CTB table is the | 403 | /// the wavefront driver). The maps cover only the band; the CTB table is the |
| 428 | /// whole picture's shape, and the tile scan and slice state are copied. | 404 | /// whole picture's shape, and the tile scan and slice state are copied. |
| 429 | - pub fn band(&self, y0: usize, own: usize, pixels: bool) -> PicState { | 405 | + pub fn band(&self, y0: usize, own: usize) -> PicState { |
| 430 | let bound = usize::from(y0 > 0); | 406 | let bound = usize::from(y0 > 0); |
| 431 | let own_units = own.div_ceil(4); | 407 | let own_units = own.div_ceil(4); |
| 432 | let (sx, sy) = crate::decode::chroma_shifts(self.chroma_format_idc); | 408 | let (sx, sy) = crate::decode::chroma_shifts(self.chroma_format_idc); |
| @@ -438,21 +414,9 @@ impl PicState { | |||
| 438 | bit_depth: self.bit_depth_y, | 414 | bit_depth: self.bit_depth_y, |
| 439 | bit_depth_c: self.bit_depth_c, | 415 | bit_depth_c: self.bit_depth_c, |
| 440 | chroma_format_idc: self.chroma_format_idc, | 416 | chroma_format_idc: self.chroma_format_idc, |
| 441 | - y: if pixels { | 417 | + y: vec![0; (bound + own) * self.width], |
| 442 | - vec![0; (bound + own) * self.width] | 418 | + cb: vec![0; (bound + own_c) * cw], |
| 443 | - } else { | 419 | + cr: vec![0; (bound + own_c) * cw], |
| 444 | - Vec::new() | ||
| 445 | - }, | ||
| 446 | - cb: if pixels { | ||
| 447 | - vec![0; (bound + own_c) * cw] | ||
| 448 | - } else { | ||
| 449 | - Vec::new() | ||
| 450 | - }, | ||
| 451 | - cr: if pixels { | ||
| 452 | - vec![0; (bound + own_c) * cw] | ||
| 453 | - } else { | ||
| 454 | - Vec::new() | ||
| 455 | - }, | ||
| 456 | }; | 420 | }; |
| 457 | PicState { | 421 | PicState { |
| 458 | width: self.width, | 422 | width: self.width, |
crates/ec-h265/src/dec/picjob.rsmodified+9 -16
| @@ -42,8 +42,6 @@ pub struct SliceJob { | |||
| 42 | pub col: Option<Arc<SharedPic>>, | 42 | pub col: Option<Arc<SharedPic>>, |
| 43 | /// `PicOrderCntVal` of the picture. | 43 | /// `PicOrderCntVal` of the picture. |
| 44 | pub cur_poc: i32, | 44 | pub cur_poc: i32, |
| 45 | - /// Reconstruct the samples (pixel decode). Off parses the syntax and the motion only. | ||
| 46 | - pub pixel: bool, | ||
| 47 | /// Where the substreams after the first start, relative to `data_off` (one per CTB row | 45 | /// Where the substreams after the first start, relative to `data_off` (one per CTB row |
| 48 | /// after the segment's first, from the entry points). Empty when there are none. | 46 | /// after the segment's first, from the entry points). Empty when there are none. |
| 49 | pub substreams: Vec<usize>, | 47 | pub substreams: Vec<usize>, |
| @@ -95,7 +93,7 @@ impl PicJob { | |||
| 95 | .. | 93 | .. |
| 96 | } = self; | 94 | } = self; |
| 97 | let (sps, pps) = (&*job.sps, &*job.pps); | 95 | let (sps, pps) = (&*job.sps, &*job.pps); |
| 98 | - let pic = pic.get_or_insert_with(|| PicState::for_sps_pps(sps, pps, job.pixel)); | 96 | + let pic = pic.get_or_insert_with(|| PicState::for_sps_pps(sps, pps)); |
| 99 | let (w, h) = ( | 97 | let (w, h) = ( |
| 100 | sps.pic_width_in_luma_samples as usize, | 98 | sps.pic_width_in_luma_samples as usize, |
| 101 | sps.pic_height_in_luma_samples as usize, | 99 | sps.pic_height_in_luma_samples as usize, |
| @@ -112,7 +110,7 @@ impl PicJob { | |||
| 112 | field.slices.push(SliceRefs::from_lists(&job.lists)); | 110 | field.slices.push(SliceRefs::from_lists(&job.lists)); |
| 113 | } | 111 | } |
| 114 | let slice = u16::try_from(field.slices.len().saturating_sub(1)).unwrap_or(u16::MAX); | 112 | let slice = u16::try_from(field.slices.len().saturating_sub(1)).unwrap_or(u16::MAX); |
| 115 | - let refs = if job.pixel && job.header.slice_type != SliceType::I { | 113 | + let refs = if job.header.slice_type != SliceType::I { |
| 116 | Some(InterRefs::new(job.refs, &job.header, sps)?) | 114 | Some(InterRefs::new(job.refs, &job.header, sps)?) |
| 117 | } else { | 115 | } else { |
| 118 | None | 116 | None |
| @@ -181,10 +179,9 @@ impl PicJob { | |||
| 181 | Ok(()) | 179 | Ok(()) |
| 182 | } | 180 | } |
| 183 | 181 | ||
| 184 | - /// The picture is complete: run the rest of the in-loop filters, publish every | 182 | + /// The picture is complete: run the rest of the in-loop filters, and publish every |
| 185 | - /// row and the collocated motion, and return the picture's motion checksum (`None` | 183 | + /// row and the collocated motion. |
| 186 | - /// when no slice ran). | 184 | + pub fn finish(&mut self) { |
| 187 | - pub fn finish(&mut self) -> Option<u64> { | ||
| 188 | let PicJob { | 185 | let PicJob { |
| 189 | shared, | 186 | shared, |
| 190 | pic, | 187 | pic, |
| @@ -194,22 +191,18 @@ impl PicJob { | |||
| 194 | } = self; | 191 | } = self; |
| 195 | let Some(mut pic) = pic.take() else { | 192 | let Some(mut pic) = pic.take() else { |
| 196 | shared.complete(); | 193 | shared.complete(); |
| 197 | - return None; | 194 | + return; |
| 198 | }; | 195 | }; |
| 199 | let h = shared.height; | 196 | let h = shared.height; |
| 200 | // Slices that finished no CTB row (or several tiles) left the motion of the | 197 | // Slices that finished no CTB row (or several tiles) left the motion of the |
| 201 | // units for the filter to read; fill every unit now. | 198 | // units for the filter to read; fill every unit now. |
| 202 | - let checksum = motion.take().map(|field| { | 199 | + if let Some(field) = motion.take() { |
| 203 | - if pic.has_pixels() { | 200 | + field.deblock_rows(&mut pic.motion, 0, h); |
| 204 | - field.deblock_rows(&mut pic.motion, 0, h); | ||
| 205 | - } | ||
| 206 | shared.publish_col(&field, h); | 201 | shared.publish_col(&field, h); |
| 207 | - field.checksum() | 202 | + } |
| 208 | - }); | ||
| 209 | let rows = pic.ctb_rows; | 203 | let rows = pic.ctb_rows; |
| 210 | let final_rows = filter.advance(&mut pic, rows); | 204 | let final_rows = filter.advance(&mut pic, rows); |
| 211 | shared.publish_rows(&pic.planes, final_rows); | 205 | shared.publish_rows(&pic.planes, final_rows); |
| 212 | shared.complete(); | 206 | shared.complete(); |
| 213 | - checksum | ||
| 214 | } | 207 | } |
| 215 | } | 208 | } |
crates/ec-h265/src/dec/recon.rsmodified+0 -10
| @@ -118,16 +118,6 @@ impl PicState { | |||
| 118 | } | 118 | } |
| 119 | } | 119 | } |
| 120 | 120 | ||
| 121 | - /// Write `value` into every sample of an `n` x `n` block of component `c`. | ||
| 122 | - pub fn fill_plane(&mut self, c: usize, x: usize, y: usize, n: usize, value: u16) { | ||
| 123 | - let origin = self.plane_origin(c); | ||
| 124 | - let (stride, plane) = self.plane_view_mut(c); | ||
| 125 | - for j in 0..n { | ||
| 126 | - let start = (y + j - origin) * stride + x; | ||
| 127 | - plane[start..start + n].fill(value); | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | - | ||
| 131 | /// The row stride of the chroma planes. | 121 | /// The row stride of the chroma planes. |
| 132 | fn chroma_stride(&self) -> usize { | 122 | fn chroma_stride(&self) -> usize { |
| 133 | self.width.div_ceil(1 << self.sub_x()) | 123 | self.width.div_ceil(1 << self.sub_x()) |
crates/ec-h265/src/dec/rowfilter.rsmodified+1 -6
| @@ -53,9 +53,7 @@ impl RowFilter { | |||
| 53 | let ctb = 1usize << pic.ctb_log2; | 53 | let ctb = 1usize << pic.ctb_log2; |
| 54 | while self.deblocked < rows && (self.deblocked + 2 <= complete || all) { | 54 | while self.deblocked < rows && (self.deblocked + 2 <= complete || all) { |
| 55 | let r = self.deblocked; | 55 | let r = self.deblocked; |
| 56 | - if pic.has_pixels() { | 56 | + deblock::deblock_rows(pic, r * ctb..(r + 1) * ctb); |
| 57 | - deblock::deblock_rows(pic, r * ctb..(r + 1) * ctb); | ||
| 58 | - } | ||
| 59 | self.deblocked += 1; | 57 | self.deblocked += 1; |
| 60 | } | 58 | } |
| 61 | while self.filtered < rows | 59 | while self.filtered < rows |
| @@ -74,9 +72,6 @@ impl RowFilter { | |||
| 74 | 72 | ||
| 75 | /// SAO of CTB row `r` for the three planes, then remember its last deblocked line. | 73 | /// SAO of CTB row `r` for the three planes, then remember its last deblocked line. |
| 76 | fn sao_row(&mut self, pic: &mut PicState, r: usize) { | 74 | fn sao_row(&mut self, pic: &mut PicState, r: usize) { |
| 77 | - if !pic.has_pixels() { | ||
| 78 | - return; | ||
| 79 | - } | ||
| 80 | let ctb = 1usize << pic.ctb_log2; | 75 | let ctb = 1usize << pic.ctb_log2; |
| 81 | // Does any CTB of the row use SAO? Without one the row is final as it is. | 76 | // Does any CTB of the row use SAO? Without one the row is final as it is. |
| 82 | let sao_on = (r * pic.ctb_cols..(r + 1) * pic.ctb_cols).any(|i| { | 77 | let sao_on = (r * pic.ctb_cols..(r + 1) * pic.ctb_cols).any(|i| { |
crates/ec-h265/src/dec/rps.rsmodified+10 -22
| @@ -27,9 +27,8 @@ pub struct RpsInput<'a> { | |||
| 27 | /// Luma height of the picture, for generated pictures. | 27 | /// Luma height of the picture, for generated pictures. |
| 28 | pub height: usize, | 28 | pub height: usize, |
| 29 | /// Bit depths (luma, chroma) of a generated (8.3.3) picture, whose samples are | 29 | /// Bit depths (luma, chroma) of a generated (8.3.3) picture, whose samples are |
| 30 | - /// grey. `None` generates a picture without samples, for a decoder that does | 30 | + /// grey. |
| 31 | - /// not decode pixels. | 31 | + pub fill: (u32, u32), |
| 32 | - pub fill: Option<(u32, u32)>, | ||
| 33 | /// `chroma_format_idc` of the generated picture. | 32 | /// `chroma_format_idc` of the generated picture. |
| 34 | pub chroma_format_idc: u32, | 33 | pub chroma_format_idc: u32, |
| 35 | } | 34 | } |
| @@ -236,25 +235,14 @@ impl Dpb { | |||
| 236 | 235 | ||
| 237 | /// Generate a missing reference picture (8.3.3.2): grey samples, no output. | 236 | /// Generate a missing reference picture (8.3.3.2): grey samples, no output. |
| 238 | fn generate(&mut self, poc: i32, marking: Marking, input: &RpsInput<'_>) -> u32 { | 237 | fn generate(&mut self, poc: i32, marking: Marking, input: &RpsInput<'_>) -> u32 { |
| 239 | - let picture = match input.fill { | 238 | + let (bit_depth, bit_depth_c) = input.fill; |
| 240 | - Some((bit_depth, bit_depth_c)) => DecodedPicture::grey_planes_fmt( | 239 | + let picture = DecodedPicture::grey_planes( |
| 241 | - input.width, | 240 | + input.width, |
| 242 | - input.height, | 241 | + input.height, |
| 243 | - bit_depth, | 242 | + bit_depth, |
| 244 | - bit_depth_c, | 243 | + bit_depth_c, |
| 245 | - input.chroma_format_idc, | 244 | + input.chroma_format_idc, |
| 246 | - ), | 245 | + ); |
| 247 | - None => DecodedPicture { | ||
| 248 | - width: input.width, | ||
| 249 | - height: input.height, | ||
| 250 | - bit_depth: 8, | ||
| 251 | - bit_depth_c: 8, | ||
| 252 | - chroma_format_idc: input.chroma_format_idc, | ||
| 253 | - y: Vec::new(), | ||
| 254 | - cb: Vec::new(), | ||
| 255 | - cr: Vec::new(), | ||
| 256 | - }, | ||
| 257 | - }; | ||
| 258 | self.insert( | 246 | self.insert( |
| 259 | poc, | 247 | poc, |
| 260 | marking, | 248 | marking, |
crates/ec-h265/src/dec/runner.rsmodified+13 -59
| @@ -15,11 +15,10 @@ | |||
| 15 | 15 | ||
| 16 | use std::panic::{AssertUnwindSafe, catch_unwind}; | 16 | use std::panic::{AssertUnwindSafe, catch_unwind}; |
| 17 | use std::sync::mpsc::{self, Receiver, Sender}; | 17 | use std::sync::mpsc::{self, Receiver, Sender}; |
| 18 | -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; | 18 | +use std::sync::{Arc, Mutex, MutexGuard}; |
| 19 | use std::thread::JoinHandle; | 19 | use std::thread::JoinHandle; |
| 20 | 20 | ||
| 21 | use super::picjob::{PicJob, SliceJob}; | 21 | use super::picjob::{PicJob, SliceJob}; |
| 22 | -use super::trace::{self, Phase}; | ||
| 23 | use ec_core::error::{Error, Result}; | 22 | use ec_core::error::{Error, Result}; |
| 24 | 23 | ||
| 25 | fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { | 24 | fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| @@ -107,34 +106,6 @@ impl Drop for PictureSlot { | |||
| 107 | } | 106 | } |
| 108 | } | 107 | } |
| 109 | 108 | ||
| 110 | -/// The motion checksum of one picture (see [`super::Decoder::motion_checksum`]), set when | ||
| 111 | -/// the picture finishes. The value is `None` for a picture no slice ran in, and also for a | ||
| 112 | -/// picture that failed. | ||
| 113 | -#[derive(Debug, Default)] | ||
| 114 | -pub struct Checksum { | ||
| 115 | - value: Mutex<Option<Option<u64>>>, | ||
| 116 | - changed: Condvar, | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | -impl Checksum { | ||
| 120 | - /// Store the picture's value and wake the readers. | ||
| 121 | - pub fn set(&self, value: Option<u64>) { | ||
| 122 | - *lock(&self.value) = Some(value); | ||
| 123 | - self.changed.notify_all(); | ||
| 124 | - } | ||
| 125 | - | ||
| 126 | - /// Wait until the value is stored. | ||
| 127 | - pub fn wait(&self) -> Option<u64> { | ||
| 128 | - let mut value = lock(&self.value); | ||
| 129 | - loop { | ||
| 130 | - if let Some(v) = *value { | ||
| 131 | - return v; | ||
| 132 | - } | ||
| 133 | - value = self.changed.wait(value).unwrap_or_else(|e| e.into_inner()); | ||
| 134 | - } | ||
| 135 | - } | ||
| 136 | -} | ||
| 137 | - | ||
| 138 | /// A message to a picture's worker. | 109 | /// A message to a picture's worker. |
| 139 | pub enum Msg { | 110 | pub enum Msg { |
| 140 | /// Run this slice segment. | 111 | /// Run this slice segment. |
| @@ -149,8 +120,6 @@ pub enum Runner { | |||
| 149 | Inline { | 120 | Inline { |
| 150 | /// The picture's job. | 121 | /// The picture's job. |
| 151 | job: Box<PicJob>, | 122 | job: Box<PicJob>, |
| 152 | - /// Set when the picture finishes. | ||
| 153 | - checksum: Arc<Checksum>, | ||
| 154 | }, | 123 | }, |
| 155 | /// On a worker thread that owns the job. | 124 | /// On a worker thread that owns the job. |
| 156 | Worker { | 125 | Worker { |
| @@ -163,15 +132,12 @@ pub enum Runner { | |||
| 163 | 132 | ||
| 164 | impl Runner { | 133 | impl Runner { |
| 165 | /// Start the decoding of the picture of `job`. `threaded` gives it a worker thread. | 134 | /// Start the decoding of the picture of `job`. `threaded` gives it a worker thread. |
| 166 | - pub fn start(job: PicJob, checksum: Arc<Checksum>, threaded: bool) -> Runner { | 135 | + pub fn start(job: PicJob, threaded: bool) -> Runner { |
| 167 | if !threaded { | 136 | if !threaded { |
| 168 | - return Runner::Inline { | 137 | + return Runner::Inline { job: Box::new(job) }; |
| 169 | - job: Box::new(job), | ||
| 170 | - checksum, | ||
| 171 | - }; | ||
| 172 | } | 138 | } |
| 173 | let (tx, rx) = mpsc::channel(); | 139 | let (tx, rx) = mpsc::channel(); |
| 174 | - let handle = std::thread::spawn(move || run_worker(rx, job, checksum)); | 140 | + let handle = std::thread::spawn(move || run_worker(rx, job)); |
| 175 | Runner::Worker { tx, handle } | 141 | Runner::Worker { tx, handle } |
| 176 | } | 142 | } |
| 177 | 143 | ||
| @@ -193,8 +159,8 @@ impl Runner { | |||
| 193 | /// goes on in the background; its handle is returned to be joined later. | 159 | /// goes on in the background; its handle is returned to be joined later. |
| 194 | pub fn finish(self) -> Option<JoinHandle<()>> { | 160 | pub fn finish(self) -> Option<JoinHandle<()>> { |
| 195 | match self { | 161 | match self { |
| 196 | - Runner::Inline { mut job, checksum } => { | 162 | + Runner::Inline { mut job } => { |
| 197 | - checksum.set(job.finish()); | 163 | + job.finish(); |
| 198 | None | 164 | None |
| 199 | } | 165 | } |
| 200 | Runner::Worker { tx, handle } => { | 166 | Runner::Worker { tx, handle } => { |
| @@ -207,39 +173,27 @@ impl Runner { | |||
| 207 | 173 | ||
| 208 | /// The body of a picture's worker thread. A failure, a panic, or a picture dropped before | 174 | /// The body of a picture's worker thread. A failure, a panic, or a picture dropped before |
| 209 | /// its finish marks the picture as failed, so that nothing waits on it forever. | 175 | /// its finish marks the picture as failed, so that nothing waits on it forever. |
| 210 | -fn run_worker(rx: Receiver<Msg>, mut job: PicJob, checksum: Arc<Checksum>) { | 176 | +fn run_worker(rx: Receiver<Msg>, mut job: PicJob) { |
| 211 | let shared = Arc::clone(job.shared()); | 177 | let shared = Arc::clone(job.shared()); |
| 212 | - trace::set_role("picture"); | 178 | + let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<()> { |
| 213 | - let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<Option<u64>> { | ||
| 214 | loop { | 179 | loop { |
| 215 | - let idle = trace::now(); | ||
| 216 | let msg = rx.recv(); | 180 | let msg = rx.recv(); |
| 217 | - trace::since(Phase::WaitMsg, idle); | ||
| 218 | let Ok(msg) = msg else { break }; | 181 | let Ok(msg) = msg else { break }; |
| 219 | - let busy = trace::now(); | ||
| 220 | match msg { | 182 | match msg { |
| 221 | Msg::Slice(slice) => job.run_slice(*slice)?, | 183 | Msg::Slice(slice) => job.run_slice(*slice)?, |
| 222 | Msg::Finish => { | 184 | Msg::Finish => { |
| 223 | - let sum = job.finish(); | 185 | + job.finish(); |
| 224 | - trace::since(Phase::Decode, busy); | 186 | + return Ok(()); |
| 225 | - return Ok(sum); | ||
| 226 | } | 187 | } |
| 227 | } | 188 | } |
| 228 | - trace::since(Phase::Decode, busy); | ||
| 229 | } | 189 | } |
| 230 | Err(Error::corrupt( | 190 | Err(Error::corrupt( |
| 231 | "HEVC decode: a picture was dropped before it finished".to_string(), | 191 | "HEVC decode: a picture was dropped before it finished".to_string(), |
| 232 | )) | 192 | )) |
| 233 | })); | 193 | })); |
| 234 | match outcome { | 194 | match outcome { |
| 235 | - Ok(Ok(sum)) => checksum.set(sum), | 195 | + Ok(Ok(())) => {} |
| 236 | - Ok(Err(e)) => { | 196 | + Ok(Err(e)) => shared.fail(&e.to_string()), |
| 237 | - shared.fail(&e.to_string()); | 197 | + Err(_) => shared.fail("HEVC decode: the picture's worker thread panicked"), |
| 238 | - checksum.set(None); | ||
| 239 | - } | ||
| 240 | - Err(_) => { | ||
| 241 | - shared.fail("HEVC decode: the picture's worker thread panicked"); | ||
| 242 | - checksum.set(None); | ||
| 243 | - } | ||
| 244 | } | 198 | } |
| 245 | } | 199 | } |
crates/ec-h265/src/dec/sao.rsmodified+1 -4
| @@ -40,9 +40,6 @@ pub fn sao_picture(pic: &mut PicState) { | |||
| 40 | /// in parallel. A band reads the deblocked input (shared, read-only) and writes only | 40 | /// in parallel. A band reads the deblocked input (shared, read-only) and writes only |
| 41 | /// its own rows of the output, so the bands never touch the same sample. | 41 | /// its own rows of the output, so the bands never touch the same sample. |
| 42 | pub fn sao_picture_threads(pic: &mut PicState, threads: usize) { | 42 | pub fn sao_picture_threads(pic: &mut PicState, threads: usize) { |
| 43 | - if !pic.has_pixels() { | ||
| 44 | - return; | ||
| 45 | - } | ||
| 46 | let ro: &PicState = pic; | 43 | let ro: &PicState = pic; |
| 47 | let y = filter_plane(ro, 0, &ro.planes.y, threads); | 44 | let y = filter_plane(ro, 0, &ro.planes.y, threads); |
| 48 | let cb = filter_plane(ro, 1, &ro.planes.cb, threads); | 45 | let cb = filter_plane(ro, 1, &ro.planes.cb, threads); |
| @@ -362,7 +359,7 @@ mod tests { | |||
| 362 | 359 | ||
| 363 | /// A 16x16 8-bit picture with one 16x16 CTB and no slices. | 360 | /// A 16x16 8-bit picture with one 16x16 CTB and no slices. |
| 364 | fn picture() -> PicState { | 361 | fn picture() -> PicState { |
| 365 | - PicState::new(16, 16, 4, 2, 8, 8, true) | 362 | + PicState::new(16, 16, 4, 2, 8, 8) |
| 366 | } | 363 | } |
| 367 | 364 | ||
| 368 | /// SAO parameters for the luma component only. | 365 | /// SAO parameters for the luma component only. |
crates/ec-h265/src/dec/shared.rsmodified+14 -32
| @@ -55,41 +55,26 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { | |||
| 55 | } | 55 | } |
| 56 | 56 | ||
| 57 | impl SharedPic { | 57 | impl SharedPic { |
| 58 | - /// The storage of a `width` by `height` picture of POC `poc`. With `pixels` | 58 | + /// The storage of a `width` by `height` picture of POC `poc`. |
| 59 | - /// false no sample planes are allocated (the motion-only decode). | ||
| 60 | pub fn new( | 59 | pub fn new( |
| 61 | poc: i32, | 60 | poc: i32, |
| 62 | width: usize, | 61 | width: usize, |
| 63 | height: usize, | 62 | height: usize, |
| 64 | bit_depth: (u32, u32), | 63 | bit_depth: (u32, u32), |
| 65 | - pixels: bool, | ||
| 66 | chroma_format_idc: u32, | 64 | chroma_format_idc: u32, |
| 67 | ) -> SharedPic { | 65 | ) -> SharedPic { |
| 68 | - let planes = if pixels { | 66 | + let (sx, sy) = crate::decode::chroma_shifts(chroma_format_idc); |
| 69 | - let (sx, sy) = crate::decode::chroma_shifts(chroma_format_idc); | 67 | + let cw = width.div_ceil(1 << sx); |
| 70 | - let cw = width.div_ceil(1 << sx); | 68 | + let ch = height.div_ceil(1 << sy); |
| 71 | - let ch = height.div_ceil(1 << sy); | 69 | + let planes = DecodedPicture { |
| 72 | - DecodedPicture { | 70 | + width, |
| 73 | - width, | 71 | + height, |
| 74 | - height, | 72 | + bit_depth: bit_depth.0, |
| 75 | - bit_depth: bit_depth.0, | 73 | + bit_depth_c: bit_depth.1, |
| 76 | - bit_depth_c: bit_depth.1, | 74 | + chroma_format_idc, |
| 77 | - chroma_format_idc, | 75 | + y: vec![0; width * height], |
| 78 | - y: vec![0; width * height], | 76 | + cb: vec![0; cw * ch], |
| 79 | - cb: vec![0; cw * ch], | 77 | + cr: vec![0; cw * ch], |
| 80 | - cr: vec![0; cw * ch], | ||
| 81 | - } | ||
| 82 | - } else { | ||
| 83 | - DecodedPicture { | ||
| 84 | - width, | ||
| 85 | - height, | ||
| 86 | - bit_depth: 8, | ||
| 87 | - bit_depth_c: 8, | ||
| 88 | - chroma_format_idc, | ||
| 89 | - y: Vec::new(), | ||
| 90 | - cb: Vec::new(), | ||
| 91 | - cr: Vec::new(), | ||
| 92 | - } | ||
| 93 | }; | 78 | }; |
| 94 | SharedPic { | 79 | SharedPic { |
| 95 | width, | 80 | width, |
| @@ -122,10 +107,7 @@ impl SharedPic { | |||
| 122 | /// Wait until at least `rows` luma rows are final. Returns the picture's failure | 107 | /// Wait until at least `rows` luma rows are final. Returns the picture's failure |
| 123 | /// instead when it has one. | 108 | /// instead when it has one. |
| 124 | pub fn wait_rows(&self, rows: usize) -> Result<()> { | 109 | pub fn wait_rows(&self, rows: usize) -> Result<()> { |
| 125 | - let t = super::trace::now(); | 110 | + self.wait_for(rows, |p| p.rows) |
| 126 | - let r = self.wait_for(rows, |p| p.rows); | ||
| 127 | - super::trace::since(super::trace::Phase::WaitRows, t); | ||
| 128 | - r | ||
| 129 | } | 111 | } |
| 130 | 112 | ||
| 131 | /// Wait until the collocated motion of at least `rows` luma rows is published. | 113 | /// Wait until the collocated motion of at least `rows` luma rows is published. |
crates/ec-h265/src/dec/trace.rsdeleted+0 -155
| @@ -1,155 +0,0 @@ | |||
| 1 | -//! Opt-in timing of the decoder's threads, for finding where they sit idle. | ||
| 2 | -//! | ||
| 3 | -//! `EC_H265_TRACE=1` turns it on. Off (the default), every hook is one check of a cached | ||
| 4 | -//! flag and no clock is read. On, each thread adds the time it spends in each [`Phase`] to | ||
| 5 | -//! its own totals. A thread's totals are merged into the table of its role when the thread | ||
| 6 | -//! ends (or, for the calling thread, when [`report`] runs), and [`report`] prints the table | ||
| 7 | -//! to stderr at the end of the stream. | ||
| 8 | - | ||
| 9 | -use std::cell::RefCell; | ||
| 10 | -use std::collections::BTreeMap; | ||
| 11 | -use std::sync::{Mutex, MutexGuard, OnceLock}; | ||
| 12 | -use std::time::{Duration, Instant}; | ||
| 13 | - | ||
| 14 | -/// The phases a thread's time is split into. | ||
| 15 | -#[derive(Clone, Copy, Debug)] | ||
| 16 | -pub enum Phase { | ||
| 17 | - /// Decoding a slice, a wavefront row, or finishing a picture (wall time; it includes | ||
| 18 | - /// the waits below that happen inside it). | ||
| 19 | - Decode = 0, | ||
| 20 | - /// Blocked until a reference picture has the rows a motion compensation reads. | ||
| 21 | - WaitRows = 1, | ||
| 22 | - /// Blocked joining the oldest in-flight picture to free a picture slot. | ||
| 23 | - WaitAdmit = 2, | ||
| 24 | - /// Blocked on the CABAC row-sync: the row above must be two CTBs ahead. | ||
| 25 | - WaitSync = 3, | ||
| 26 | - /// A picture worker idle, waiting for the next slice or the finish message. | ||
| 27 | - WaitMsg = 4, | ||
| 28 | - /// Blocked joining the picture workers at end of stream. | ||
| 29 | - WaitJoin = 5, | ||
| 30 | - /// Serial work on the calling thread outside the slice decode: picture start and | ||
| 31 | - /// finish (RPS, bumping, DPB insert). | ||
| 32 | - Serial = 6, | ||
| 33 | - /// Blocked until the collocated picture has the motion rows temporal prediction reads. | ||
| 34 | - WaitCol = 7, | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | -const N: usize = 8; | ||
| 38 | -/// Whether tracing is on (`EC_H265_TRACE` set to anything but `0`). | ||
| 39 | -pub fn on() -> bool { | ||
| 40 | - static ON: OnceLock<bool> = OnceLock::new(); | ||
| 41 | - *ON.get_or_init(|| std::env::var_os("EC_H265_TRACE").is_some_and(|v| v != "0")) | ||
| 42 | -} | ||
| 43 | - | ||
| 44 | -/// The start of a timed span, or `None` when tracing is off (no clock is read). | ||
| 45 | -#[inline] | ||
| 46 | -pub fn now() -> Option<Instant> { | ||
| 47 | - if on() { Some(Instant::now()) } else { None } | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -/// Add the time since `start` to `phase` of this thread. | ||
| 51 | -#[inline] | ||
| 52 | -pub fn since(phase: Phase, start: Option<Instant>) { | ||
| 53 | - if let Some(t) = start { | ||
| 54 | - add(phase, t.elapsed()); | ||
| 55 | - } | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -fn add(phase: Phase, d: Duration) { | ||
| 59 | - let _ = ACC.try_with(|a| { | ||
| 60 | - a.borrow_mut().ns[phase as usize] += d.as_nanos() as u64; | ||
| 61 | - }); | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -/// Name this thread's role in the report (the default is `caller`). | ||
| 65 | -pub fn set_role(role: &'static str) { | ||
| 66 | - if on() { | ||
| 67 | - let _ = ACC.try_with(|a| a.borrow_mut().role = role); | ||
| 68 | - } | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -#[derive(Default)] | ||
| 72 | -struct Totals { | ||
| 73 | - threads: usize, | ||
| 74 | - ns: [u64; N], | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -fn totals() -> MutexGuard<'static, BTreeMap<&'static str, Totals>> { | ||
| 78 | - static T: Mutex<BTreeMap<&'static str, Totals>> = Mutex::new(BTreeMap::new()); | ||
| 79 | - T.lock().unwrap_or_else(|e| e.into_inner()) | ||
| 80 | -} | ||
| 81 | - | ||
| 82 | -struct Acc { | ||
| 83 | - role: &'static str, | ||
| 84 | - ns: [u64; N], | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | -impl Acc { | ||
| 88 | - /// Merge this thread's totals into its role's table and clear them. | ||
| 89 | - fn merge(&mut self) { | ||
| 90 | - if self.ns.iter().all(|&n| n == 0) { | ||
| 91 | - return; | ||
| 92 | - } | ||
| 93 | - let mut t = totals(); | ||
| 94 | - let e = t.entry(self.role).or_default(); | ||
| 95 | - e.threads += 1; | ||
| 96 | - for (dst, src) in e.ns.iter_mut().zip(self.ns.iter()) { | ||
| 97 | - *dst += src; | ||
| 98 | - } | ||
| 99 | - self.ns = [0; N]; | ||
| 100 | - } | ||
| 101 | -} | ||
| 102 | - | ||
| 103 | -impl Drop for Acc { | ||
| 104 | - fn drop(&mut self) { | ||
| 105 | - self.merge(); | ||
| 106 | - } | ||
| 107 | -} | ||
| 108 | - | ||
| 109 | -thread_local! { | ||
| 110 | - static ACC: RefCell<Acc> = const { RefCell::new(Acc { role: "caller", ns: [0; N] }) }; | ||
| 111 | -} | ||
| 112 | - | ||
| 113 | -/// Merge the calling thread's totals, then print every role's table to stderr and clear | ||
| 114 | -/// the tables. Worker threads have merged already: they are joined before this runs. | ||
| 115 | -pub fn report() { | ||
| 116 | - if !on() { | ||
| 117 | - return; | ||
| 118 | - } | ||
| 119 | - let _ = ACC.try_with(|a| a.borrow_mut().merge()); | ||
| 120 | - let mut t = totals(); | ||
| 121 | - if t.is_empty() { | ||
| 122 | - return; | ||
| 123 | - } | ||
| 124 | - eprintln!("EC_H265_TRACE (ms, summed over the threads of each role)"); | ||
| 125 | - eprintln!( | ||
| 126 | - "{:<12}{:>8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}", | ||
| 127 | - "role", | ||
| 128 | - "threads", | ||
| 129 | - "decode", | ||
| 130 | - "wait_rows", | ||
| 131 | - "wait_col", | ||
| 132 | - "wait_admit", | ||
| 133 | - "wait_sync", | ||
| 134 | - "wait_msg", | ||
| 135 | - "wait_join", | ||
| 136 | - "serial" | ||
| 137 | - ); | ||
| 138 | - for (role, tot) in t.iter() { | ||
| 139 | - let ms = |p: Phase| tot.ns[p as usize] as f64 / 1e6; | ||
| 140 | - eprintln!( | ||
| 141 | - "{:<12}{:>8}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}", | ||
| 142 | - role, | ||
| 143 | - tot.threads, | ||
| 144 | - ms(Phase::Decode), | ||
| 145 | - ms(Phase::WaitRows), | ||
| 146 | - ms(Phase::WaitCol), | ||
| 147 | - ms(Phase::WaitAdmit), | ||
| 148 | - ms(Phase::WaitSync), | ||
| 149 | - ms(Phase::WaitMsg), | ||
| 150 | - ms(Phase::WaitJoin), | ||
| 151 | - ms(Phase::Serial), | ||
| 152 | - ); | ||
| 153 | - } | ||
| 154 | - t.clear(); | ||
| 155 | -} | ||
crates/ec-h265/src/decode.rsmodified+0 -28
| @@ -51,10 +51,6 @@ impl DecodedPicture { | |||
| 51 | let (sx, sy) = self.chroma_shifts(); | 51 | let (sx, sy) = self.chroma_shifts(); |
| 52 | (self.width.div_ceil(1 << sx), self.height.div_ceil(1 << sy)) | 52 | (self.width.div_ceil(1 << sx), self.height.div_ceil(1 << sy)) |
| 53 | } | 53 | } |
| 54 | - /// A picture of mid-grey samples (`1 << (bit_depth - 1)`). | ||
| 55 | - pub fn grey(width: usize, height: usize, bit_depth: u32) -> DecodedPicture { | ||
| 56 | - Self::grey_planes(width, height, bit_depth, bit_depth) | ||
| 57 | - } | ||
| 58 | 54 | ||
| 59 | /// A picture of mid-grey samples, each plane at its own bit depth. | 55 | /// A picture of mid-grey samples, each plane at its own bit depth. |
| 60 | pub fn grey_planes( | 56 | pub fn grey_planes( |
| @@ -62,16 +58,6 @@ impl DecodedPicture { | |||
| 62 | height: usize, | 58 | height: usize, |
| 63 | bit_depth: u32, | 59 | bit_depth: u32, |
| 64 | bit_depth_c: u32, | 60 | bit_depth_c: u32, |
| 65 | - ) -> DecodedPicture { | ||
| 66 | - Self::grey_planes_fmt(width, height, bit_depth, bit_depth_c, 1) | ||
| 67 | - } | ||
| 68 | - | ||
| 69 | - /// [`Self::grey_planes`] for any `chroma_format_idc`. | ||
| 70 | - pub fn grey_planes_fmt( | ||
| 71 | - width: usize, | ||
| 72 | - height: usize, | ||
| 73 | - bit_depth: u32, | ||
| 74 | - bit_depth_c: u32, | ||
| 75 | chroma_format_idc: u32, | 61 | chroma_format_idc: u32, |
| 76 | ) -> DecodedPicture { | 62 | ) -> DecodedPicture { |
| 77 | let mid = 1u16 << (bit_depth - 1); | 63 | let mid = 1u16 << (bit_depth - 1); |
| @@ -89,20 +75,6 @@ impl DecodedPicture { | |||
| 89 | cr: vec![mid_c; cw * ch], | 75 | cr: vec![mid_c; cw * ch], |
| 90 | } | 76 | } |
| 91 | } | 77 | } |
| 92 | - | ||
| 93 | - /// The bit depth of component `c` (0 luma, 1 and 2 chroma). | ||
| 94 | - pub fn bit_depth_of(&self, c: usize) -> u32 { | ||
| 95 | - if c == 0 { | ||
| 96 | - self.bit_depth | ||
| 97 | - } else { | ||
| 98 | - self.bit_depth_c | ||
| 99 | - } | ||
| 100 | - } | ||
| 101 | - | ||
| 102 | - /// The luma plane as 8-bit samples. Only meaningful for 8-bit pictures. | ||
| 103 | - pub fn y_u8(&self) -> Vec<u8> { | ||
| 104 | - self.y.iter().map(|&v| v as u8).collect() | ||
| 105 | - } | ||
| 106 | } | 78 | } |
| 107 | 79 | ||
| 108 | /// Decode one IDR access unit: VPS/SPS/PPS/slice NALs in Annex-B framing, one | 80 | /// Decode one IDR access unit: VPS/SPS/PPS/slice NALs in Annex-B framing, one |
crates/ec-h265/src/enc_p.rsmodified+90 -93
| @@ -22,7 +22,7 @@ | |||
| 22 | use crate::cabac::{CabacEncoder, Contexts, ctx}; | 22 | use crate::cabac::{CabacEncoder, Contexts, ctx}; |
| 23 | use crate::ctu::{Pel, lambda_for}; | 23 | use crate::ctu::{Pel, lambda_for}; |
| 24 | use crate::dec::amvp::derive_amvp; | 24 | use crate::dec::amvp::derive_amvp; |
| 25 | -use crate::dec::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; | 25 | +use crate::dec::cu_syntax::{PartMode, PredictionUnit}; |
| 26 | use crate::dec::deblock::{deblock_picture, deblock_rows}; | 26 | use crate::dec::deblock::{deblock_picture, deblock_rows}; |
| 27 | use crate::dec::mc::{Block, McScratch, PlaneMut, PlaneRef, RefPicture, predict_pu}; | 27 | use crate::dec::mc::{Block, McScratch, PlaneMut, PlaneRef, RefPicture, predict_pu}; |
| 28 | use crate::dec::merge::derive_merge; | 28 | use crate::dec::merge::derive_merge; |
| @@ -71,8 +71,22 @@ const EARLY_SKIP_COST: f64 = 4.0; | |||
| 71 | /// Mean absolute difference per sample below which a motion-searched block is not split. | 71 | /// Mean absolute difference per sample below which a motion-searched block is not split. |
| 72 | const EARLY_SPLIT_SAD: f64 = 0.25; | 72 | const EARLY_SPLIT_SAD: f64 = 0.25; |
| 73 | 73 | ||
| 74 | -/// Search thresholds of the P-picture decision. The defaults are the measured | 74 | +/// Intra modes costed in full, the best by SAD of their prediction. |
| 75 | -/// values; the `EC_H265_*` overrides exist for the sweep in the lane report. | 75 | +const INTRA_K: usize = 1; |
| 76 | +/// Residual energy bound below which a transform block is taken to quantise to zero. | ||
| 77 | +const ZERO_ALPHA: f64 = 24.0; | ||
| 78 | +/// First pattern step (quarter samples) of the search for 16x16 blocks. | ||
| 79 | +const STEP16: i16 = 16; | ||
| 80 | +/// First pattern step (quarter samples) of the search for 8x8 blocks. | ||
| 81 | +const STEP8: i16 = 16; | ||
| 82 | +/// First pattern step (quarter samples) of the search for split partitions. | ||
| 83 | +const STEP_PART: i16 = 16; | ||
| 84 | +/// Whole-sample scan stride. | ||
| 85 | +const FULL_STRIDE: i16 = 4; | ||
| 86 | +/// Sub-sample refinement passes. | ||
| 87 | +const SUB_PASSES: u32 = 1; | ||
| 88 | + | ||
| 89 | +/// Search thresholds of the P-picture decision, per speed preset. | ||
| 76 | #[derive(Clone, Copy)] | 90 | #[derive(Clone, Copy)] |
| 77 | pub(crate) struct PKnobs { | 91 | pub(crate) struct PKnobs { |
| 78 | /// Whole-sample scan half-width for blocks of 32 and up. | 92 | /// Whole-sample scan half-width for blocks of 32 and up. |
| @@ -87,80 +101,74 @@ pub(crate) struct PKnobs { | |||
| 87 | full_gate: f64, | 101 | full_gate: f64, |
| 88 | /// Cost per sample below which the best inter candidate ends the intra search. | 102 | /// Cost per sample below which the best inter candidate ends the intra search. |
| 89 | intra_gate: f64, | 103 | intra_gate: f64, |
| 90 | - /// Intra luma modes costed in full, the best by SAD of their prediction. | ||
| 91 | - intra_k: usize, | ||
| 92 | - /// A transform block whose residual energy times the transform gain is below this many | ||
| 93 | - /// squares of the smallest non-zero coefficient is taken to quantise to zero without | ||
| 94 | - /// transforming it (1 is the bound that is exact; larger trades a little accuracy). | ||
| 95 | - zero_alpha: f64, | ||
| 96 | - /// First pattern step (quarter samples) of the search for 16x16 and 8x8 blocks, and halves. | ||
| 97 | - step16: i16, | ||
| 98 | - step8: i16, | ||
| 99 | - step_part: i16, | ||
| 100 | - full_stride: i16, | ||
| 101 | - res_proxy: bool, | ||
| 102 | - sub_passes: u32, | ||
| 103 | /// Most distinct merge candidates costed in full. | 104 | /// Most distinct merge candidates costed in full. |
| 104 | merge_max: usize, | 105 | merge_max: usize, |
| 105 | /// Cost both AMVP predictor flags (otherwise only the one with the smaller vector difference). | 106 | /// Cost both AMVP predictor flags (otherwise only the one with the smaller vector difference). |
| 106 | amvp_both: bool, | 107 | amvp_both: bool, |
| 107 | /// log2 of the smallest inter coding unit the analysis searches (3 = 8x8). | 108 | /// log2 of the smallest inter coding unit the analysis searches (3 = 8x8). |
| 108 | min_log2: u32, | 109 | min_log2: u32, |
| 109 | - /// Smallest square (samples) whose horizontal and vertical halves are searched and costed. | ||
| 110 | - halves_min: usize, | ||
| 111 | /// Most intra luma modes considered (MPMs first) before the SAD ranking. | 110 | /// Most intra luma modes considered (MPMs first) before the SAD ranking. |
| 112 | intra_modes: usize, | 111 | intra_modes: usize, |
| 113 | /// Cost per sample below which the sub-sample refinement is skipped. | 112 | /// Cost per sample below which the sub-sample refinement is skipped. |
| 114 | sub_gate: f64, | 113 | sub_gate: f64, |
| 115 | /// Skip the quarter-sample refinement step. | 114 | /// Skip the quarter-sample refinement step. |
| 116 | no_quarter: bool, | 115 | no_quarter: bool, |
| 116 | + /// Smallest square (samples) whose horizontal and vertical halves are searched and costed. | ||
| 117 | + halves_min: usize, | ||
| 117 | } | 118 | } |
| 118 | 119 | ||
| 120 | +const PKNOBS: [PKnobs; 3] = [ | ||
| 121 | + PKnobs { | ||
| 122 | + full_large: FULL_RANGE_LARGE, | ||
| 123 | + full_small: FULL_RANGE_SMALL, | ||
| 124 | + split_sad: EARLY_SPLIT_SAD, | ||
| 125 | + skip_cost: EARLY_SKIP_COST, | ||
| 126 | + full_gate: 4.0, | ||
| 127 | + intra_gate: 0.0, | ||
| 128 | + merge_max: 5, | ||
| 129 | + amvp_both: true, | ||
| 130 | + min_log2: 3, | ||
| 131 | + intra_modes: 7, | ||
| 132 | + sub_gate: 0.0, | ||
| 133 | + no_quarter: false, | ||
| 134 | + halves_min: 16, | ||
| 135 | + }, | ||
| 136 | + PKnobs { | ||
| 137 | + full_large: 8, | ||
| 138 | + full_small: 4, | ||
| 139 | + split_sad: 1.0, | ||
| 140 | + skip_cost: 16.0, | ||
| 141 | + full_gate: 12.0, | ||
| 142 | + intra_gate: 6.0, | ||
| 143 | + merge_max: 3, | ||
| 144 | + amvp_both: false, | ||
| 145 | + min_log2: 3, | ||
| 146 | + intra_modes: 3, | ||
| 147 | + sub_gate: 1.0, | ||
| 148 | + no_quarter: false, | ||
| 149 | + halves_min: 32, | ||
| 150 | + }, | ||
| 151 | + PKnobs { | ||
| 152 | + full_large: 4, | ||
| 153 | + full_small: 0, | ||
| 154 | + split_sad: 2.0, | ||
| 155 | + skip_cost: 32.0, | ||
| 156 | + full_gate: 16.0, | ||
| 157 | + intra_gate: 12.0, | ||
| 158 | + merge_max: 2, | ||
| 159 | + amvp_both: false, | ||
| 160 | + min_log2: 4, | ||
| 161 | + intra_modes: 2, | ||
| 162 | + sub_gate: 2.0, | ||
| 163 | + no_quarter: true, | ||
| 164 | + halves_min: 1024, | ||
| 165 | + }, | ||
| 166 | +]; | ||
| 167 | + | ||
| 119 | impl PKnobs { | 168 | impl PKnobs { |
| 120 | - /// The knobs of a speed preset. `Default` is the measured set; `EC_H265_*` | 169 | + /// The knobs of a speed preset. |
| 121 | - /// environment variables override any of them (sweeps only). | ||
| 122 | pub(crate) fn for_preset(p: Preset) -> PKnobs { | 170 | pub(crate) fn for_preset(p: Preset) -> PKnobs { |
| 123 | - let f = |name: &str, d: f64| { | 171 | + PKNOBS[p as usize] |
| 124 | - std::env::var(name) | ||
| 125 | - .ok() | ||
| 126 | - .and_then(|v| v.parse::<f64>().ok()) | ||
| 127 | - .unwrap_or(d) | ||
| 128 | - }; | ||
| 129 | - // (fast, faster) values against the default. | ||
| 130 | - let pick = |d: f64, fast: f64, faster: f64| match p { | ||
| 131 | - Preset::Default => d, | ||
| 132 | - Preset::Fast => fast, | ||
| 133 | - Preset::Faster => faster, | ||
| 134 | - }; | ||
| 135 | - PKnobs { | ||
| 136 | - full_large: f( | ||
| 137 | - "EC_H265_FULL_LARGE", | ||
| 138 | - pick(f64::from(FULL_RANGE_LARGE), 8.0, 4.0), | ||
| 139 | - ) as i16, | ||
| 140 | - full_small: f( | ||
| 141 | - "EC_H265_FULL_SMALL", | ||
| 142 | - pick(f64::from(FULL_RANGE_SMALL), 4.0, 0.0), | ||
| 143 | - ) as i16, | ||
| 144 | - split_sad: f("EC_H265_SPLIT_SAD", pick(EARLY_SPLIT_SAD, 1.0, 2.0)), | ||
| 145 | - skip_cost: f("EC_H265_SKIP_COST", pick(EARLY_SKIP_COST, 16.0, 32.0)), | ||
| 146 | - full_gate: f("EC_H265_FULL_GATE", pick(4.0, 12.0, 16.0)), | ||
| 147 | - intra_gate: f("EC_H265_INTRA_GATE", pick(0.0, 6.0, 12.0)), | ||
| 148 | - intra_k: f("EC_H265_INTRA_K", 1.0) as usize, | ||
| 149 | - zero_alpha: f("EC_H265_ZERO_ALPHA", pick(24.0, 24.0, 24.0)), | ||
| 150 | - step16: f("EC_H265_STEP16", 16.0) as i16, | ||
| 151 | - step8: f("EC_H265_STEP8", 16.0) as i16, | ||
| 152 | - step_part: f("EC_H265_STEPP", 16.0) as i16, | ||
| 153 | - full_stride: f("EC_H265_FULL_STRIDE", 4.0) as i16, | ||
| 154 | - sub_passes: f("EC_H265_SUB_PASSES", pick(1.0, 1.0, 1.0)) as u32, | ||
| 155 | - res_proxy: f("EC_H265_RES_PROXY", 1.0) != 0.0, | ||
| 156 | - merge_max: f("EC_H265_MERGE_MAX", pick(5.0, 3.0, 2.0)) as usize, | ||
| 157 | - amvp_both: f("EC_H265_AMVP_BOTH", pick(1.0, 0.0, 0.0)) != 0.0, | ||
| 158 | - min_log2: f("EC_H265_MIN_LOG2", pick(3.0, 3.0, 4.0)) as u32, | ||
| 159 | - intra_modes: f("EC_H265_INTRA_MODES", pick(7.0, 3.0, 2.0)) as usize, | ||
| 160 | - sub_gate: f("EC_H265_SUB_GATE", pick(0.0, 1.0, 2.0)), | ||
| 161 | - no_quarter: f("EC_H265_NO_QUARTER", pick(0.0, 0.0, 1.0)) != 0.0, | ||
| 162 | - halves_min: f("EC_H265_HALVES_MIN", pick(16.0, 32.0, 1024.0)) as usize, | ||
| 163 | - } | ||
| 164 | } | 172 | } |
| 165 | } | 173 | } |
| 166 | 174 | ||
| @@ -577,7 +585,7 @@ impl<'a> PCoder<'a> { | |||
| 577 | bit_depth: bd, | 585 | bit_depth: bd, |
| 578 | }, | 586 | }, |
| 579 | ]; | 587 | ]; |
| 580 | - let mut pic = PicState::new(w, h, ctb_log2, 2, bd, bd, true); | 588 | + let mut pic = PicState::new(w, h, ctb_log2, 2, bd, bd); |
| 581 | pic.strong_intra_smoothing = true; // as the sequence parameter set says | 589 | pic.strong_intra_smoothing = true; // as the sequence parameter set says |
| 582 | pic.slices = vec![SliceFilter { | 590 | pic.slices = vec![SliceFilter { |
| 583 | deblock_disabled: !enc.cfg.deblock, | 591 | deblock_disabled: !enc.cfg.deblock, |
| @@ -728,14 +736,14 @@ impl<'a> PCoder<'a> { | |||
| 728 | self.k.full_small | 736 | self.k.full_small |
| 729 | }, | 737 | }, |
| 730 | full_gate: self.k.full_gate, | 738 | full_gate: self.k.full_gate, |
| 731 | - full_stride: self.k.full_stride, | 739 | + full_stride: FULL_STRIDE, |
| 732 | - sub_passes: self.k.sub_passes, | 740 | + sub_passes: SUB_PASSES, |
| 733 | sub_gate: self.k.sub_gate, | 741 | sub_gate: self.k.sub_gate, |
| 734 | no_quarter: self.k.no_quarter, | 742 | no_quarter: self.k.no_quarter, |
| 735 | first_step: match n { | 743 | first_step: match n { |
| 736 | 32.. => 16, | 744 | 32.. => 16, |
| 737 | - 16.. => self.k.step16, | 745 | + 16.. => STEP16, |
| 738 | - _ => self.k.step8, | 746 | + _ => STEP8, |
| 739 | }, | 747 | }, |
| 740 | }; | 748 | }; |
| 741 | let best = search.run((x, y), (n, n), mvp, &seeds); | 749 | let best = search.run((x, y), (n, n), mvp, &seeds); |
| @@ -800,10 +808,10 @@ impl<'a> PCoder<'a> { | |||
| 800 | full_range: 0, | 808 | full_range: 0, |
| 801 | full_gate: 0.0, | 809 | full_gate: 0.0, |
| 802 | full_stride: 1, | 810 | full_stride: 1, |
| 803 | - sub_passes: self.k.sub_passes, | 811 | + sub_passes: SUB_PASSES, |
| 804 | sub_gate: self.k.sub_gate, | 812 | sub_gate: self.k.sub_gate, |
| 805 | no_quarter: self.k.no_quarter, | 813 | no_quarter: self.k.no_quarter, |
| 806 | - first_step: self.k.step_part, | 814 | + first_step: STEP_PART, |
| 807 | }; | 815 | }; |
| 808 | let best = search.run((rx, ry), (rw, rh), mvp, &seeds); | 816 | let best = search.run((rx, ry), (rw, rh), mvp, &seeds); |
| 809 | total += best.cost; | 817 | total += best.cost; |
| @@ -905,13 +913,6 @@ impl<'a> PCoder<'a> { | |||
| 905 | ) -> Result<()> { | 913 | ) -> Result<()> { |
| 906 | let n = 1usize << log2; | 914 | let n = 1usize << log2; |
| 907 | let analysis_mv = analysis.mv; | 915 | let analysis_mv = analysis.mv; |
| 908 | - let geom = CuGeometry { | ||
| 909 | - x, | ||
| 910 | - y, | ||
| 911 | - size: n, | ||
| 912 | - part_mode: PartMode::Part2Nx2N, | ||
| 913 | - skip: false, | ||
| 914 | - }; | ||
| 915 | // Candidate motions: each distinct merge candidate, then AMVP with the | 916 | // Candidate motions: each distinct merge candidate, then AMVP with the |
| 916 | // analysed vector under either predictor. | 917 | // analysed vector under either predictor. |
| 917 | let mut merge_motions: Vec<(u8, PbMotion)> = Vec::new(); | 918 | let mut merge_motions: Vec<(u8, PbMotion)> = Vec::new(); |
| @@ -927,7 +928,7 @@ impl<'a> PCoder<'a> { | |||
| 927 | }; | 928 | }; |
| 928 | let m = { | 929 | let m = { |
| 929 | let sm = self.sm(); | 930 | let sm = self.sm(); |
| 930 | - derive_merge(&sm, &geom, 0, &pu) | 931 | + derive_merge(&sm, x, y, n, PartMode::Part2Nx2N, 0, &pu) |
| 931 | }; | 932 | }; |
| 932 | if merge_motions.iter().all(|(_, prev)| *prev != m) { | 933 | if merge_motions.iter().all(|(_, prev)| *prev != m) { |
| 933 | merge_motions.push((idx, m)); | 934 | merge_motions.push((idx, m)); |
| @@ -1009,7 +1010,7 @@ impl<'a> PCoder<'a> { | |||
| 1009 | let inter_best = best.as_ref().map_or(f64::MAX, |(c, _, _)| *c); | 1010 | let inter_best = best.as_ref().map_or(f64::MAX, |(c, _, _)| *c); |
| 1010 | if inter_best < self.k.intra_gate * (n * n) as f64 { | 1011 | if inter_best < self.k.intra_gate * (n * n) as f64 { |
| 1011 | modes.clear(); | 1012 | modes.clear(); |
| 1012 | - } else if self.k.intra_k < modes.len() { | 1013 | + } else if INTRA_K < modes.len() { |
| 1013 | let mut ranked: Vec<(u64, u8)> = modes | 1014 | let mut ranked: Vec<(u64, u8)> = modes |
| 1014 | .iter() | 1015 | .iter() |
| 1015 | .map(|&m| { | 1016 | .map(|&m| { |
| @@ -1018,11 +1019,7 @@ impl<'a> PCoder<'a> { | |||
| 1018 | }) | 1019 | }) |
| 1019 | .collect(); | 1020 | .collect(); |
| 1020 | ranked.sort_unstable(); | 1021 | ranked.sort_unstable(); |
| 1021 | - modes = ranked | 1022 | + modes = ranked.into_iter().take(INTRA_K).map(|(_, m)| m).collect(); |
| 1022 | - .into_iter() | ||
| 1023 | - .take(self.k.intra_k) | ||
| 1024 | - .map(|(_, m)| m) | ||
| 1025 | - .collect(); | ||
| 1026 | } | 1023 | } |
| 1027 | let no_motion = PbMotion::new([false, false], [-1, -1], [[0, 0], [0, 0]]); | 1024 | let no_motion = PbMotion::new([false, false], [-1, -1], [[0, 0], [0, 0]]); |
| 1028 | for mode in modes { | 1025 | for mode in modes { |
| @@ -1182,7 +1179,7 @@ impl<'a> PCoder<'a> { | |||
| 1182 | self.bd, | 1179 | self.bd, |
| 1183 | sh, | 1180 | sh, |
| 1184 | (0, false), | 1181 | (0, false), |
| 1185 | - self.k.zero_alpha, | 1182 | + ZERO_ALPHA, |
| 1186 | ); | 1183 | ); |
| 1187 | let cb = code_tb( | 1184 | let cb = code_tb( |
| 1188 | &src.cb, | 1185 | &src.cb, |
| @@ -1195,7 +1192,7 @@ impl<'a> PCoder<'a> { | |||
| 1195 | self.bd, | 1192 | self.bd, |
| 1196 | sh, | 1193 | sh, |
| 1197 | (0, false), | 1194 | (0, false), |
| 1198 | - self.k.zero_alpha, | 1195 | + ZERO_ALPHA, |
| 1199 | ); | 1196 | ); |
| 1200 | let cr = code_tb( | 1197 | let cr = code_tb( |
| 1201 | &src.cr, | 1198 | &src.cr, |
| @@ -1208,7 +1205,7 @@ impl<'a> PCoder<'a> { | |||
| 1208 | self.bd, | 1205 | self.bd, |
| 1209 | sh, | 1206 | sh, |
| 1210 | (0, false), | 1207 | (0, false), |
| 1211 | - self.k.zero_alpha, | 1208 | + ZERO_ALPHA, |
| 1212 | ); | 1209 | ); |
| 1213 | ssd += luma.ssd + cb.ssd + cr.ssd; | 1210 | ssd += luma.ssd + cb.ssd + cr.ssd; |
| 1214 | for r in 0..half { | 1211 | for r in 0..half { |
| @@ -1278,7 +1275,7 @@ impl<'a> PCoder<'a> { | |||
| 1278 | self.bd, | 1275 | self.bd, |
| 1279 | sh, | 1276 | sh, |
| 1280 | (0, false), | 1277 | (0, false), |
| 1281 | - self.k.zero_alpha, | 1278 | + ZERO_ALPHA, |
| 1282 | ); | 1279 | ); |
| 1283 | let cb = code_tb( | 1280 | let cb = code_tb( |
| 1284 | &src.cb, | 1281 | &src.cb, |
| @@ -1291,7 +1288,7 @@ impl<'a> PCoder<'a> { | |||
| 1291 | self.bd, | 1288 | self.bd, |
| 1292 | sh, | 1289 | sh, |
| 1293 | (0, false), | 1290 | (0, false), |
| 1294 | - self.k.zero_alpha, | 1291 | + ZERO_ALPHA, |
| 1295 | ); | 1292 | ); |
| 1296 | let cr = code_tb( | 1293 | let cr = code_tb( |
| 1297 | &src.cr, | 1294 | &src.cr, |
| @@ -1304,7 +1301,7 @@ impl<'a> PCoder<'a> { | |||
| 1304 | self.bd, | 1301 | self.bd, |
| 1305 | sh, | 1302 | sh, |
| 1306 | (0, false), | 1303 | (0, false), |
| 1307 | - self.k.zero_alpha, | 1304 | + ZERO_ALPHA, |
| 1308 | ); | 1305 | ); |
| 1309 | let cbf = [luma.cbf, cb.cbf, cr.cbf]; | 1306 | let cbf = [luma.cbf, cb.cbf, cr.cbf]; |
| 1310 | let any = cbf.iter().any(|&c| c); | 1307 | let any = cbf.iter().any(|&c| c); |
| @@ -1430,7 +1427,7 @@ impl<'a> PCoder<'a> { | |||
| 1430 | self.bd, | 1427 | self.bd, |
| 1431 | sh, | 1428 | sh, |
| 1432 | (scan, n == 4), | 1429 | (scan, n == 4), |
| 1433 | - self.k.zero_alpha, | 1430 | + ZERO_ALPHA, |
| 1434 | ); | 1431 | ); |
| 1435 | let cb = code_tb( | 1432 | let cb = code_tb( |
| 1436 | &src.cb, | 1433 | &src.cb, |
| @@ -1443,7 +1440,7 @@ impl<'a> PCoder<'a> { | |||
| 1443 | self.bd, | 1440 | self.bd, |
| 1444 | sh, | 1441 | sh, |
| 1445 | (cscan, false), | 1442 | (cscan, false), |
| 1446 | - self.k.zero_alpha, | 1443 | + ZERO_ALPHA, |
| 1447 | ); | 1444 | ); |
| 1448 | let cr = code_tb( | 1445 | let cr = code_tb( |
| 1449 | &src.cr, | 1446 | &src.cr, |
| @@ -1456,7 +1453,7 @@ impl<'a> PCoder<'a> { | |||
| 1456 | self.bd, | 1453 | self.bd, |
| 1457 | sh, | 1454 | sh, |
| 1458 | (cscan, false), | 1455 | (cscan, false), |
| 1459 | - self.k.zero_alpha, | 1456 | + ZERO_ALPHA, |
| 1460 | ); | 1457 | ); |
| 1461 | let syntax = CuSyntax { | 1458 | let syntax = CuSyntax { |
| 1462 | skip: false, | 1459 | skip: false, |
| @@ -1589,7 +1586,7 @@ impl<'a> PCoder<'a> { | |||
| 1589 | c_idx: usize, | 1586 | c_idx: usize, |
| 1590 | scan: usize, | 1587 | scan: usize, |
| 1591 | ) { | 1588 | ) { |
| 1592 | - if e.is_estimating() && self.k.res_proxy { | 1589 | + if e.is_estimating() { |
| 1593 | e.add_estimated_bits(estimate_residual_bits(levels, log2, scan)); | 1590 | e.add_estimated_bits(estimate_residual_bits(levels, log2, scan)); |
| 1594 | } else { | 1591 | } else { |
| 1595 | encode_residual(e, levels, log2, c_idx, scan, self.sign_hiding, None); | 1592 | encode_residual(e, levels, log2, c_idx, scan, self.sign_hiding, None); |
| @@ -1835,7 +1832,7 @@ pub(crate) fn code_p_picture( | |||
| 1835 | true, | 1832 | true, |
| 1836 | ); | 1833 | ); |
| 1837 | write_annex_b(&mut au, NalHeader::new(NalUnitType::TrailR), &rbsp, true); | 1834 | write_annex_b(&mut au, NalHeader::new(NalUnitType::TrailR), &rbsp, true); |
| 1838 | - let shared = Arc::new(SharedPic::new(poc, w, h, (8, 8), false, 1)); | 1835 | + let shared = Arc::new(SharedPic::new(poc, w, h, (8, 8), 1)); |
| 1839 | shared.publish_col(&field, h); | 1836 | shared.publish_col(&field, h); |
| 1840 | Ok((au, recon, PrevPic { field, shared })) | 1837 | Ok((au, recon, PrevPic { field, shared })) |
| 1841 | } | 1838 | } |
crates/ec-h265/src/encoder.rsmodified+8 -3
| @@ -989,9 +989,9 @@ impl Encoder { | |||
| 989 | true, | 989 | true, |
| 990 | ); | 990 | ); |
| 991 | if let Some(rbsp) = | 991 | if let Some(rbsp) = |
| 992 | - sei::hdr_metadata_rbsp_with(self.cfg.mastering_display, self.cfg.content_light) | 992 | + sei::hdr_metadata_rbsp(self.cfg.mastering_display, self.cfg.content_light) |
| 993 | { | 993 | { |
| 994 | - write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); | 994 | + write_annex_b(&mut au, NalHeader::new(NalUnitType::PrefixSei), &rbsp, true); |
| 995 | } | 995 | } |
| 996 | 996 | ||
| 997 | // Entry points count the bytes as they appear in the NAL, emulation | 997 | // Entry points count the bytes as they appear in the NAL, emulation |
| @@ -1033,7 +1033,12 @@ impl Encoder { | |||
| 1033 | (&bcb, w / 2 * bps, w / 2 * bps, h / 2), | 1033 | (&bcb, w / 2 * bps, w / 2 * bps, h / 2), |
| 1034 | (&bcr, w / 2 * bps, w / 2 * bps, h / 2), | 1034 | (&bcr, w / 2 * bps, w / 2 * bps, h / 2), |
| 1035 | ]); | 1035 | ]); |
| 1036 | - write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); | 1036 | + write_annex_b( |
| 1037 | + &mut au, | ||
| 1038 | + NalHeader::new(NalUnitType::SuffixSei), | ||
| 1039 | + &rbsp, | ||
| 1040 | + false, | ||
| 1041 | + ); | ||
| 1037 | } | 1042 | } |
| 1038 | au | 1043 | au |
| 1039 | } | 1044 | } |
crates/ec-h265/src/residual.rsmodified+0 -258
| @@ -1618,262 +1618,4 @@ mod tests { | |||
| 1618 | } | 1618 | } |
| 1619 | } | 1619 | } |
| 1620 | } | 1620 | } |
| 1621 | - | ||
| 1622 | - /// [`rdoq`], but every trial re-derives the whole block's bits from `base` | ||
| 1623 | - /// (the pre-change behaviour) instead of using the sub-block frozen-prefix | ||
| 1624 | - /// cursor. Kept only for | ||
| 1625 | - /// [`sub_block_cursor_matches_full_recompute`] to check the cursor against. | ||
| 1626 | - #[allow(clippy::too_many_arguments)] | ||
| 1627 | - fn rdoq_full_recompute( | ||
| 1628 | - coeffs: &[i32], | ||
| 1629 | - levels: &mut [i32], | ||
| 1630 | - n: usize, | ||
| 1631 | - qp: i32, | ||
| 1632 | - bit_depth: u32, | ||
| 1633 | - c_idx: usize, | ||
| 1634 | - scan_idx: usize, | ||
| 1635 | - cbf_ctx: usize, | ||
| 1636 | - lambda: f64, | ||
| 1637 | - transform_skip: Option<bool>, | ||
| 1638 | - enc: &mut CabacEncoder, | ||
| 1639 | - ) -> usize { | ||
| 1640 | - let log2_size = n.trailing_zeros(); | ||
| 1641 | - let scale = coeff_ssd_scale(n); | ||
| 1642 | - let lambda = RDOQ_LAMBDA * lambda; | ||
| 1643 | - let base = enc.snapshot(); | ||
| 1644 | - let err = |level: i32, coeff: i32| { | ||
| 1645 | - let d = f64::from(dequant_level_bd(level, n, qp, bit_depth) - coeff); | ||
| 1646 | - d * d | ||
| 1647 | - }; | ||
| 1648 | - | ||
| 1649 | - let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum(); | ||
| 1650 | - let bits = levels_bits( | ||
| 1651 | - enc, | ||
| 1652 | - &base, | ||
| 1653 | - levels, | ||
| 1654 | - log2_size, | ||
| 1655 | - c_idx, | ||
| 1656 | - scan_idx, | ||
| 1657 | - cbf_ctx, | ||
| 1658 | - true, | ||
| 1659 | - transform_skip, | ||
| 1660 | - ); | ||
| 1661 | - let mut cost = scale * dist + lambda * bits; | ||
| 1662 | - | ||
| 1663 | - let sub_scan = scan(log2_size - 2, scan_idx); | ||
| 1664 | - let pos_scan = scan(2, scan_idx); | ||
| 1665 | - let order: Vec<usize> = sub_scan | ||
| 1666 | - .iter() | ||
| 1667 | - .flat_map(|&(xs, ys)| { | ||
| 1668 | - pos_scan.iter().map(move |&(xp, yp)| { | ||
| 1669 | - (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize | ||
| 1670 | - }) | ||
| 1671 | - }) | ||
| 1672 | - .collect(); | ||
| 1673 | - | ||
| 1674 | - let sub_wide = n >> 2; | ||
| 1675 | - let mut csbf = [false; 64]; | ||
| 1676 | - let mut sub_count = [0i32; 64]; | ||
| 1677 | - let mut nz_positions: Vec<i32> = Vec::new(); | ||
| 1678 | - for (k, &i) in order.iter().enumerate().rev() { | ||
| 1679 | - if levels[i] != 0 { | ||
| 1680 | - nz_positions.push(k as i32); | ||
| 1681 | - let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2); | ||
| 1682 | - sub_count[sub_idx] += 1; | ||
| 1683 | - csbf[sub_idx] = true; | ||
| 1684 | - } | ||
| 1685 | - } | ||
| 1686 | - let mut cur_last = nz_positions.first().copied().unwrap_or(0); | ||
| 1687 | - let mut nz_idx = 0usize; | ||
| 1688 | - | ||
| 1689 | - for (k, &i) in order.iter().enumerate().rev() { | ||
| 1690 | - let level = levels[i]; | ||
| 1691 | - if level == 0 { | ||
| 1692 | - continue; | ||
| 1693 | - } | ||
| 1694 | - let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0); | ||
| 1695 | - nz_idx += 1; | ||
| 1696 | - if level.abs() > RDOQ_MAX_LEVEL { | ||
| 1697 | - continue; | ||
| 1698 | - } | ||
| 1699 | - let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2); | ||
| 1700 | - let mut tried = level.abs(); | ||
| 1701 | - for candidate in [level.abs() - 1, 0] { | ||
| 1702 | - if candidate == tried { | ||
| 1703 | - continue; | ||
| 1704 | - } | ||
| 1705 | - tried = candidate; | ||
| 1706 | - let keep = levels[i]; | ||
| 1707 | - levels[i] = candidate * level.signum(); | ||
| 1708 | - let now_zero = levels[i] == 0; | ||
| 1709 | - let sub_count_before = sub_count[sub_idx]; | ||
| 1710 | - let csbf_before = csbf[sub_idx]; | ||
| 1711 | - if now_zero { | ||
| 1712 | - sub_count[sub_idx] -= 1; | ||
| 1713 | - csbf[sub_idx] = sub_count[sub_idx] > 0; | ||
| 1714 | - } | ||
| 1715 | - let trial_last = if now_zero && k as i32 == cur_last { | ||
| 1716 | - next_last | ||
| 1717 | - } else { | ||
| 1718 | - cur_last | ||
| 1719 | - }; | ||
| 1720 | - let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]); | ||
| 1721 | - let any = sub_count.iter().any(|&c| c > 0); | ||
| 1722 | - let trial_bits = levels_bits_with( | ||
| 1723 | - enc, | ||
| 1724 | - &base, | ||
| 1725 | - levels, | ||
| 1726 | - log2_size, | ||
| 1727 | - c_idx, | ||
| 1728 | - scan_idx, | ||
| 1729 | - cbf_ctx, | ||
| 1730 | - any, | ||
| 1731 | - transform_skip, | ||
| 1732 | - trial_last, | ||
| 1733 | - csbf, | ||
| 1734 | - ); | ||
| 1735 | - let trial = scale * trial_dist + lambda * trial_bits; | ||
| 1736 | - if trial < cost { | ||
| 1737 | - cost = trial; | ||
| 1738 | - dist = trial_dist; | ||
| 1739 | - if now_zero { | ||
| 1740 | - cur_last = trial_last; | ||
| 1741 | - } | ||
| 1742 | - } else { | ||
| 1743 | - levels[i] = keep; | ||
| 1744 | - sub_count[sub_idx] = sub_count_before; | ||
| 1745 | - csbf[sub_idx] = csbf_before; | ||
| 1746 | - } | ||
| 1747 | - } | ||
| 1748 | - } | ||
| 1749 | - let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum(); | ||
| 1750 | - let zero_bits = levels_bits( | ||
| 1751 | - enc, | ||
| 1752 | - &base, | ||
| 1753 | - levels, | ||
| 1754 | - log2_size, | ||
| 1755 | - c_idx, | ||
| 1756 | - scan_idx, | ||
| 1757 | - cbf_ctx, | ||
| 1758 | - false, | ||
| 1759 | - transform_skip, | ||
| 1760 | - ); | ||
| 1761 | - if scale * zero_dist + lambda * zero_bits <= cost { | ||
| 1762 | - levels[..n * n].fill(0); | ||
| 1763 | - enc.restore(&base); | ||
| 1764 | - return 0; | ||
| 1765 | - } | ||
| 1766 | - enc.restore(&base); | ||
| 1767 | - levels[..n * n].iter().filter(|&&l| l != 0).count() | ||
| 1768 | - } | ||
| 1769 | - | ||
| 1770 | - /// A tiny xorshift RNG — deterministic across runs, no extra dependency. | ||
| 1771 | - struct Xorshift(u32); | ||
| 1772 | - impl Xorshift { | ||
| 1773 | - fn next(&mut self) -> u32 { | ||
| 1774 | - self.0 ^= self.0 << 13; | ||
| 1775 | - self.0 ^= self.0 >> 17; | ||
| 1776 | - self.0 ^= self.0 << 5; | ||
| 1777 | - self.0 | ||
| 1778 | - } | ||
| 1779 | - } | ||
| 1780 | - | ||
| 1781 | - /// ENTRY GATE for lane-h265rdoq r3: the sub-block frozen-prefix cursor | ||
| 1782 | - /// [`rdoq`] now uses must produce bit-for-bit the same trial decisions — | ||
| 1783 | - /// and so the same final `levels` and the same final bitstream — as | ||
| 1784 | - /// always re-deriving every trial's bits from the block's start | ||
| 1785 | - /// ([`rdoq_full_recompute`], this round's pre-change behaviour). Covers | ||
| 1786 | - /// every block size with a sub-block split (8/16/32 — 4x4 has none), | ||
| 1787 | - /// every scan, 8 seeds, sign-hiding on/off on the final bitstream, and | ||
| 1788 | - /// deliberately includes levels of magnitude 1-3 so some trials drop the | ||
| 1789 | - /// last significant coefficient, some empty a whole sub-block (csbf | ||
| 1790 | - /// flips), and some sit right at the greater1/greater2 escape boundary. | ||
| 1791 | - #[test] | ||
| 1792 | - fn sub_block_cursor_matches_full_recompute() { | ||
| 1793 | - for log2 in [3u32, 4, 5] { | ||
| 1794 | - let n = 1usize << log2; | ||
| 1795 | - for scan_idx in 0..3 { | ||
| 1796 | - for seed in 1..=8u32 { | ||
| 1797 | - let mut rng = Xorshift(seed.wrapping_mul(2654435761).max(1)); | ||
| 1798 | - let mut coeffs = vec![0i32; n * n]; | ||
| 1799 | - for c in coeffs.iter_mut() { | ||
| 1800 | - // Skewed toward small magnitudes (0..=3) so RDOQ_MAX_LEVEL's | ||
| 1801 | - // trial window and the greater1/greater2 boundary both fire | ||
| 1802 | - // often, with occasional larger outliers left untouched. | ||
| 1803 | - let r = rng.next(); | ||
| 1804 | - *c = match r % 5 { | ||
| 1805 | - 0 => 0, | ||
| 1806 | - 1 => (r >> 8) as i32 % 2 + 1, | ||
| 1807 | - 2 => -(((r >> 8) as i32 % 2) + 1), | ||
| 1808 | - 3 => (r >> 8) as i32 % 6 + 1, | ||
| 1809 | - _ => -(((r >> 8) as i32 % 6) + 1), | ||
| 1810 | - }; | ||
| 1811 | - } | ||
| 1812 | - let qp = 20 + (seed as i32 % 20); | ||
| 1813 | - | ||
| 1814 | - let mut levels_a = coeffs.clone(); | ||
| 1815 | - let mut enc_a = CabacEncoder::counter(Contexts::new(30)); | ||
| 1816 | - let count_a = rdoq( | ||
| 1817 | - &coeffs, | ||
| 1818 | - &mut levels_a, | ||
| 1819 | - n, | ||
| 1820 | - qp, | ||
| 1821 | - 8, | ||
| 1822 | - 0, | ||
| 1823 | - scan_idx, | ||
| 1824 | - ctx::CBF_LUMA, | ||
| 1825 | - 1.0, | ||
| 1826 | - None, | ||
| 1827 | - &mut enc_a, | ||
| 1828 | - ); | ||
| 1829 | - | ||
| 1830 | - let mut levels_b = coeffs.clone(); | ||
| 1831 | - let mut enc_b = CabacEncoder::counter(Contexts::new(30)); | ||
| 1832 | - let count_b = rdoq_full_recompute( | ||
| 1833 | - &coeffs, | ||
| 1834 | - &mut levels_b, | ||
| 1835 | - n, | ||
| 1836 | - qp, | ||
| 1837 | - 8, | ||
| 1838 | - 0, | ||
| 1839 | - scan_idx, | ||
| 1840 | - ctx::CBF_LUMA, | ||
| 1841 | - 1.0, | ||
| 1842 | - None, | ||
| 1843 | - &mut enc_b, | ||
| 1844 | - ); | ||
| 1845 | - | ||
| 1846 | - assert_eq!( | ||
| 1847 | - count_a, count_b, | ||
| 1848 | - "log2={log2} scan={scan_idx} seed={seed}: non-zero count differs" | ||
| 1849 | - ); | ||
| 1850 | - assert_eq!( | ||
| 1851 | - levels_a, levels_b, | ||
| 1852 | - "log2={log2} scan={scan_idx} seed={seed}: decided levels differ" | ||
| 1853 | - ); | ||
| 1854 | - | ||
| 1855 | - if count_a == 0 { | ||
| 1856 | - continue; | ||
| 1857 | - } | ||
| 1858 | - for sign_hiding in [false, true] { | ||
| 1859 | - let mut final_levels = levels_a.clone(); | ||
| 1860 | - if sign_hiding { | ||
| 1861 | - hide_signs(&coeffs, &mut final_levels, n, 30, scan_idx); | ||
| 1862 | - } | ||
| 1863 | - let mut fenc = CabacEncoder::counter(Contexts::new(30)); | ||
| 1864 | - encode_residual( | ||
| 1865 | - &mut fenc, | ||
| 1866 | - &final_levels, | ||
| 1867 | - log2, | ||
| 1868 | - 0, | ||
| 1869 | - scan_idx, | ||
| 1870 | - sign_hiding, | ||
| 1871 | - None, | ||
| 1872 | - ); | ||
| 1873 | - assert!(fenc.bit_count() > 0); | ||
| 1874 | - } | ||
| 1875 | - } | ||
| 1876 | - } | ||
| 1877 | - } | ||
| 1878 | - } | ||
| 1879 | } | 1621 | } |
crates/ec-h265/src/transform.rsmodified+0 -7
| @@ -686,13 +686,6 @@ pub fn dequantize_bd(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, bit_ | |||
| 686 | dequantize_weighted(levels, scaled, n, qp, bit_depth, None); | 686 | dequantize_weighted(levels, scaled, n, qp, bit_depth, None); |
| 687 | } | 687 | } |
| 688 | 688 | ||
| 689 | -/// [`dequantize`] with a scaling matrix (8.6.4.2): `m` is the block's | ||
| 690 | -/// `ScalingFactor` in raster order, or `None` for the flat 16 that a stream | ||
| 691 | -/// without scaling lists (or a transform-skipped block larger than 4x4) uses. | ||
| 692 | -pub fn dequantize_with(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, m: Option<&[u8]>) { | ||
| 693 | - dequantize_weighted(levels, scaled, n, qp, 8, m); | ||
| 694 | -} | ||
| 695 | - | ||
| 696 | /// The loop behind every dequantize entry point: one block at `bit_depth`, with | 689 | /// The loop behind every dequantize entry point: one block at `bit_depth`, with |
| 697 | /// the weight matrix `m` (or flat 16 for `None`). | 690 | /// the weight matrix `m` (or flat 16 for `None`). |
| 698 | pub fn dequantize_weighted( | 691 | pub fn dequantize_weighted( |
crates/ec-h265/tests/it/common.rsmodified+12 -3
| @@ -192,9 +192,18 @@ pub fn pin_or_panic(site: &str, path: &std::path::Path, bytes: &[u8]) { | |||
| 192 | 192 | ||
| 193 | pub const PLANE_NAMES: [&str; 3] = ["Y", "Cb", "Cr"]; | 193 | pub const PLANE_NAMES: [&str; 3] = ["Y", "Cb", "Cr"]; |
| 194 | 194 | ||
| 195 | +/// The bit depth of component `c` (0 luma, 1 and 2 chroma). | ||
| 196 | +pub fn bit_depth_of(pic: &DecodedPicture, c: usize) -> u32 { | ||
| 197 | + if c == 0 { | ||
| 198 | + pic.bit_depth | ||
| 199 | + } else { | ||
| 200 | + pic.bit_depth_c | ||
| 201 | + } | ||
| 202 | +} | ||
| 203 | + | ||
| 195 | /// Bytes per sample of component `c`: 1 for 8-bit, 2 (little endian) above 8 bits. | 204 | /// Bytes per sample of component `c`: 1 for 8-bit, 2 (little endian) above 8 bits. |
| 196 | pub fn bytes_per_sample(pic: &DecodedPicture, c: usize) -> usize { | 205 | pub fn bytes_per_sample(pic: &DecodedPicture, c: usize) -> usize { |
| 197 | - if pic.bit_depth_of(c) > 8 { 2 } else { 1 } | 206 | + if bit_depth_of(pic, c) > 8 { 2 } else { 1 } |
| 198 | } | 207 | } |
| 199 | 208 | ||
| 200 | /// The samples of a picture cropped to its conformance window, as the bytes a YUV | 209 | /// The samples of a picture cropped to its conformance window, as the bytes a YUV |
| @@ -424,7 +433,7 @@ pub fn plane_matches(pic: &DecodedPicture, expected: &PictureHash) -> Vec<bool> | |||
| 424 | .map(|(i, &w)| { | 433 | .map(|(i, &w)| { |
| 425 | planes | 434 | planes |
| 426 | .get(i) | 435 | .get(i) |
| 427 | - .is_some_and(|p| plane_crc(p, pic.bit_depth_of(i)) == w) | 436 | + .is_some_and(|p| plane_crc(p, bit_depth_of(pic, i)) == w) |
| 428 | }) | 437 | }) |
| 429 | .collect(), | 438 | .collect(), |
| 430 | PictureHash::Checksum(want) => want | 439 | PictureHash::Checksum(want) => want |
| @@ -433,7 +442,7 @@ pub fn plane_matches(pic: &DecodedPicture, expected: &PictureHash) -> Vec<bool> | |||
| 433 | .map(|(i, &w)| { | 442 | .map(|(i, &w)| { |
| 434 | planes | 443 | planes |
| 435 | .get(i) | 444 | .get(i) |
| 436 | - .is_some_and(|p| plane_checksum(p, dims[i].0, pic.bit_depth_of(i)) == w) | 445 | + .is_some_and(|p| plane_checksum(p, dims[i].0, bit_depth_of(pic, i)) == w) |
| 437 | }) | 446 | }) |
| 438 | .collect(), | 447 | .collect(), |
| 439 | } | 448 | } |
crates/ec-h265/tests/it/conformance.rsdeleted+0 -964
| @@ -1,964 +0,0 @@ | |||
| 1 | -//! Conformance: every access unit this encoder writes must decode in ffmpeg, | ||
| 2 | -//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own | ||
| 3 | -//! reconstruction. That equality is the whole point of coding with the in-loop | ||
| 4 | -//! filters off: it turns "the file plays" into "the decoder and the encoder | ||
| 5 | -//! agree on every sample". | ||
| 6 | - | ||
| 7 | -use crate::common::{natural_frame, pin_or_panic, test_frame}; | ||
| 8 | -use ec_core::frame::VideoFrame; | ||
| 9 | -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip}; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -fn scratch_dir() -> PathBuf { | ||
| 13 | - let dir = std::env::temp_dir().join("ec-h265-tests"); | ||
| 14 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 15 | - dir | ||
| 16 | -} | ||
| 17 | - | ||
| 18 | -/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. | ||
| 19 | -fn ffmpeg_decode(path: &Path) -> Result<Vec<u8>, String> { | ||
| 20 | - let out = path.with_extension("yuv"); | ||
| 21 | - let status = ec_testkit::ffmpeg() | ||
| 22 | - .args(["-v", "error", "-y", "-i"]) | ||
| 23 | - .arg(path) | ||
| 24 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 25 | - .arg(&out) | ||
| 26 | - .output() | ||
| 27 | - .map_err(|e| e.to_string())?; | ||
| 28 | - if !status.status.success() { | ||
| 29 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 30 | - } | ||
| 31 | - let stderr = String::from_utf8_lossy(&status.stderr).to_string(); | ||
| 32 | - if !stderr.trim().is_empty() { | ||
| 33 | - return Err(format!("ffmpeg complained: {stderr}")); | ||
| 34 | - } | ||
| 35 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -/// Pin one access unit as an Annex-B file for [`ffmpeg_decode`]. | ||
| 39 | -/// | ||
| 40 | -/// lane-h26xpinloud: this used `File::create(..).expect(..)` + | ||
| 41 | -/// `write_all(..).expect("write bitstream")`, which closes only the ERROR path. | ||
| 42 | -/// A write that reports success and leaves a short file put a truncated stream | ||
| 43 | -/// at exactly the path ffmpeg then decoded, so the shortfall now carries the | ||
| 44 | -/// path, both counts, and the OS error. Panic semantics kept: this caller | ||
| 45 | -/// panicked before and still does, with the failure line as the message. | ||
| 46 | -fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { | ||
| 47 | - let path = scratch_dir().join(format!("{name}.265")); | ||
| 48 | - pin_or_panic("write_au", &path, &picture.au); | ||
| 49 | - path | ||
| 50 | -} | ||
| 51 | - | ||
| 52 | -fn planes_of(frame: &VideoFrame) -> Vec<u8> { | ||
| 53 | - let mut out = Vec::new(); | ||
| 54 | - let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 55 | - for (i, plane) in frame.planes.iter().enumerate() { | ||
| 56 | - let (pw, ph) = if i == 0 { | ||
| 57 | - (w, h) | ||
| 58 | - } else { | ||
| 59 | - (w.div_ceil(2), h.div_ceil(2)) | ||
| 60 | - }; | ||
| 61 | - for row in 0..ph { | ||
| 62 | - out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | ||
| 63 | - } | ||
| 64 | - } | ||
| 65 | - out | ||
| 66 | -} | ||
| 67 | - | ||
| 68 | -fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 69 | - assert_eq!(a.len(), b.len()); | ||
| 70 | - let mse: f64 = a | ||
| 71 | - .iter() | ||
| 72 | - .zip(b) | ||
| 73 | - .map(|(x, y)| { | ||
| 74 | - let d = f64::from(*x) - f64::from(*y); | ||
| 75 | - d * d | ||
| 76 | - }) | ||
| 77 | - .sum::<f64>() | ||
| 78 | - / a.len() as f64; | ||
| 79 | - if mse == 0.0 { | ||
| 80 | - 99.0 | ||
| 81 | - } else { | ||
| 82 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 83 | - } | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -/// Encode one picture; `ctb` of `None` takes the configured default. | ||
| 87 | -fn encode(width: u32, height: u32, qp: i32, ctb: Option<usize>) -> (VideoFrame, EncodedPicture) { | ||
| 88 | - encode_with(width, height, qp, ctb, false, false) | ||
| 89 | -} | ||
| 90 | - | ||
| 91 | -fn encode_with( | ||
| 92 | - width: u32, | ||
| 93 | - height: u32, | ||
| 94 | - qp: i32, | ||
| 95 | - ctb: Option<usize>, | ||
| 96 | - chroma_mode_search: bool, | ||
| 97 | - intra_nxn: bool, | ||
| 98 | -) -> (VideoFrame, EncodedPicture) { | ||
| 99 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 100 | - cfg.chroma_mode_search = chroma_mode_search; | ||
| 101 | - cfg.intra_nxn = intra_nxn; | ||
| 102 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 103 | - if let Some(ctb) = ctb { | ||
| 104 | - cfg.ctb_size = ctb; | ||
| 105 | - } | ||
| 106 | - cfg.keep_recon = true; | ||
| 107 | - cfg.picture_hash = true; | ||
| 108 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 109 | - let frame = test_frame(width, height, 0); | ||
| 110 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 111 | - (frame, coded) | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -/// Same as `encode_with`, but on the grainy natural frame and with no chroma | ||
| 115 | -/// mode search — the synthetic test frame is flat enough that the quadtree | ||
| 116 | -/// never keeps an 8x8 coding unit, which is the only size PART_NxN applies to. | ||
| 117 | -fn encode_natural( | ||
| 118 | - width: u32, | ||
| 119 | - height: u32, | ||
| 120 | - qp: i32, | ||
| 121 | - intra_nxn: bool, | ||
| 122 | -) -> (VideoFrame, EncodedPicture) { | ||
| 123 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 124 | - cfg.intra_nxn = intra_nxn; | ||
| 125 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 126 | - cfg.keep_recon = true; | ||
| 127 | - cfg.picture_hash = true; | ||
| 128 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 129 | - let frame = natural_frame(width, height, 0); | ||
| 130 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 131 | - (frame, coded) | ||
| 132 | -} | ||
| 133 | - | ||
| 134 | -/// The chroma mode search is off by default (it loses on screen content, see | ||
| 135 | -/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an | ||
| 136 | -/// `intra_chroma_pred_mode` other than the derived one. This exercises the four | ||
| 137 | -/// explicit modes: the stream has to differ from the derived-only one — proving | ||
| 138 | -/// the search actually fired — and still decode bit-exactly. | ||
| 139 | -#[test] | ||
| 140 | -fn chroma_mode_search_decodes_bit_exactly() { | ||
| 141 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 142 | - let (source, coded) = encode_with(w, h, 27, None, true, false); | ||
| 143 | - let (_, derived) = encode_with(w, h, 27, None, false, false); | ||
| 144 | - let name = format!("chroma-rd-{w}x{h}"); | ||
| 145 | - assert_ne!( | ||
| 146 | - coded.au, derived.au, | ||
| 147 | - "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" | ||
| 148 | - ); | ||
| 149 | - let path = write_au(&name, &coded); | ||
| 150 | - let decoded = match ffmpeg_decode(&path) { | ||
| 151 | - Ok(bytes) => bytes, | ||
| 152 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 153 | - }; | ||
| 154 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 155 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 156 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 157 | - if mismatches != 0 { | ||
| 158 | - // Which plane and where: a luma-only divergence is the transform | ||
| 159 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 160 | - let luma = (w * h) as usize; | ||
| 161 | - let chroma = luma / 4; | ||
| 162 | - let first = decoded | ||
| 163 | - .iter() | ||
| 164 | - .zip(&recon) | ||
| 165 | - .position(|(a, b)| a != b) | ||
| 166 | - .unwrap(); | ||
| 167 | - let count = |range: std::ops::Range<usize>| { | ||
| 168 | - decoded[range.clone()] | ||
| 169 | - .iter() | ||
| 170 | - .zip(&recon[range]) | ||
| 171 | - .filter(|(a, b)| a != b) | ||
| 172 | - .count() | ||
| 173 | - }; | ||
| 174 | - let mut map = String::new(); | ||
| 175 | - for by in (0..h as usize).step_by(16) { | ||
| 176 | - for bx in (0..w as usize).step_by(16) { | ||
| 177 | - let mut c = 0; | ||
| 178 | - for row in by..by + 16 { | ||
| 179 | - for col in bx..bx + 16 { | ||
| 180 | - let i = row * w as usize + col; | ||
| 181 | - if decoded[i] != recon[i] { | ||
| 182 | - c += 1; | ||
| 183 | - } | ||
| 184 | - } | ||
| 185 | - } | ||
| 186 | - map.push_str(&format!("{c:4}")); | ||
| 187 | - } | ||
| 188 | - map.push('\n'); | ||
| 189 | - } | ||
| 190 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 191 | - panic!( | ||
| 192 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 193 | - ({}, {})", | ||
| 194 | - count(0..luma), | ||
| 195 | - count(luma..luma + chroma), | ||
| 196 | - count(luma + chroma..luma + 2 * chroma), | ||
| 197 | - first % w as usize, | ||
| 198 | - first / w as usize, | ||
| 199 | - ); | ||
| 200 | - } | ||
| 201 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 202 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 203 | - } | ||
| 204 | -} | ||
| 205 | - | ||
| 206 | -/// PART_NxN is off by default, so nothing else here codes a four-partition | ||
| 207 | -/// coding unit. This does: the stream has to differ from the 2Nx2N-only one — | ||
| 208 | -/// proving the partition actually fired — and still decode bit-exactly, which | ||
| 209 | -/// is the only check that the inferred transform split, the four `cbf_luma` | ||
| 210 | -/// flags at transform depth 1 and the chroma residual riding on the last | ||
| 211 | -/// partition are all where the decoder looks for them. | ||
| 212 | -#[test] | ||
| 213 | -fn intra_nxn_decodes_bit_exactly() { | ||
| 214 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 215 | - let (source, coded) = encode_natural(w, h, 22, true); | ||
| 216 | - let (_, square) = encode_natural(w, h, 22, false); | ||
| 217 | - let name = format!("intra-nxn-{w}x{h}"); | ||
| 218 | - assert_ne!( | ||
| 219 | - coded.au, square.au, | ||
| 220 | - "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" | ||
| 221 | - ); | ||
| 222 | - let path = write_au(&name, &coded); | ||
| 223 | - let decoded = match ffmpeg_decode(&path) { | ||
| 224 | - Ok(bytes) => bytes, | ||
| 225 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 226 | - }; | ||
| 227 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 228 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 229 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 230 | - if mismatches != 0 { | ||
| 231 | - // Which plane and where: a luma-only divergence is the transform | ||
| 232 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 233 | - let luma = (w * h) as usize; | ||
| 234 | - let chroma = luma / 4; | ||
| 235 | - let first = decoded | ||
| 236 | - .iter() | ||
| 237 | - .zip(&recon) | ||
| 238 | - .position(|(a, b)| a != b) | ||
| 239 | - .unwrap(); | ||
| 240 | - let count = |range: std::ops::Range<usize>| { | ||
| 241 | - decoded[range.clone()] | ||
| 242 | - .iter() | ||
| 243 | - .zip(&recon[range]) | ||
| 244 | - .filter(|(a, b)| a != b) | ||
| 245 | - .count() | ||
| 246 | - }; | ||
| 247 | - let mut map = String::new(); | ||
| 248 | - for by in (0..h as usize).step_by(16) { | ||
| 249 | - for bx in (0..w as usize).step_by(16) { | ||
| 250 | - let mut c = 0; | ||
| 251 | - for row in by..by + 16 { | ||
| 252 | - for col in bx..bx + 16 { | ||
| 253 | - let i = row * w as usize + col; | ||
| 254 | - if decoded[i] != recon[i] { | ||
| 255 | - c += 1; | ||
| 256 | - } | ||
| 257 | - } | ||
| 258 | - } | ||
| 259 | - map.push_str(&format!("{c:4}")); | ||
| 260 | - } | ||
| 261 | - map.push('\n'); | ||
| 262 | - } | ||
| 263 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 264 | - panic!( | ||
| 265 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 266 | - ({}, {})", | ||
| 267 | - count(0..luma), | ||
| 268 | - count(luma..luma + chroma), | ||
| 269 | - count(luma + chroma..luma + 2 * chroma), | ||
| 270 | - first % w as usize, | ||
| 271 | - first / w as usize, | ||
| 272 | - ); | ||
| 273 | - } | ||
| 274 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 275 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 276 | - } | ||
| 277 | -} | ||
| 278 | - | ||
| 279 | -/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for | ||
| 280 | -/// it by nudging a level, so the encoder and the decoder only agree if the | ||
| 281 | -/// parity the encoder wrote is the parity the decoder reads. The stream has to | ||
| 282 | -/// differ from the hiding-off one, and ffmpeg's decode has to match the | ||
| 283 | -/// encoder's reconstruction sample for sample. | ||
| 284 | -/// | ||
| 285 | -/// Size is deliberately not asserted here: hiding is not optional per | ||
| 286 | -/// sub-block, so a single small picture can come out a few bytes longer when | ||
| 287 | -/// the nudges cost more than the signs saved. Whether it pays is what the | ||
| 288 | -/// `EC_H265_SDH` arm of the clip gate measures. | ||
| 289 | -#[test] | ||
| 290 | -fn sign_hiding_decodes_bit_exactly() { | ||
| 291 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 292 | - let (source, coded) = encode_sdh(w, h, 22, true); | ||
| 293 | - let (_, plain) = encode_sdh(w, h, 22, false); | ||
| 294 | - let name = format!("sign-hiding-{w}x{h}"); | ||
| 295 | - assert_ne!( | ||
| 296 | - coded.au, plain.au, | ||
| 297 | - "{name}: no sub-block ever qualified, so this decode proves nothing" | ||
| 298 | - ); | ||
| 299 | - let path = write_au(&name, &coded); | ||
| 300 | - let decoded = match ffmpeg_decode(&path) { | ||
| 301 | - Ok(bytes) => bytes, | ||
| 302 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 303 | - }; | ||
| 304 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 305 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 306 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 307 | - if mismatches != 0 { | ||
| 308 | - // Which plane and where: a luma-only divergence is the transform | ||
| 309 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 310 | - let luma = (w * h) as usize; | ||
| 311 | - let chroma = luma / 4; | ||
| 312 | - let first = decoded | ||
| 313 | - .iter() | ||
| 314 | - .zip(&recon) | ||
| 315 | - .position(|(a, b)| a != b) | ||
| 316 | - .unwrap(); | ||
| 317 | - let count = |range: std::ops::Range<usize>| { | ||
| 318 | - decoded[range.clone()] | ||
| 319 | - .iter() | ||
| 320 | - .zip(&recon[range]) | ||
| 321 | - .filter(|(a, b)| a != b) | ||
| 322 | - .count() | ||
| 323 | - }; | ||
| 324 | - let mut map = String::new(); | ||
| 325 | - for by in (0..h as usize).step_by(16) { | ||
| 326 | - for bx in (0..w as usize).step_by(16) { | ||
| 327 | - let mut c = 0; | ||
| 328 | - for row in by..by + 16 { | ||
| 329 | - for col in bx..bx + 16 { | ||
| 330 | - let i = row * w as usize + col; | ||
| 331 | - if decoded[i] != recon[i] { | ||
| 332 | - c += 1; | ||
| 333 | - } | ||
| 334 | - } | ||
| 335 | - } | ||
| 336 | - map.push_str(&format!("{c:4}")); | ||
| 337 | - } | ||
| 338 | - map.push('\n'); | ||
| 339 | - } | ||
| 340 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 341 | - panic!( | ||
| 342 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 343 | - ({}, {})", | ||
| 344 | - count(0..luma), | ||
| 345 | - count(luma..luma + chroma), | ||
| 346 | - count(luma + chroma..luma + 2 * chroma), | ||
| 347 | - first % w as usize, | ||
| 348 | - first / w as usize, | ||
| 349 | - ); | ||
| 350 | - } | ||
| 351 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 352 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 353 | - } | ||
| 354 | -} | ||
| 355 | - | ||
| 356 | -/// The natural frame coded with sign data hiding on or off, everything else | ||
| 357 | -/// left at its default. | ||
| 358 | -fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { | ||
| 359 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 360 | - cfg.sign_hiding = sign_hiding; | ||
| 361 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 362 | - cfg.keep_recon = true; | ||
| 363 | - cfg.picture_hash = true; | ||
| 364 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 365 | - let frame = natural_frame(width, height, 0); | ||
| 366 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 367 | - (frame, coded) | ||
| 368 | -} | ||
| 369 | - | ||
| 370 | -/// The natural frame coded with transform skip on or off, everything else | ||
| 371 | -/// left at its default. | ||
| 372 | -fn encode_tskip( | ||
| 373 | - width: u32, | ||
| 374 | - height: u32, | ||
| 375 | - qp: i32, | ||
| 376 | - tskip: TransformSkip, | ||
| 377 | -) -> (VideoFrame, EncodedPicture) { | ||
| 378 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 379 | - cfg.transform_skip = tskip; | ||
| 380 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 381 | - cfg.keep_recon = true; | ||
| 382 | - cfg.picture_hash = true; | ||
| 383 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 384 | - let frame = natural_frame(width, height, 0); | ||
| 385 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 386 | - (frame, coded) | ||
| 387 | -} | ||
| 388 | - | ||
| 389 | -/// Transform skip bypasses the integer transform on 4x4 TUs, coding residual | ||
| 390 | -/// samples directly with a fixed shift. The encoder and decoder agree only if | ||
| 391 | -/// the shift matches on both sides; the stream has to differ from the | ||
| 392 | -/// skip-off one, and ffmpeg's decode has to match the encoder's reconstruction | ||
| 393 | -/// sample for sample. | ||
| 394 | -#[test] | ||
| 395 | -fn transform_skip_decodes_bit_exactly() { | ||
| 396 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 397 | - let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4); | ||
| 398 | - let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off); | ||
| 399 | - let name = format!("transform-skip-{w}x{h}"); | ||
| 400 | - assert_ne!( | ||
| 401 | - coded.au, plain.au, | ||
| 402 | - "{name}: no TU ever skipped, so this decode proves nothing" | ||
| 403 | - ); | ||
| 404 | - let path = write_au(&name, &coded); | ||
| 405 | - let decoded = match ffmpeg_decode(&path) { | ||
| 406 | - Ok(bytes) => bytes, | ||
| 407 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 408 | - }; | ||
| 409 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 410 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 411 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 412 | - if mismatches != 0 { | ||
| 413 | - // Which plane and where: a luma-only divergence is the transform | ||
| 414 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 415 | - let luma = (w * h) as usize; | ||
| 416 | - let chroma = luma / 4; | ||
| 417 | - let first = decoded | ||
| 418 | - .iter() | ||
| 419 | - .zip(&recon) | ||
| 420 | - .position(|(a, b)| a != b) | ||
| 421 | - .unwrap(); | ||
| 422 | - let count = |range: std::ops::Range<usize>| { | ||
| 423 | - decoded[range.clone()] | ||
| 424 | - .iter() | ||
| 425 | - .zip(&recon[range]) | ||
| 426 | - .filter(|(a, b)| a != b) | ||
| 427 | - .count() | ||
| 428 | - }; | ||
| 429 | - let mut map = String::new(); | ||
| 430 | - for by in (0..h as usize).step_by(16) { | ||
| 431 | - for bx in (0..w as usize).step_by(16) { | ||
| 432 | - let mut c = 0; | ||
| 433 | - for row in by..by + 16 { | ||
| 434 | - for col in bx..bx + 16 { | ||
| 435 | - let i = row * w as usize + col; | ||
| 436 | - if decoded[i] != recon[i] { | ||
| 437 | - c += 1; | ||
| 438 | - } | ||
| 439 | - } | ||
| 440 | - } | ||
| 441 | - map.push_str(&format!("{c:4}")); | ||
| 442 | - } | ||
| 443 | - map.push('\n'); | ||
| 444 | - } | ||
| 445 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 446 | - panic!( | ||
| 447 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 448 | - ({}, {})", | ||
| 449 | - count(0..luma), | ||
| 450 | - count(luma..luma + chroma), | ||
| 451 | - count(luma + chroma..luma + 2 * chroma), | ||
| 452 | - first % w as usize, | ||
| 453 | - first / w as usize, | ||
| 454 | - ); | ||
| 455 | - } | ||
| 456 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 457 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); | ||
| 458 | - } | ||
| 459 | -} | ||
| 460 | -#[test] | ||
| 461 | -fn ffmpeg_decodes_bit_exactly_at_every_shape() { | ||
| 462 | - // 1920x1080 needs the conformance window on the bottom (1088 coded rows are | ||
| 463 | - // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916 | ||
| 464 | - // needs it on the right, 130x66 exercises a partial CTB in both directions. | ||
| 465 | - // Both tree sizes are coded: the default is 32, and 64 is still offered. | ||
| 466 | - for &(w, h, ctb) in &[ | ||
| 467 | - (64u32, 64u32, None), | ||
| 468 | - (130, 66, None), | ||
| 469 | - (1916, 1080, None), | ||
| 470 | - (352, 288, None), | ||
| 471 | - (1916, 1080, Some(64)), | ||
| 472 | - (130, 66, Some(64)), | ||
| 473 | - ] { | ||
| 474 | - let (source, coded) = encode(w, h, 27, ctb); | ||
| 475 | - let name = format!( | ||
| 476 | - "shape-{w}x{h}-ctb{}", | ||
| 477 | - ctb.map_or("default".to_string(), |c| c.to_string()) | ||
| 478 | - ); | ||
| 479 | - let path = write_au(&name, &coded); | ||
| 480 | - let decoded = match ffmpeg_decode(&path) { | ||
| 481 | - Ok(bytes) => bytes, | ||
| 482 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 483 | - }; | ||
| 484 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 485 | - assert_eq!( | ||
| 486 | - decoded.len(), | ||
| 487 | - recon.len(), | ||
| 488 | - "{name}: decoded {} bytes, reconstruction {} bytes", | ||
| 489 | - decoded.len(), | ||
| 490 | - recon.len() | ||
| 491 | - ); | ||
| 492 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 493 | - if mismatches != 0 { | ||
| 494 | - // Which plane and where: a luma-only divergence is the transform | ||
| 495 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 496 | - let luma = (w * h) as usize; | ||
| 497 | - let chroma = luma / 4; | ||
| 498 | - let first = decoded | ||
| 499 | - .iter() | ||
| 500 | - .zip(&recon) | ||
| 501 | - .position(|(a, b)| a != b) | ||
| 502 | - .unwrap(); | ||
| 503 | - let count = |range: std::ops::Range<usize>| { | ||
| 504 | - decoded[range.clone()] | ||
| 505 | - .iter() | ||
| 506 | - .zip(&recon[range]) | ||
| 507 | - .filter(|(a, b)| a != b) | ||
| 508 | - .count() | ||
| 509 | - }; | ||
| 510 | - let mut map = String::new(); | ||
| 511 | - for by in (0..h as usize).step_by(16) { | ||
| 512 | - for bx in (0..w as usize).step_by(16) { | ||
| 513 | - let mut c = 0; | ||
| 514 | - for row in by..by + 16 { | ||
| 515 | - for col in bx..bx + 16 { | ||
| 516 | - let i = row * w as usize + col; | ||
| 517 | - if decoded[i] != recon[i] { | ||
| 518 | - c += 1; | ||
| 519 | - } | ||
| 520 | - } | ||
| 521 | - } | ||
| 522 | - map.push_str(&format!("{c:4}")); | ||
| 523 | - } | ||
| 524 | - map.push('\n'); | ||
| 525 | - } | ||
| 526 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 527 | - panic!( | ||
| 528 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 529 | - ({}, {})", | ||
| 530 | - count(0..luma), | ||
| 531 | - count(luma..luma + chroma), | ||
| 532 | - count(luma + chroma..luma + 2 * chroma), | ||
| 533 | - first % w as usize, | ||
| 534 | - first / w as usize, | ||
| 535 | - ); | ||
| 536 | - } | ||
| 537 | - // And the encode is worth something: PSNR against the source. | ||
| 538 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 539 | - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 540 | - } | ||
| 541 | -} | ||
| 542 | - | ||
| 543 | -/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one | ||
| 544 | -/// luma mode, with the transform split inferred rather than signalled | ||
| 545 | -/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a | ||
| 546 | -/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the | ||
| 547 | -/// stream has to differ from the same encode with `cu64` off, or the test would | ||
| 548 | -/// pass without a single 64x64 coding unit ever being kept. | ||
| 549 | -#[test] | ||
| 550 | -fn cu64_decodes_bit_exactly() { | ||
| 551 | - // 130x66 is here for the partial coding tree blocks, not for the decision: | ||
| 552 | - // at that size only two tree blocks are whole and the search keeps neither, | ||
| 553 | - // so its stream is allowed to come out identical. | ||
| 554 | - for &(w, h, qp, fires) in &[ | ||
| 555 | - (352u32, 288u32, 32i32, true), | ||
| 556 | - (256, 256, 37, true), | ||
| 557 | - (130, 66, 32, false), | ||
| 558 | - ] { | ||
| 559 | - let (source, off) = encode_cu64(w, h, qp, false); | ||
| 560 | - let (_, on) = encode_cu64(w, h, qp, true); | ||
| 561 | - let name = format!("cu64-{w}x{h}-qp{qp}"); | ||
| 562 | - if fires { | ||
| 563 | - assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); | ||
| 564 | - } | ||
| 565 | - | ||
| 566 | - let path = write_au(&name, &on); | ||
| 567 | - let decoded = match ffmpeg_decode(&path) { | ||
| 568 | - Ok(bytes) => bytes, | ||
| 569 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 570 | - }; | ||
| 571 | - let recon = planes_of(on.recon.as_ref().expect("recon kept")); | ||
| 572 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 573 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 574 | - if mismatches != 0 { | ||
| 575 | - let first = decoded | ||
| 576 | - .iter() | ||
| 577 | - .zip(&recon) | ||
| 578 | - .position(|(a, b)| a != b) | ||
| 579 | - .unwrap(); | ||
| 580 | - let luma = (w * h) as usize; | ||
| 581 | - panic!( | ||
| 582 | - "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", | ||
| 583 | - first % w as usize, | ||
| 584 | - first / w as usize, | ||
| 585 | - decoded[..luma] | ||
| 586 | - .iter() | ||
| 587 | - .zip(&recon[..luma]) | ||
| 588 | - .filter(|(a, b)| a != b) | ||
| 589 | - .count(), | ||
| 590 | - ); | ||
| 591 | - } | ||
| 592 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 593 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); | ||
| 594 | - } | ||
| 595 | -} | ||
| 596 | - | ||
| 597 | -fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { | ||
| 598 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 599 | - cfg.ctb_size = 64; | ||
| 600 | - cfg.cu64 = cu64; | ||
| 601 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 602 | - cfg.keep_recon = true; | ||
| 603 | - cfg.picture_hash = true; | ||
| 604 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 605 | - let frame = natural_frame(width, height, 0); | ||
| 606 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 607 | - (frame, coded) | ||
| 608 | -} | ||
| 609 | - | ||
| 610 | -/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower | ||
| 611 | -/// tree; that trade is only worth taking if the bits it costs are noise. | ||
| 612 | -#[test] | ||
| 613 | -fn the_default_tree_costs_almost_nothing_against_64() { | ||
| 614 | - let source = natural_frame(1920, 1080, 0); | ||
| 615 | - let mut coded = Vec::new(); | ||
| 616 | - for ctb in [32usize, 64] { | ||
| 617 | - let mut cfg = EncoderConfig::new(1920, 1080); | ||
| 618 | - cfg.rate_control = RateControl::ConstantQp(27); | ||
| 619 | - cfg.ctb_size = ctb; | ||
| 620 | - cfg.keep_recon = true; | ||
| 621 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 622 | - let picture = encoder.encode_idr(&source).expect("encode"); | ||
| 623 | - let quality = psnr( | ||
| 624 | - &planes_of(&source), | ||
| 625 | - &planes_of(picture.recon.as_ref().unwrap()), | ||
| 626 | - ); | ||
| 627 | - coded.push((picture.au.len(), quality)); | ||
| 628 | - } | ||
| 629 | - let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); | ||
| 630 | - println!( | ||
| 631 | - "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ | ||
| 632 | - ({:+.1}% bits, {:+.2} dB)", | ||
| 633 | - (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, | ||
| 634 | - psnr32 - psnr64 | ||
| 635 | - ); | ||
| 636 | - assert!( | ||
| 637 | - // Measured 1.0% on this fixture; the bound leaves room for the shape of | ||
| 638 | - // the picture, not for a change of coding behaviour. | ||
| 639 | - (bits32 as f64) < bits64 as f64 * 1.03, | ||
| 640 | - "CTB 32 spent {bits32} bytes against 64's {bits64}" | ||
| 641 | - ); | ||
| 642 | - assert!( | ||
| 643 | - (psnr32 - psnr64).abs() < 0.1, | ||
| 644 | - "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" | ||
| 645 | - ); | ||
| 646 | -} | ||
| 647 | - | ||
| 648 | -#[test] | ||
| 649 | -fn ffmpeg_verifies_the_decoded_picture_hash() { | ||
| 650 | - // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's | ||
| 651 | - // decoder checks that claim against what it decoded when asked to. This is | ||
| 652 | - // the one oracle that does not depend on this crate being right about | ||
| 653 | - // anything except the hash itself. | ||
| 654 | - let (_, coded) = encode(352, 288, 30, None); | ||
| 655 | - let path = write_au("hash-352x288", &coded); | ||
| 656 | - let output = ec_testkit::ffmpeg() | ||
| 657 | - .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) | ||
| 658 | - .arg(&path) | ||
| 659 | - .args(["-f", "null", "-"]) | ||
| 660 | - .output() | ||
| 661 | - .expect("run ffmpeg"); | ||
| 662 | - let log = String::from_utf8_lossy(&output.stderr).to_string(); | ||
| 663 | - let checks: Vec<&str> = log | ||
| 664 | - .lines() | ||
| 665 | - .filter(|line| line.contains("Verifying checksum")) | ||
| 666 | - .collect(); | ||
| 667 | - assert!(!checks.is_empty(), "ffmpeg checked no picture hash: {log}"); | ||
| 668 | - for line in checks { | ||
| 669 | - assert_eq!(line.matches("correct").count(), 3, "hash mismatch: {line}"); | ||
| 670 | - } | ||
| 671 | -} | ||
| 672 | - | ||
| 673 | -#[test] | ||
| 674 | -fn vaapi_hardware_decodes_the_stream() { | ||
| 675 | - // The other half of "it decodes": a GPU decoder is a different | ||
| 676 | - // implementation with different tolerances, and it is what edith's HEVC | ||
| 677 | - // path actually uses. Skipped where there is no render node. | ||
| 678 | - if !Path::new("/dev/dri/renderD128").exists() { | ||
| 679 | - eprintln!("skipping: no VA-API render node"); | ||
| 680 | - return; | ||
| 681 | - } | ||
| 682 | - let (_, coded) = encode(1920, 1080, 27, None); | ||
| 683 | - let path = write_au("vaapi-1080p", &coded); | ||
| 684 | - let output = ec_testkit::ffmpeg() | ||
| 685 | - .args([ | ||
| 686 | - "-v", | ||
| 687 | - "error", | ||
| 688 | - "-hwaccel", | ||
| 689 | - "vaapi", | ||
| 690 | - "-hwaccel_device", | ||
| 691 | - "/dev/dri/renderD128", | ||
| 692 | - "-i", | ||
| 693 | - ]) | ||
| 694 | - .arg(&path) | ||
| 695 | - .args(["-f", "null", "-"]) | ||
| 696 | - .output() | ||
| 697 | - .expect("run ffmpeg"); | ||
| 698 | - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); | ||
| 699 | - if stderr.contains("Failed to initialise VAAPI") | ||
| 700 | - || stderr.contains("No VA display found") | ||
| 701 | - || stderr.contains("Device creation failed") | ||
| 702 | - { | ||
| 703 | - eprintln!("skipping: VA-API unavailable here ({})", stderr.trim()); | ||
| 704 | - return; | ||
| 705 | - } | ||
| 706 | - assert!( | ||
| 707 | - output.status.success() && stderr.trim().is_empty(), | ||
| 708 | - "VA-API decode failed: {stderr}" | ||
| 709 | - ); | ||
| 710 | -} | ||
| 711 | - | ||
| 712 | -#[test] | ||
| 713 | -fn quality_rises_as_qp_falls() { | ||
| 714 | - let mut previous = 0.0; | ||
| 715 | - for &qp in &[40i32, 32, 27, 22] { | ||
| 716 | - let (source, coded) = encode(256, 144, qp, None); | ||
| 717 | - let recon = planes_of(coded.recon.as_ref().expect("recon")); | ||
| 718 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 719 | - assert!( | ||
| 720 | - quality > previous, | ||
| 721 | - "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" | ||
| 722 | - ); | ||
| 723 | - previous = quality; | ||
| 724 | - } | ||
| 725 | - assert!( | ||
| 726 | - previous > 40.0, | ||
| 727 | - "QP 22 should clear 40 dB, got {previous:.2}" | ||
| 728 | - ); | ||
| 729 | -} | ||
| 730 | - | ||
| 731 | -#[test] | ||
| 732 | -fn threads_do_not_change_the_bitstream() { | ||
| 733 | - let mut cfg = EncoderConfig::new(320, 192); | ||
| 734 | - cfg.rate_control = RateControl::ConstantQp(30); | ||
| 735 | - cfg.threads = 1; | ||
| 736 | - let single = Encoder::new(cfg.clone()).unwrap(); | ||
| 737 | - cfg.threads = 8; | ||
| 738 | - let many = Encoder::new(cfg).unwrap(); | ||
| 739 | - let frame = test_frame(320, 192, 3); | ||
| 740 | - let a = single.encode_idr(&frame).unwrap(); | ||
| 741 | - let b = many.encode_idr(&frame).unwrap(); | ||
| 742 | - assert_eq!(a.au, b.au, "wavefront changed the bitstream"); | ||
| 743 | -} | ||
| 744 | - | ||
| 745 | -#[test] | ||
| 746 | -fn a_bit_target_lands_near_its_target() { | ||
| 747 | - // The model picks a QP from bits-per-pixel; a picture that comes out more | ||
| 748 | - // than a quarter off is coded once more at a corrected QP. What is asserted | ||
| 749 | - // is the contract that mode offers — near the target, monotonic in it — not | ||
| 750 | - // a bitrate to the byte, which no single-picture encoder can promise. | ||
| 751 | - let mut previous = 0usize; | ||
| 752 | - for target in [400_000u64, 1_200_000, 3_000_000] { | ||
| 753 | - let mut cfg = EncoderConfig::new(640, 360); | ||
| 754 | - cfg.rate_control = RateControl::TargetBits(target); | ||
| 755 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 756 | - let frame = test_frame(640, 360, 5); | ||
| 757 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 758 | - let bits = coded.au.len() * 8; | ||
| 759 | - assert!( | ||
| 760 | - bits > previous, | ||
| 761 | - "target {target}: {bits} bits did not grow with the target" | ||
| 762 | - ); | ||
| 763 | - previous = bits; | ||
| 764 | - let ratio = bits as f64 / target as f64; | ||
| 765 | - assert!( | ||
| 766 | - (0.4..2.5).contains(&ratio), | ||
| 767 | - "target {target}: got {bits} bits (x{ratio:.2}) at QP {}", | ||
| 768 | - coded.qp | ||
| 769 | - ); | ||
| 770 | - } | ||
| 771 | -} | ||
| 772 | - | ||
| 773 | -#[test] | ||
| 774 | -fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { | ||
| 775 | - let cfg = EncoderConfig::new(128, 96); | ||
| 776 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 777 | - let frames: Vec<VideoFrame> = (0..3).map(|i| test_frame(128, 96, i * 11)).collect(); | ||
| 778 | - let coded = encoder.encode_batch(frames.iter()).expect("batch encode"); | ||
| 779 | - assert_eq!(coded.len(), 3); | ||
| 780 | - for picture in &coded { | ||
| 781 | - // Every access unit stands alone: parameter sets, then an IDR slice. | ||
| 782 | - let nals = ec_h265_syntax::split_annex_b(&picture.au); | ||
| 783 | - let types: Vec<_> = nals.iter().map(|n| n.header.nal_type).collect(); | ||
| 784 | - assert_eq!( | ||
| 785 | - &types[..4], | ||
| 786 | - &[ | ||
| 787 | - ec_h265_syntax::NalUnitType::Vps, | ||
| 788 | - ec_h265_syntax::NalUnitType::Sps, | ||
| 789 | - ec_h265_syntax::NalUnitType::Pps, | ||
| 790 | - ec_h265_syntax::NalUnitType::IdrWRadl, | ||
| 791 | - ], | ||
| 792 | - "access unit is not self-contained" | ||
| 793 | - ); | ||
| 794 | - } | ||
| 795 | - // Different pictures, different bitstreams. | ||
| 796 | - assert_ne!(coded[0].au, coded[1].au); | ||
| 797 | -} | ||
| 798 | - | ||
| 799 | -/// Rate-distortion quantisation changes which levels are coded, so the streams | ||
| 800 | -/// it produces are a different set of bins from the plain quantiser's; ffmpeg | ||
| 801 | -/// has to read them back to the same samples the encoder reconstructed. | ||
| 802 | -#[test] | ||
| 803 | -fn rdoq_decodes_bit_exactly() { | ||
| 804 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 805 | - let (source, coded) = encode_rdoq(w, h, 27, true); | ||
| 806 | - let (_, plain) = encode_rdoq(w, h, 27, false); | ||
| 807 | - let name = format!("rdoq-{w}x{h}"); | ||
| 808 | - assert_ne!( | ||
| 809 | - coded.au, plain.au, | ||
| 810 | - "{name}: the level search changed no byte, so it is not running" | ||
| 811 | - ); | ||
| 812 | - let path = write_au(&name, &coded); | ||
| 813 | - let decoded = match ffmpeg_decode(&path) { | ||
| 814 | - Ok(bytes) => bytes, | ||
| 815 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 816 | - }; | ||
| 817 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 818 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 819 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 820 | - if mismatches != 0 { | ||
| 821 | - // Which plane and where: a luma-only divergence is the transform | ||
| 822 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 823 | - let luma = (w * h) as usize; | ||
| 824 | - let chroma = luma / 4; | ||
| 825 | - let first = decoded | ||
| 826 | - .iter() | ||
| 827 | - .zip(&recon) | ||
| 828 | - .position(|(a, b)| a != b) | ||
| 829 | - .unwrap(); | ||
| 830 | - let count = |range: std::ops::Range<usize>| { | ||
| 831 | - decoded[range.clone()] | ||
| 832 | - .iter() | ||
| 833 | - .zip(&recon[range]) | ||
| 834 | - .filter(|(a, b)| a != b) | ||
| 835 | - .count() | ||
| 836 | - }; | ||
| 837 | - let mut map = String::new(); | ||
| 838 | - for by in (0..h as usize).step_by(16) { | ||
| 839 | - for bx in (0..w as usize).step_by(16) { | ||
| 840 | - let mut c = 0; | ||
| 841 | - for row in by..by + 16 { | ||
| 842 | - for col in bx..bx + 16 { | ||
| 843 | - let i = row * w as usize + col; | ||
| 844 | - if decoded[i] != recon[i] { | ||
| 845 | - c += 1; | ||
| 846 | - } | ||
| 847 | - } | ||
| 848 | - } | ||
| 849 | - map.push_str(&format!("{c:4}")); | ||
| 850 | - } | ||
| 851 | - map.push('\n'); | ||
| 852 | - } | ||
| 853 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 854 | - panic!( | ||
| 855 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 856 | - ({}, {})", | ||
| 857 | - count(0..luma), | ||
| 858 | - count(luma..luma + chroma), | ||
| 859 | - count(luma + chroma..luma + 2 * chroma), | ||
| 860 | - first % w as usize, | ||
| 861 | - first / w as usize, | ||
| 862 | - ); | ||
| 863 | - } | ||
| 864 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 865 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 866 | - } | ||
| 867 | -} | ||
| 868 | - | ||
| 869 | -/// The natural frame coded with the level search on or off, everything else | ||
| 870 | -/// left at its default. | ||
| 871 | -fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { | ||
| 872 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 873 | - cfg.rdoq = rdoq; | ||
| 874 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 875 | - cfg.keep_recon = true; | ||
| 876 | - cfg.picture_hash = true; | ||
| 877 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 878 | - let frame = natural_frame(width, height, 0); | ||
| 879 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 880 | - (frame, coded) | ||
| 881 | -} | ||
| 882 | - | ||
| 883 | -/// RQT must produce a bitstream a conformant decoder reads back to the exact | ||
| 884 | -/// samples the encoder reconstructed. | ||
| 885 | -#[test] | ||
| 886 | -fn rqt_decodes_bit_exactly() { | ||
| 887 | - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { | ||
| 888 | - let (source, coded) = encode_rqt(w, h, 27, true); | ||
| 889 | - let (_, plain) = encode_rqt(w, h, 27, false); | ||
| 890 | - let name = format!("rqt-{w}x{h}"); | ||
| 891 | - assert_ne!( | ||
| 892 | - coded.au, plain.au, | ||
| 893 | - "{name}: RQT changed no byte, so the split path is not running" | ||
| 894 | - ); | ||
| 895 | - let path = write_au(&name, &coded); | ||
| 896 | - let decoded = match ffmpeg_decode(&path) { | ||
| 897 | - Ok(bytes) => bytes, | ||
| 898 | - Err(e) => panic!("{name}: ffmpeg failed: {e}"), | ||
| 899 | - }; | ||
| 900 | - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); | ||
| 901 | - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); | ||
| 902 | - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); | ||
| 903 | - if mismatches != 0 { | ||
| 904 | - // Which plane and where: a luma-only divergence is the transform | ||
| 905 | - // tree, a chroma-only one is the flags that ride on it. | ||
| 906 | - let luma = (w * h) as usize; | ||
| 907 | - let chroma = luma / 4; | ||
| 908 | - let first = decoded | ||
| 909 | - .iter() | ||
| 910 | - .zip(&recon) | ||
| 911 | - .position(|(a, b)| a != b) | ||
| 912 | - .unwrap(); | ||
| 913 | - let count = |range: std::ops::Range<usize>| { | ||
| 914 | - decoded[range.clone()] | ||
| 915 | - .iter() | ||
| 916 | - .zip(&recon[range]) | ||
| 917 | - .filter(|(a, b)| a != b) | ||
| 918 | - .count() | ||
| 919 | - }; | ||
| 920 | - let mut map = String::new(); | ||
| 921 | - for by in (0..h as usize).step_by(16) { | ||
| 922 | - for bx in (0..w as usize).step_by(16) { | ||
| 923 | - let mut c = 0; | ||
| 924 | - for row in by..by + 16 { | ||
| 925 | - for col in bx..bx + 16 { | ||
| 926 | - let i = row * w as usize + col; | ||
| 927 | - if decoded[i] != recon[i] { | ||
| 928 | - c += 1; | ||
| 929 | - } | ||
| 930 | - } | ||
| 931 | - } | ||
| 932 | - map.push_str(&format!("{c:4}")); | ||
| 933 | - } | ||
| 934 | - map.push('\n'); | ||
| 935 | - } | ||
| 936 | - eprintln!("luma 16x16 mismatch map:\n{map}"); | ||
| 937 | - panic!( | ||
| 938 | - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ | ||
| 939 | - ({}, {})", | ||
| 940 | - count(0..luma), | ||
| 941 | - count(luma..luma + chroma), | ||
| 942 | - count(luma + chroma..luma + 2 * chroma), | ||
| 943 | - first % w as usize, | ||
| 944 | - first / w as usize, | ||
| 945 | - ); | ||
| 946 | - } | ||
| 947 | - let quality = psnr(&planes_of(&source), &recon); | ||
| 948 | - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); | ||
| 949 | - } | ||
| 950 | -} | ||
| 951 | - | ||
| 952 | -/// The natural frame coded with RQT on or off, everything else left at its | ||
| 953 | -/// default. | ||
| 954 | -fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { | ||
| 955 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 956 | - cfg.rqt = rqt; | ||
| 957 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 958 | - cfg.keep_recon = true; | ||
| 959 | - cfg.picture_hash = true; | ||
| 960 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 961 | - let frame = natural_frame(width, height, 0); | ||
| 962 | - let coded = encoder.encode_idr(&frame).expect("encode"); | ||
| 963 | - (frame, coded) | ||
| 964 | -} | ||
crates/ec-h265/tests/it/conformance_intra.rsdeleted+0 -276
| @@ -1,276 +0,0 @@ | |||
| 1 | -//! Checks every output picture of each JCT-VC conformance stream against the | ||
| 2 | -//! MD5 in its decoded picture hash SEI (D.3.19). | ||
| 3 | -//! | ||
| 4 | -//! Streams the decoder refuses are reported with the error text. Mismatches are | ||
| 5 | -//! reported, never asserted. The digest is computed with the SEI writer of | ||
| 6 | -//! `ec-h265-syntax`, which is the same MD5 the hash message carries. | ||
| 7 | - | ||
| 8 | -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; | ||
| 9 | -use std::panic::{self, AssertUnwindSafe}; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -use ec_h265::dec::Decoder; | ||
| 13 | - | ||
| 14 | -/// The outcome of one stream, one row of the report. | ||
| 15 | -struct Row { | ||
| 16 | - name: String, | ||
| 17 | - accepted: &'static str, | ||
| 18 | - checked: usize, | ||
| 19 | - exact: usize, | ||
| 20 | - detail: String, | ||
| 21 | - /// Whether any picture was checked against the reference YUV (no hash SEI). | ||
| 22 | - by_reference: bool, | ||
| 23 | - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). | ||
| 24 | - decode_secs: f64, | ||
| 25 | -} | ||
| 26 | - | ||
| 27 | -fn jctvc_root() -> PathBuf { | ||
| 28 | - ec_testkit::fixture("vectors/hevc-jctvc") | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 32 | -/// directory under the root, sorted by name. Some zips extract one directory | ||
| 33 | -/// deeper, so two levels are searched. | ||
| 34 | -fn streams() -> Vec<PathBuf> { | ||
| 35 | - let root = jctvc_root(); | ||
| 36 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 37 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 38 | - return; | ||
| 39 | - }; | ||
| 40 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 41 | - paths.sort(); | ||
| 42 | - for p in paths { | ||
| 43 | - if p.is_dir() && depth > 0 { | ||
| 44 | - bitstreams_in(&p, depth - 1, out); | ||
| 45 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 46 | - out.push(p); | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - } | ||
| 50 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 51 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 52 | - dirs.sort(); | ||
| 53 | - dirs.into_iter() | ||
| 54 | - .filter(|d| d.is_dir()) | ||
| 55 | - .filter_map(|d| { | ||
| 56 | - let mut found = Vec::new(); | ||
| 57 | - bitstreams_in(&d, 2, &mut found); | ||
| 58 | - found.into_iter().next() | ||
| 59 | - }) | ||
| 60 | - .collect() | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -/// Decodes one stream and checks every output picture against its MD5 SEI. | ||
| 64 | -fn check_stream(path: &Path, name: &str) -> Row { | ||
| 65 | - let mut row = Row { | ||
| 66 | - name: name.to_string(), | ||
| 67 | - accepted: "no", | ||
| 68 | - checked: 0, | ||
| 69 | - exact: 0, | ||
| 70 | - detail: String::new(), | ||
| 71 | - by_reference: false, | ||
| 72 | - decode_secs: 0.0, | ||
| 73 | - }; | ||
| 74 | - let data = match std::fs::read(path) { | ||
| 75 | - Ok(d) => d, | ||
| 76 | - Err(e) => { | ||
| 77 | - row.detail = format!("read error: {e}"); | ||
| 78 | - return row; | ||
| 79 | - } | ||
| 80 | - }; | ||
| 81 | - let reference = std::fs::read(path.with_extension("yuv")).ok(); | ||
| 82 | - // A `<name>_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It | ||
| 83 | - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a | ||
| 84 | - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). | ||
| 85 | - let whole_output = std::fs::read_to_string(path.with_file_name(format!("{name}_md5.txt"))) | ||
| 86 | - .ok() | ||
| 87 | - .and_then(|text| whole_output_digest(&text)); | ||
| 88 | - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); | ||
| 89 | - let mut whole_output_checked = 0usize; | ||
| 90 | - | ||
| 91 | - let started = std::time::Instant::now(); | ||
| 92 | - let mut dec = Decoder::new(); | ||
| 93 | - if let Err(e) = dec.decode_annex_b(&data) { | ||
| 94 | - row.detail = format!("error: {e}"); | ||
| 95 | - return row; | ||
| 96 | - } | ||
| 97 | - if let Err(e) = dec.flush() { | ||
| 98 | - row.detail = format!("error: {e}"); | ||
| 99 | - return row; | ||
| 100 | - } | ||
| 101 | - row.accepted = "yes"; | ||
| 102 | - | ||
| 103 | - let mut out_index = 0usize; | ||
| 104 | - let mut first: Option<String> = None; | ||
| 105 | - while let Some(frame) = dec.next_frame() { | ||
| 106 | - let index = out_index; | ||
| 107 | - out_index += 1; | ||
| 108 | - let Some(expected) = frame.meta.picture_hash.as_ref() else { | ||
| 109 | - if whole_output.is_some() { | ||
| 110 | - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); | ||
| 111 | - whole_output_checked += 1; | ||
| 112 | - continue; | ||
| 113 | - } | ||
| 114 | - // No hash SEI: the frame is checked against the reference YUV, when there is one. | ||
| 115 | - if let Some(reference) = reference.as_deref() { | ||
| 116 | - let want = cropped_bytes(&frame.picture, &frame.window); | ||
| 117 | - let start = index * want.len(); | ||
| 118 | - row.checked += 1; | ||
| 119 | - if reference.get(start..start + want.len()) == Some(&want[..]) { | ||
| 120 | - row.exact += 1; | ||
| 121 | - } else if first.is_none() { | ||
| 122 | - let at = (0..3) | ||
| 123 | - .find_map(|plane| { | ||
| 124 | - let d = | ||
| 125 | - describe(Some(reference), index, &frame.picture, frame.poc, plane); | ||
| 126 | - (!d.contains("no sample differs")).then_some(d) | ||
| 127 | - }) | ||
| 128 | - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); | ||
| 129 | - first = Some(format!("{at} (reference YUV, cropped)")); | ||
| 130 | - } | ||
| 131 | - row.by_reference = true; | ||
| 132 | - } | ||
| 133 | - continue; | ||
| 134 | - }; | ||
| 135 | - row.checked += 1; | ||
| 136 | - let pic = &*frame.picture; | ||
| 137 | - let mut exact = true; | ||
| 138 | - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { | ||
| 139 | - if ok { | ||
| 140 | - continue; | ||
| 141 | - } | ||
| 142 | - exact = false; | ||
| 143 | - if first.is_none() { | ||
| 144 | - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; | ||
| 145 | - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); | ||
| 146 | - first = Some(format!("{at} slices={kind}")); | ||
| 147 | - } | ||
| 148 | - } | ||
| 149 | - if exact { | ||
| 150 | - row.exact += 1; | ||
| 151 | - } | ||
| 152 | - } | ||
| 153 | - row.decode_secs = started.elapsed().as_secs_f64(); | ||
| 154 | - if let Some(want) = whole_output { | ||
| 155 | - let got = whole_output_md5.finish(); | ||
| 156 | - row.checked += whole_output_checked; | ||
| 157 | - if got == want { | ||
| 158 | - row.exact += whole_output_checked; | ||
| 159 | - } else { | ||
| 160 | - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); | ||
| 161 | - first.get_or_insert(format!( | ||
| 162 | - "whole-output MD5 {hex} differs from {name}_md5.txt" | ||
| 163 | - )); | ||
| 164 | - } | ||
| 165 | - row.by_reference = true; | ||
| 166 | - } | ||
| 167 | - row.detail = match (first, row.checked) { | ||
| 168 | - (Some(f), _) => format!("first mismatch {f}"), | ||
| 169 | - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), | ||
| 170 | - (None, _) if whole_output.is_some() => { | ||
| 171 | - "ok (whole-output MD5 from the conformance package)".to_string() | ||
| 172 | - } | ||
| 173 | - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), | ||
| 174 | - (None, _) => "ok".to_string(), | ||
| 175 | - }; | ||
| 176 | - row | ||
| 177 | -} | ||
| 178 | - | ||
| 179 | -#[test] | ||
| 180 | -fn conformance_pictures_match_the_sei_hash() { | ||
| 181 | - let root = jctvc_root(); | ||
| 182 | - let streams = streams(); | ||
| 183 | - assert!( | ||
| 184 | - !streams.is_empty(), | ||
| 185 | - "no conformance streams under {}", | ||
| 186 | - root.display() | ||
| 187 | - ); | ||
| 188 | - | ||
| 189 | - let mut rows = Vec::new(); | ||
| 190 | - for path in &streams { | ||
| 191 | - let name = path | ||
| 192 | - .file_stem() | ||
| 193 | - .map(|s| s.to_string_lossy().into_owned()) | ||
| 194 | - .unwrap_or_default(); | ||
| 195 | - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); | ||
| 196 | - let mut row = match outcome { | ||
| 197 | - Ok(row) => row, | ||
| 198 | - Err(payload) => { | ||
| 199 | - let msg = payload | ||
| 200 | - .downcast_ref::<&str>() | ||
| 201 | - .map(|s| s.to_string()) | ||
| 202 | - .or_else(|| payload.downcast_ref::<String>().cloned()) | ||
| 203 | - .unwrap_or_default(); | ||
| 204 | - Row { | ||
| 205 | - name: name.clone(), | ||
| 206 | - accepted: "panic", | ||
| 207 | - checked: 0, | ||
| 208 | - exact: 0, | ||
| 209 | - detail: format!("panic: {msg}"), | ||
| 210 | - by_reference: false, | ||
| 211 | - decode_secs: 0.0, | ||
| 212 | - } | ||
| 213 | - } | ||
| 214 | - }; | ||
| 215 | - row.detail = row.detail.replace(['\t', '\n'], " "); | ||
| 216 | - rows.push(row); | ||
| 217 | - } | ||
| 218 | - | ||
| 219 | - let mut table = | ||
| 220 | - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); | ||
| 221 | - for r in &rows { | ||
| 222 | - println!( | ||
| 223 | - "{} | {} | {} | {} | {} | {:.2}s", | ||
| 224 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 225 | - ); | ||
| 226 | - table.push_str(&format!( | ||
| 227 | - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", | ||
| 228 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 229 | - )); | ||
| 230 | - } | ||
| 231 | - let checked: usize = rows.iter().map(|r| r.checked).sum(); | ||
| 232 | - let exact: usize = rows.iter().map(|r| r.exact).sum(); | ||
| 233 | - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); | ||
| 234 | - println!( | ||
| 235 | - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", | ||
| 236 | - rows.len() | ||
| 237 | - ); | ||
| 238 | - let report = std::env::var("EC_H265_INTRA_REPORT") | ||
| 239 | - .ok() | ||
| 240 | - .filter(|p| !p.is_empty()); | ||
| 241 | - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); | ||
| 242 | - if let Some(Err((path, e))) = written { | ||
| 243 | - eprintln!("could not write report {path}: {e}"); | ||
| 244 | - } | ||
| 245 | - | ||
| 246 | - // Every accepted stream must be fully exact, except the streams named in KNOWN_INEXACT. | ||
| 247 | - let failing: Vec<String> = rows | ||
| 248 | - .iter() | ||
| 249 | - .filter(|r| r.accepted == "yes" && r.checked > 0 && r.exact != r.checked) | ||
| 250 | - .filter(|r| !KNOWN_INEXACT.iter().any(|(name, _)| *name == r.name)) | ||
| 251 | - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) | ||
| 252 | - .collect(); | ||
| 253 | - assert!( | ||
| 254 | - failing.is_empty(), | ||
| 255 | - "accepted streams that are not exact and not in KNOWN_INEXACT:\n{}", | ||
| 256 | - failing.join("\n") | ||
| 257 | - ); | ||
| 258 | -} | ||
| 259 | - | ||
| 260 | -#[test] | ||
| 261 | -fn whole_output_digest_reads_the_first_word() { | ||
| 262 | - let digest = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea").unwrap(); | ||
| 263 | - assert_eq!(digest[0], 0x1d); | ||
| 264 | - assert_eq!(digest[15], 0xea); | ||
| 265 | - let with_name = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea out.yuv\n"); | ||
| 266 | - assert_eq!(with_name, Some(digest)); | ||
| 267 | - assert_eq!(whole_output_digest("1ddf7426"), None); | ||
| 268 | - assert_eq!( | ||
| 269 | - whole_output_digest("zzdf74263cb4953cfdfcf99c563d88ea"), | ||
| 270 | - None | ||
| 271 | - ); | ||
| 272 | -} | ||
| 273 | - | ||
| 274 | -/// Accepted streams that are knowingly not fully exact, each with the reason. Remove an entry | ||
| 275 | -/// once the stream is exact. Nothing else may be listed. | ||
| 276 | -const KNOWN_INEXACT: &[(&str, &str)] = &[]; | ||
crates/ec-h265/tests/it/conformance_rext.rsdeleted+0 -325
| @@ -1,325 +0,0 @@ | |||
| 1 | -//! Checks every output picture of each JCT-VC range extension conformance stream | ||
| 2 | -//! (D.3.19), or against the whole-output MD5 of the package when the stream has no hash. | ||
| 3 | -//! | ||
| 4 | -//! A stream the decoder refuses must be refused by name: the error text has to be one of | ||
| 5 | -//! `REFUSED`. Every other stream has to decode exactly, picture for picture. | ||
| 6 | - | ||
| 7 | -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; | ||
| 8 | -use std::panic::{self, AssertUnwindSafe}; | ||
| 9 | -use std::path::{Path, PathBuf}; | ||
| 10 | - | ||
| 11 | -use ec_h265::dec::Decoder; | ||
| 12 | - | ||
| 13 | -/// The outcome of one stream, one row of the report. | ||
| 14 | -struct Row { | ||
| 15 | - name: String, | ||
| 16 | - accepted: &'static str, | ||
| 17 | - checked: usize, | ||
| 18 | - exact: usize, | ||
| 19 | - detail: String, | ||
| 20 | - /// Whether any picture was checked against the reference YUV (no hash SEI). | ||
| 21 | - by_reference: bool, | ||
| 22 | - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). | ||
| 23 | - decode_secs: f64, | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -fn jctvc_root() -> PathBuf { | ||
| 27 | - ec_testkit::fixture("vectors/hevc-rext") | ||
| 28 | -} | ||
| 29 | - | ||
| 30 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 31 | -/// directory under the root, sorted by name. Some zips extract one directory | ||
| 32 | -/// deeper, so two levels are searched. | ||
| 33 | -fn streams() -> Vec<PathBuf> { | ||
| 34 | - let root = jctvc_root(); | ||
| 35 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 36 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 37 | - return; | ||
| 38 | - }; | ||
| 39 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 40 | - paths.sort(); | ||
| 41 | - for p in paths { | ||
| 42 | - if p.is_dir() && depth > 0 { | ||
| 43 | - bitstreams_in(&p, depth - 1, out); | ||
| 44 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 45 | - out.push(p); | ||
| 46 | - } | ||
| 47 | - } | ||
| 48 | - } | ||
| 49 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 50 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 51 | - dirs.sort(); | ||
| 52 | - dirs.into_iter() | ||
| 53 | - .filter(|d| d.is_dir()) | ||
| 54 | - .filter(|d| { | ||
| 55 | - std::env::var("EC_H265_REXT_ONLY") | ||
| 56 | - .map_or(true, |only| d.to_string_lossy().contains(&only)) | ||
| 57 | - }) | ||
| 58 | - .filter_map(|d| { | ||
| 59 | - let mut found = Vec::new(); | ||
| 60 | - bitstreams_in(&d, 2, &mut found); | ||
| 61 | - found.into_iter().next() | ||
| 62 | - }) | ||
| 63 | - .collect() | ||
| 64 | -} | ||
| 65 | - | ||
| 66 | -/// Every 32-digit hex word of the MD5 files beside the bitstream (`*md5*`): one of them is the | ||
| 67 | -/// MD5 of the whole decoded output, the others are the bitstream's own. | ||
| 68 | -fn candidate_digests(path: &Path) -> Vec<[u8; 16]> { | ||
| 69 | - let mut out = Vec::new(); | ||
| 70 | - let Some(dir) = path.parent() else { | ||
| 71 | - return out; | ||
| 72 | - }; | ||
| 73 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 74 | - return out; | ||
| 75 | - }; | ||
| 76 | - for e in entries.flatten() { | ||
| 77 | - let name = e.file_name().to_string_lossy().to_lowercase(); | ||
| 78 | - if !name.contains("md5") { | ||
| 79 | - continue; | ||
| 80 | - } | ||
| 81 | - if let Ok(text) = std::fs::read_to_string(e.path()) { | ||
| 82 | - for word in text.split_whitespace() { | ||
| 83 | - if let Some(d) = whole_output_digest(word) { | ||
| 84 | - out.push(d); | ||
| 85 | - } | ||
| 86 | - } | ||
| 87 | - } | ||
| 88 | - } | ||
| 89 | - out | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -/// The stream cut at its start codes: each chunk is one NAL unit with its start code. | ||
| 93 | -fn nal_chunks(data: &[u8]) -> Vec<&[u8]> { | ||
| 94 | - let mut starts: Vec<usize> = (0..data.len().saturating_sub(2)) | ||
| 95 | - .filter(|&i| data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) | ||
| 96 | - .collect(); | ||
| 97 | - starts.push(data.len()); | ||
| 98 | - starts.windows(2).map(|w| &data[w[0]..w[1]]).collect() | ||
| 99 | -} | ||
| 100 | - | ||
| 101 | -/// Decodes one stream and checks every output picture against its MD5 SEI. | ||
| 102 | -fn check_stream(path: &Path, name: &str) -> Row { | ||
| 103 | - let mut row = Row { | ||
| 104 | - name: name.to_string(), | ||
| 105 | - accepted: "no", | ||
| 106 | - checked: 0, | ||
| 107 | - exact: 0, | ||
| 108 | - detail: String::new(), | ||
| 109 | - by_reference: false, | ||
| 110 | - decode_secs: 0.0, | ||
| 111 | - }; | ||
| 112 | - let data = match std::fs::read(path) { | ||
| 113 | - Ok(d) => d, | ||
| 114 | - Err(e) => { | ||
| 115 | - row.detail = format!("read error: {e}"); | ||
| 116 | - return row; | ||
| 117 | - } | ||
| 118 | - }; | ||
| 119 | - let reference = std::fs::read(path.with_extension("yuv")).ok(); | ||
| 120 | - // A `<name>_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It | ||
| 121 | - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a | ||
| 122 | - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). | ||
| 123 | - let whole_output = Some(candidate_digests(path)).filter(|d| !d.is_empty()); | ||
| 124 | - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); | ||
| 125 | - let mut whole_output_checked = 0usize; | ||
| 126 | - | ||
| 127 | - let started = std::time::Instant::now(); | ||
| 128 | - let mut dec = Decoder::new(); | ||
| 129 | - let mut out_index = 0usize; | ||
| 130 | - let mut first: Option<String> = None; | ||
| 131 | - let mut handle = |frame: ec_h265::dec::Frame| { | ||
| 132 | - let index = out_index; | ||
| 133 | - out_index += 1; | ||
| 134 | - if whole_output.is_some() { | ||
| 135 | - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); | ||
| 136 | - } | ||
| 137 | - let Some(expected) = frame.meta.picture_hash.as_ref() else { | ||
| 138 | - if whole_output.is_some() { | ||
| 139 | - whole_output_checked += 1; | ||
| 140 | - return; | ||
| 141 | - } | ||
| 142 | - // No hash SEI: the frame is checked against the reference YUV, when there is one. | ||
| 143 | - if let Some(reference) = reference.as_deref() { | ||
| 144 | - let want = cropped_bytes(&frame.picture, &frame.window); | ||
| 145 | - let start = index * want.len(); | ||
| 146 | - row.checked += 1; | ||
| 147 | - if reference.get(start..start + want.len()) == Some(&want[..]) { | ||
| 148 | - row.exact += 1; | ||
| 149 | - } else if first.is_none() { | ||
| 150 | - let at = (0..3) | ||
| 151 | - .find_map(|plane| { | ||
| 152 | - let d = | ||
| 153 | - describe(Some(reference), index, &frame.picture, frame.poc, plane); | ||
| 154 | - (!d.contains("no sample differs")).then_some(d) | ||
| 155 | - }) | ||
| 156 | - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); | ||
| 157 | - first = Some(format!("{at} (reference YUV, cropped)")); | ||
| 158 | - } | ||
| 159 | - row.by_reference = true; | ||
| 160 | - } | ||
| 161 | - return; | ||
| 162 | - }; | ||
| 163 | - row.checked += 1; | ||
| 164 | - let pic = &*frame.picture; | ||
| 165 | - let mut exact = true; | ||
| 166 | - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { | ||
| 167 | - if ok { | ||
| 168 | - continue; | ||
| 169 | - } | ||
| 170 | - exact = false; | ||
| 171 | - if first.is_none() { | ||
| 172 | - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; | ||
| 173 | - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); | ||
| 174 | - first = Some(format!("{at} slices={kind}")); | ||
| 175 | - } | ||
| 176 | - } | ||
| 177 | - if exact { | ||
| 178 | - row.exact += 1; | ||
| 179 | - } | ||
| 180 | - }; | ||
| 181 | - // Frames are drained after every NAL unit, so the output of a long stream is not held. | ||
| 182 | - for unit in nal_chunks(&data) { | ||
| 183 | - if let Err(e) = dec.decode_annex_b(unit) { | ||
| 184 | - row.detail = format!("error: {e}"); | ||
| 185 | - return row; | ||
| 186 | - } | ||
| 187 | - while let Some(frame) = dec.next_frame() { | ||
| 188 | - handle(frame); | ||
| 189 | - } | ||
| 190 | - } | ||
| 191 | - if let Err(e) = dec.flush() { | ||
| 192 | - row.detail = format!("error: {e}"); | ||
| 193 | - return row; | ||
| 194 | - } | ||
| 195 | - row.accepted = "yes"; | ||
| 196 | - while let Some(frame) = dec.next_frame() { | ||
| 197 | - handle(frame); | ||
| 198 | - } | ||
| 199 | - row.decode_secs = started.elapsed().as_secs_f64(); | ||
| 200 | - if let Some(want) = whole_output.as_ref().filter(|_| whole_output_checked > 0) { | ||
| 201 | - let got = whole_output_md5.finish(); | ||
| 202 | - row.checked += whole_output_checked; | ||
| 203 | - if want.contains(&got) { | ||
| 204 | - row.exact += whole_output_checked; | ||
| 205 | - } else { | ||
| 206 | - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); | ||
| 207 | - first.get_or_insert(format!( | ||
| 208 | - "whole-output MD5 {hex} differs from {name}_md5.txt" | ||
| 209 | - )); | ||
| 210 | - } | ||
| 211 | - row.by_reference = true; | ||
| 212 | - } | ||
| 213 | - row.detail = match (first, row.checked) { | ||
| 214 | - (Some(f), _) => format!("first mismatch {f}"), | ||
| 215 | - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), | ||
| 216 | - (None, _) if whole_output.is_some() && whole_output_checked > 0 => { | ||
| 217 | - "ok (whole-output MD5 from the conformance package)".to_string() | ||
| 218 | - } | ||
| 219 | - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), | ||
| 220 | - (None, _) => "ok".to_string(), | ||
| 221 | - }; | ||
| 222 | - row | ||
| 223 | -} | ||
| 224 | - | ||
| 225 | -#[test] | ||
| 226 | -fn rext_conformance_pictures_match_the_sei_hash() { | ||
| 227 | - let root = jctvc_root(); | ||
| 228 | - let streams = streams(); | ||
| 229 | - assert!( | ||
| 230 | - !streams.is_empty(), | ||
| 231 | - "no conformance streams under {}", | ||
| 232 | - root.display() | ||
| 233 | - ); | ||
| 234 | - | ||
| 235 | - let mut rows = Vec::new(); | ||
| 236 | - for path in &streams { | ||
| 237 | - let name = path | ||
| 238 | - .file_stem() | ||
| 239 | - .map(|s| s.to_string_lossy().into_owned()) | ||
| 240 | - .unwrap_or_default(); | ||
| 241 | - eprintln!("stream {name}"); | ||
| 242 | - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); | ||
| 243 | - let mut row = match outcome { | ||
| 244 | - Ok(row) => row, | ||
| 245 | - Err(payload) => { | ||
| 246 | - let msg = payload | ||
| 247 | - .downcast_ref::<&str>() | ||
| 248 | - .map(|s| s.to_string()) | ||
| 249 | - .or_else(|| payload.downcast_ref::<String>().cloned()) | ||
| 250 | - .unwrap_or_default(); | ||
| 251 | - Row { | ||
| 252 | - name: name.clone(), | ||
| 253 | - accepted: "panic", | ||
| 254 | - checked: 0, | ||
| 255 | - exact: 0, | ||
| 256 | - detail: format!("panic: {msg}"), | ||
| 257 | - by_reference: false, | ||
| 258 | - decode_secs: 0.0, | ||
| 259 | - } | ||
| 260 | - } | ||
| 261 | - }; | ||
| 262 | - row.detail = row.detail.replace(['\t', '\n'], " "); | ||
| 263 | - rows.push(row); | ||
| 264 | - } | ||
| 265 | - | ||
| 266 | - let mut table = | ||
| 267 | - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); | ||
| 268 | - for r in &rows { | ||
| 269 | - println!( | ||
| 270 | - "{} | {} | {} | {} | {} | {:.2}s", | ||
| 271 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 272 | - ); | ||
| 273 | - table.push_str(&format!( | ||
| 274 | - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", | ||
| 275 | - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs | ||
| 276 | - )); | ||
| 277 | - } | ||
| 278 | - let checked: usize = rows.iter().map(|r| r.checked).sum(); | ||
| 279 | - let exact: usize = rows.iter().map(|r| r.exact).sum(); | ||
| 280 | - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); | ||
| 281 | - println!( | ||
| 282 | - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", | ||
| 283 | - rows.len() | ||
| 284 | - ); | ||
| 285 | - let report = std::env::var("EC_H265_REXT_REPORT") | ||
| 286 | - .ok() | ||
| 287 | - .filter(|p| !p.is_empty()); | ||
| 288 | - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); | ||
| 289 | - if let Some(Err((path, e))) = written { | ||
| 290 | - eprintln!("could not write report {path}: {e}"); | ||
| 291 | - } | ||
| 292 | - | ||
| 293 | - // Every accepted stream must be fully exact; a refusal must name a tool in REFUSED. | ||
| 294 | - let failing: Vec<String> = rows | ||
| 295 | - .iter() | ||
| 296 | - .filter(|r| r.accepted == "yes" && (r.checked == 0 || r.exact != r.checked)) | ||
| 297 | - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) | ||
| 298 | - .collect(); | ||
| 299 | - assert!( | ||
| 300 | - failing.is_empty(), | ||
| 301 | - "accepted streams that are not exact:\n{}", | ||
| 302 | - failing.join("\n") | ||
| 303 | - ); | ||
| 304 | - let unexpected: Vec<String> = rows | ||
| 305 | - .iter() | ||
| 306 | - .filter(|r| r.accepted != "yes") | ||
| 307 | - .filter(|r| !REFUSED.iter().any(|name| r.detail.contains(name))) | ||
| 308 | - .map(|r| format!("{} ({}: {})", r.name, r.accepted, r.detail)) | ||
| 309 | - .collect(); | ||
| 310 | - assert!( | ||
| 311 | - unexpected.is_empty(), | ||
| 312 | - "streams refused for a reason not in REFUSED:\n{}", | ||
| 313 | - unexpected.join("\n") | ||
| 314 | - ); | ||
| 315 | -} | ||
| 316 | - | ||
| 317 | -/// The refusals a conformance stream may end in: tools this decoder names and does not decode. | ||
| 318 | -const REFUSED: &[&str] = &[ | ||
| 319 | - "extended_precision_processing_flag", | ||
| 320 | - "cabac_bypass_alignment_enabled_flag", | ||
| 321 | - "high_precision_offsets_enabled_flag", | ||
| 322 | - "bit depth 16", | ||
| 323 | - "bit depth 14", | ||
| 324 | - "bit depth 13", | ||
| 325 | -]; | ||
crates/ec-h265/tests/it/conformance_rext422.rsdeleted+0 -128
| @@ -1,128 +0,0 @@ | |||
| 1 | -//! HEVC RExt 4:2:2 (Main 4:2:2 10 and the 8-bit generated clips) against ffmpeg. | ||
| 2 | -//! | ||
| 3 | -//! The committed 64x64 stream is decoded by ffmpeg at run time and compared sample for | ||
| 4 | -//! sample. The Sony RExt conformance streams and the generated GOP/intra clips live in the | ||
| 5 | - | ||
| 6 | -use std::path::{Path, PathBuf}; | ||
| 7 | - | ||
| 8 | -use ec_h265::Decoder; | ||
| 9 | - | ||
| 10 | -const YUV422_10: &[u8] = include_bytes!("../data/refusals/yuv422_10.265"); | ||
| 11 | - | ||
| 12 | -fn decode(data: &[u8]) -> Vec<ec_h265::decode::DecodedPicture> { | ||
| 13 | - let mut dec = Decoder::new(); | ||
| 14 | - dec.decode_annex_b(data).expect("decode"); | ||
| 15 | - dec.flush().expect("flush"); | ||
| 16 | - let mut out = Vec::new(); | ||
| 17 | - while let Some(f) = dec.next_frame() { | ||
| 18 | - out.push((*f.picture).clone()); | ||
| 19 | - } | ||
| 20 | - out | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -/// The first coded-size-cropped `w` x `h` window of every picture, as planar little-endian | ||
| 24 | -/// samples (one byte per sample at 8 bit, two above), the layout of ffmpeg's rawvideo. | ||
| 25 | -fn raw(pictures: &[ec_h265::decode::DecodedPicture], w: usize, h: usize) -> Vec<u8> { | ||
| 26 | - let mut out = Vec::new(); | ||
| 27 | - for p in pictures { | ||
| 28 | - let wide = p.bit_depth > 8; | ||
| 29 | - for (plane, pw, cw) in [ | ||
| 30 | - (&p.y, p.width, w), | ||
| 31 | - (&p.cb, p.width / 2, w / 2), | ||
| 32 | - (&p.cr, p.width / 2, w / 2), | ||
| 33 | - ] { | ||
| 34 | - for y in 0..h { | ||
| 35 | - for x in 0..cw { | ||
| 36 | - let v = plane[y * pw + x]; | ||
| 37 | - if wide { | ||
| 38 | - out.extend_from_slice(&v.to_le_bytes()); | ||
| 39 | - } else { | ||
| 40 | - out.push(v as u8); | ||
| 41 | - } | ||
| 42 | - } | ||
| 43 | - } | ||
| 44 | - } | ||
| 45 | - } | ||
| 46 | - out | ||
| 47 | -} | ||
| 48 | - | ||
| 49 | -fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> { | ||
| 50 | - if a.len() != b.len() { | ||
| 51 | - return Some(a.len().min(b.len())); | ||
| 52 | - } | ||
| 53 | - a.iter().zip(b).position(|(x, y)| x != y) | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -fn ffmpeg_422_10(src: &Path, reference: &Path) { | ||
| 57 | - let st = ec_testkit::ffmpeg() | ||
| 58 | - .args(["-v", "error", "-y", "-i"]) | ||
| 59 | - .arg(src) | ||
| 60 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv422p10le"]) | ||
| 61 | - .arg(reference) | ||
| 62 | - .status() | ||
| 63 | - .unwrap(); | ||
| 64 | - assert!(st.success(), "ffmpeg failed on {}", src.display()); | ||
| 65 | -} | ||
| 66 | - | ||
| 67 | -#[test] | ||
| 68 | -fn committed_422_stream_matches_ffmpeg() { | ||
| 69 | - let dir = std::env::temp_dir().join("ec-h265-rext422"); | ||
| 70 | - std::fs::create_dir_all(&dir).unwrap(); | ||
| 71 | - let src = dir.join("yuv422_10.265"); | ||
| 72 | - let reference = dir.join("yuv422_10.yuv"); | ||
| 73 | - std::fs::write(&src, YUV422_10).unwrap(); | ||
| 74 | - ffmpeg_422_10(&src, &reference); | ||
| 75 | - let want = std::fs::read(&reference).unwrap(); | ||
| 76 | - let got = raw(&decode(YUV422_10), 64, 64); | ||
| 77 | - assert_eq!( | ||
| 78 | - first_diff(&got, &want), | ||
| 79 | - None, | ||
| 80 | - "4:2:2 10-bit differs from ffmpeg" | ||
| 81 | - ); | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -fn rext_root() -> PathBuf { | ||
| 85 | - ec_testkit::fixture("vectors/hevc-rext") | ||
| 86 | -} | ||
| 87 | - | ||
| 88 | -fn find_stream(dir: &Path) -> Option<PathBuf> { | ||
| 89 | - for e in std::fs::read_dir(dir).ok()?.flatten() { | ||
| 90 | - let p = e.path(); | ||
| 91 | - if p.is_dir() { | ||
| 92 | - if let Some(f) = find_stream(&p) { | ||
| 93 | - return Some(f); | ||
| 94 | - } | ||
| 95 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 96 | - return Some(p); | ||
| 97 | - } | ||
| 98 | - } | ||
| 99 | - None | ||
| 100 | -} | ||
| 101 | - | ||
| 102 | -#[test] | ||
| 103 | -fn rext_422_vectors_are_byte_exact() { | ||
| 104 | - let root = rext_root(); | ||
| 105 | - let dir = std::env::temp_dir().join("ec-h265-rext422-vectors"); | ||
| 106 | - std::fs::create_dir_all(&dir).unwrap(); | ||
| 107 | - let mut checked = 0; | ||
| 108 | - for (name, w, h) in [ | ||
| 109 | - ("GENERAL_10b_422_RExt_Sony_1", 400, 384), | ||
| 110 | - ("Main_422_10_A_RExt_Sony_2", 1920, 1080), | ||
| 111 | - ("Main_422_10_B_RExt_Sony_2", 2560, 1600), | ||
| 112 | - ] { | ||
| 113 | - let stream = find_stream(&root.join(name)).unwrap_or_else(|| panic!("{name}: no stream")); | ||
| 114 | - let reference = dir.join(format!("{name}.yuv")); | ||
| 115 | - ffmpeg_422_10(&stream, &reference); | ||
| 116 | - let data = std::fs::read(&stream).unwrap_or_else(|e| panic!("{}: {e}", stream.display())); | ||
| 117 | - let want = std::fs::read(&reference).unwrap(); | ||
| 118 | - let got = raw(&decode(&data), w, h); | ||
| 119 | - assert_eq!( | ||
| 120 | - first_diff(&got, &want), | ||
| 121 | - None, | ||
| 122 | - "{} differs from ffmpeg", | ||
| 123 | - stream.display() | ||
| 124 | - ); | ||
| 125 | - checked += 1; | ||
| 126 | - } | ||
| 127 | - eprintln!("4:2:2 vectors checked byte-exact: {checked}"); | ||
| 128 | -} | ||
crates/ec-h265/tests/it/cu_syntax.rsdeleted+0 -130
| @@ -1,130 +0,0 @@ | |||
| 1 | -//! CU syntax tests over the JCT-VC conformance streams: the P/B slice syntax with the | ||
| 2 | -//! zero-motion stand-in (the sweep, pixel-pipeline and motion-determinism tests were removed by | ||
| 3 | -//! testcut Phase 2). | ||
| 4 | - | ||
| 5 | -use ec_core::error::Error; | ||
| 6 | -use ec_h265::dec::Decoder; | ||
| 7 | -use std::path::{Path, PathBuf}; | ||
| 8 | - | ||
| 9 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each directory | ||
| 10 | -fn streams() -> Vec<PathBuf> { | ||
| 11 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 12 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 13 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 14 | - return; | ||
| 15 | - }; | ||
| 16 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 17 | - paths.sort(); | ||
| 18 | - for p in paths { | ||
| 19 | - if p.is_dir() && depth > 0 { | ||
| 20 | - bitstreams_in(&p, depth - 1, out); | ||
| 21 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 22 | - out.push(p); | ||
| 23 | - } | ||
| 24 | - } | ||
| 25 | - } | ||
| 26 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 27 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 28 | - dirs.sort(); | ||
| 29 | - dirs.into_iter() | ||
| 30 | - .filter(|d| d.is_dir()) | ||
| 31 | - .filter_map(|d| { | ||
| 32 | - let mut found = Vec::new(); | ||
| 33 | - bitstreams_in(&d, 2, &mut found); | ||
| 34 | - found.into_iter().next() | ||
| 35 | - }) | ||
| 36 | - .collect() | ||
| 37 | -} | ||
| 38 | - | ||
| 39 | -/// Split an Annex-B byte stream into NAL units (header included, start codes and | ||
| 40 | -/// trailing zero bytes removed). | ||
| 41 | -fn nal_units(data: &[u8]) -> Vec<&[u8]> { | ||
| 42 | - let mut starts = Vec::new(); | ||
| 43 | - let mut i = 0; | ||
| 44 | - while i + 3 <= data.len() { | ||
| 45 | - if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { | ||
| 46 | - starts.push(i + 3); | ||
| 47 | - i += 3; | ||
| 48 | - } else { | ||
| 49 | - i += 1; | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - let mut out = Vec::new(); | ||
| 53 | - for (k, &s) in starts.iter().enumerate() { | ||
| 54 | - let mut e = starts.get(k + 1).map_or(data.len(), |&next| next - 3); | ||
| 55 | - while e > s && data[e - 1] == 0 { | ||
| 56 | - e -= 1; | ||
| 57 | - } | ||
| 58 | - if e > s { | ||
| 59 | - out.push(&data[s..e]); | ||
| 60 | - } | ||
| 61 | - } | ||
| 62 | - out | ||
| 63 | -} | ||
| 64 | - | ||
| 65 | -/// Whether a NAL unit is a coded slice segment (types 0 to 9 and 16 to 21). | ||
| 66 | -fn is_slice(nal: &[u8]) -> bool { | ||
| 67 | - let t = (nal[0] >> 1) & 0x3f; | ||
| 68 | - t <= 9 || (16..=21).contains(&t) | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -/// The P/B slice syntax ([`ec_h265::dec::cu_syntax::parse_slice`] with the zero-motion | ||
| 72 | -/// stand-in, no DPB to derive motion from) over every P and B slice segment of every | ||
| 73 | -/// stream. Pixel decode is off so the decoder only keeps parameter sets. Refusals are | ||
| 74 | -/// fine; any other error is a failure. | ||
| 75 | -#[test] | ||
| 76 | -fn inter_placeholder_runs_over_pb_slices() { | ||
| 77 | - use ec_core::bitio::BitReader; | ||
| 78 | - use ec_h265_syntax::nal::{NalUnitType, unescape_rbsp}; | ||
| 79 | - use ec_h265_syntax::slice::{SliceHeader, SliceType}; | ||
| 80 | - let streams = streams(); | ||
| 81 | - assert!(!streams.is_empty(), "no conformance streams"); | ||
| 82 | - let (mut pb_slices, mut decoded, mut refused) = (0usize, 0usize, 0usize); | ||
| 83 | - for path in &streams { | ||
| 84 | - let data = std::fs::read(path).expect("read bitstream"); | ||
| 85 | - let mut dec = Decoder::new(); | ||
| 86 | - dec.set_pixel_decode(false); | ||
| 87 | - for nal in nal_units(&data) { | ||
| 88 | - let code = (nal[0] >> 1) & 0x3f; | ||
| 89 | - if is_slice(nal) { | ||
| 90 | - let rbsp = unescape_rbsp(&nal[2..]); | ||
| 91 | - let mut r = BitReader::new(&rbsp); | ||
| 92 | - let _first = r.read_bit(); | ||
| 93 | - if (16..=21).contains(&code) { | ||
| 94 | - let _no_output_of_prior_pics = r.read_bit(); | ||
| 95 | - } | ||
| 96 | - let pps_id = r.read_ue().unwrap_or(u32::MAX); | ||
| 97 | - if let Some(pps) = dec.pps(pps_id) | ||
| 98 | - && let Some(sps) = dec.sps(pps.sps_id) | ||
| 99 | - && let Ok((header, pos)) = | ||
| 100 | - SliceHeader::parse(&rbsp, sps, pps, NalUnitType::from_code(code)) | ||
| 101 | - && header.slice_type != SliceType::I | ||
| 102 | - && header.first_slice_segment_in_pic | ||
| 103 | - { | ||
| 104 | - pb_slices += 1; | ||
| 105 | - let off = (pos.header_bits / 8) as usize; | ||
| 106 | - let slice_data = rbsp.get(off..).unwrap_or(&[]); | ||
| 107 | - let mut zero = ec_h265::dec::cu_syntax::ZeroMotion; | ||
| 108 | - match ec_h265::dec::cu_syntax::parse_slice( | ||
| 109 | - sps, | ||
| 110 | - pps, | ||
| 111 | - &header, | ||
| 112 | - slice_data, | ||
| 113 | - &mut zero, | ||
| 114 | - &mut |_| {}, | ||
| 115 | - ) { | ||
| 116 | - Ok(_) => decoded += 1, | ||
| 117 | - Err(Error::Unsupported { .. }) => refused += 1, | ||
| 118 | - Err(err) => { | ||
| 119 | - panic!("{}: P/B placeholder failed: {err}", path.display()) | ||
| 120 | - } | ||
| 121 | - } | ||
| 122 | - } | ||
| 123 | - } | ||
| 124 | - let _ = dec.push_nal(nal); | ||
| 125 | - } | ||
| 126 | - } | ||
| 127 | - println!( | ||
| 128 | - "inter syntax: {decoded} P/B slices parsed, {refused} refused by name, of {pb_slices} first-slice P/B segments" | ||
| 129 | - ); | ||
| 130 | -} | ||
crates/ec-h265/tests/it/dec_meta.rsdeleted+0 -244
| @@ -1,244 +0,0 @@ | |||
| 1 | -//! Metadata on the decoder's output frames: HDR SEI from the IRAP on, the VUI | ||
| 2 | -//! colour description, the decoded picture hash, and the rule that Dolby Vision | ||
| 3 | -//! NAL units (62, 63) and malformed SEI change nothing. | ||
| 4 | -//! | ||
| 5 | -//! The streams come from `fixtures/vectors/hevc-jctvc`. Without them the tests | ||
| 6 | - | ||
| 7 | -use std::path::{Path, PathBuf}; | ||
| 8 | - | ||
| 9 | -use ec_h265::dec::{Decoder, Frame}; | ||
| 10 | -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; | ||
| 11 | -use ec_h265_syntax::sei::{ContentLightLevel, MasteringDisplay, PictureHash}; | ||
| 12 | - | ||
| 13 | -fn stream_files() -> Vec<PathBuf> { | ||
| 14 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 15 | - fn walk(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 16 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 17 | - return; | ||
| 18 | - }; | ||
| 19 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 20 | - paths.sort(); | ||
| 21 | - for p in paths { | ||
| 22 | - if p.is_dir() && depth > 0 { | ||
| 23 | - walk(&p, depth - 1, out); | ||
| 24 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 25 | - out.push(p); | ||
| 26 | - } | ||
| 27 | - } | ||
| 28 | - } | ||
| 29 | - let mut out = Vec::new(); | ||
| 30 | - walk(&root, 2, &mut out); | ||
| 31 | - out | ||
| 32 | -} | ||
| 33 | - | ||
| 34 | -/// The raw NAL units (two-byte header and escaped payload) of an Annex-B stream. | ||
| 35 | -fn raw_nals(data: &[u8]) -> Vec<Vec<u8>> { | ||
| 36 | - split_annex_b(data) | ||
| 37 | - .iter() | ||
| 38 | - .map(|n| { | ||
| 39 | - let mut v = n.header.to_bytes().to_vec(); | ||
| 40 | - v.extend_from_slice(n.payload); | ||
| 41 | - v | ||
| 42 | - }) | ||
| 43 | - .collect() | ||
| 44 | -} | ||
| 45 | - | ||
| 46 | -/// Decode with picture management only, returning every frame, or the first error. | ||
| 47 | -fn decode(nals: &[Vec<u8>]) -> Result<Vec<Frame>, String> { | ||
| 48 | - let mut dec = Decoder::new(); | ||
| 49 | - dec.set_pixel_decode(false); | ||
| 50 | - for nal in nals { | ||
| 51 | - dec.push_nal(nal).map_err(|e| e.to_string())?; | ||
| 52 | - } | ||
| 53 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 54 | - let mut frames = Vec::new(); | ||
| 55 | - while let Some(f) = dec.next_frame() { | ||
| 56 | - frames.push(f); | ||
| 57 | - } | ||
| 58 | - Ok(frames) | ||
| 59 | -} | ||
| 60 | - | ||
| 61 | -/// The first conformance stream that decodes without error, with its NAL units. | ||
| 62 | -fn clean_stream() -> Option<(String, Vec<Vec<u8>>)> { | ||
| 63 | - for path in stream_files() { | ||
| 64 | - let Ok(data) = std::fs::read(&path) else { | ||
| 65 | - continue; | ||
| 66 | - }; | ||
| 67 | - let nals = raw_nals(&data); | ||
| 68 | - if decode(&nals).is_ok() { | ||
| 69 | - let name = path | ||
| 70 | - .file_name() | ||
| 71 | - .unwrap_or_default() | ||
| 72 | - .to_string_lossy() | ||
| 73 | - .to_string(); | ||
| 74 | - return Some((name, nals)); | ||
| 75 | - } | ||
| 76 | - } | ||
| 77 | - None | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -fn require_stream() -> (String, Vec<Vec<u8>>) { | ||
| 81 | - clean_stream().expect("no clean conformance stream") | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -/// What a frame looks like to a caller, for comparing two decodes. | ||
| 85 | -fn key(f: &Frame) -> (i32, u32, usize, usize, Vec<u16>, Vec<u16>, Vec<u16>) { | ||
| 86 | - ( | ||
| 87 | - f.poc, | ||
| 88 | - f.au_index, | ||
| 89 | - f.picture.width, | ||
| 90 | - f.picture.height, | ||
| 91 | - f.picture.y.clone(), | ||
| 92 | - f.picture.cb.clone(), | ||
| 93 | - f.picture.cr.clone(), | ||
| 94 | - ) | ||
| 95 | -} | ||
| 96 | - | ||
| 97 | -/// A NAL unit of the given type, with the payload escaped. | ||
| 98 | -fn nal_unit(nal_type: u8, rbsp: &[u8]) -> Vec<u8> { | ||
| 99 | - let mut v = vec![nal_type << 1, 1]; | ||
| 100 | - escape_rbsp(rbsp, &mut v); | ||
| 101 | - v | ||
| 102 | -} | ||
| 103 | - | ||
| 104 | -fn is_vcl(nal: &[u8]) -> bool { | ||
| 105 | - matches!((nal[0] >> 1) & 0x3f, 0..=21) | ||
| 106 | -} | ||
| 107 | - | ||
| 108 | -/// The HDR10 mastering display of a 1000 nit, 0.0050 nit BT.2020 grade, then a | ||
| 109 | -/// content light level of MaxCLL 1000 and MaxFALL 400, as one prefix SEI RBSP. | ||
| 110 | -fn hdr10_prefix_rbsp() -> Vec<u8> { | ||
| 111 | - let mut mdcv = Vec::new(); | ||
| 112 | - for (x, y) in [ | ||
| 113 | - (8500u16, 39_850u16), | ||
| 114 | - (6550, 2300), | ||
| 115 | - (35_400, 14_600), | ||
| 116 | - (15_635, 16_450), | ||
| 117 | - ] { | ||
| 118 | - mdcv.extend_from_slice(&x.to_be_bytes()); | ||
| 119 | - mdcv.extend_from_slice(&y.to_be_bytes()); | ||
| 120 | - } | ||
| 121 | - mdcv.extend_from_slice(&10_000_000u32.to_be_bytes()); | ||
| 122 | - mdcv.extend_from_slice(&50u32.to_be_bytes()); | ||
| 123 | - let mut rbsp = vec![137, 24]; | ||
| 124 | - rbsp.extend_from_slice(&mdcv); | ||
| 125 | - rbsp.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90, 0x80]); | ||
| 126 | - rbsp | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -#[test] | ||
| 130 | -fn dolby_vision_nal_units_change_nothing() { | ||
| 131 | - let (name, nals) = require_stream(); | ||
| 132 | - let base = decode(&nals).unwrap(); | ||
| 133 | - let mut injected = Vec::new(); | ||
| 134 | - for nal in &nals { | ||
| 135 | - injected.push(vec![62 << 1, 1, 0xde, 0xad, 0xbe, 0xef]); | ||
| 136 | - injected.push(vec![63 << 1, 1, 0x80]); | ||
| 137 | - injected.push(nal.clone()); | ||
| 138 | - } | ||
| 139 | - let with_rpu = decode(&injected).unwrap(); | ||
| 140 | - assert!(!base.is_empty(), "{name}: no frames"); | ||
| 141 | - assert_eq!(base.len(), with_rpu.len(), "{name}: frame count changed"); | ||
| 142 | - for (a, b) in base.iter().zip(&with_rpu) { | ||
| 143 | - assert_eq!( | ||
| 144 | - key(a), | ||
| 145 | - key(b), | ||
| 146 | - "{name}: a frame changed with type 62/63 NAL units" | ||
| 147 | - ); | ||
| 148 | - } | ||
| 149 | -} | ||
| 150 | - | ||
| 151 | -#[test] | ||
| 152 | -fn malformed_sei_is_skipped_and_the_stream_decodes_the_same() { | ||
| 153 | - let (name, nals) = require_stream(); | ||
| 154 | - let base = decode(&nals).unwrap(); | ||
| 155 | - let mut injected = Vec::new(); | ||
| 156 | - for nal in &nals { | ||
| 157 | - // A message that runs past the RBSP, a suffix SEI with a reserved hash type, | ||
| 158 | - // and one with a short mastering display payload. | ||
| 159 | - injected.push(nal_unit(39, &[5, 9, 1, 2, 0x80])); | ||
| 160 | - injected.push(nal_unit(40, &[132, 2, 3, 0, 0x80])); | ||
| 161 | - let mut short_mdcv = vec![137, 23]; | ||
| 162 | - short_mdcv.extend_from_slice(&[0; 23]); | ||
| 163 | - short_mdcv.push(0x80); | ||
| 164 | - injected.push(nal_unit(39, &short_mdcv)); | ||
| 165 | - injected.push(nal.clone()); | ||
| 166 | - } | ||
| 167 | - let with_bad = decode(&injected).unwrap(); | ||
| 168 | - assert_eq!(base.len(), with_bad.len(), "{name}: frame count changed"); | ||
| 169 | - for (a, b) in base.iter().zip(&with_bad) { | ||
| 170 | - assert_eq!(key(a), key(b), "{name}: a frame changed with malformed SEI"); | ||
| 171 | - assert!( | ||
| 172 | - b.mastering_display().is_none(), | ||
| 173 | - "{name}: a malformed SEI produced metadata" | ||
| 174 | - ); | ||
| 175 | - } | ||
| 176 | -} | ||
| 177 | - | ||
| 178 | -#[test] | ||
| 179 | -fn hdr_sei_applies_to_every_frame_from_the_irap_on() { | ||
| 180 | - let (name, nals) = require_stream(); | ||
| 181 | - let mut injected = Vec::new(); | ||
| 182 | - let mut placed = false; | ||
| 183 | - for nal in &nals { | ||
| 184 | - if !placed && is_vcl(nal) { | ||
| 185 | - // A prefix SEI in the first access unit, before its first slice. | ||
| 186 | - injected.push(nal_unit(39, &hdr10_prefix_rbsp())); | ||
| 187 | - placed = true; | ||
| 188 | - } | ||
| 189 | - injected.push(nal.clone()); | ||
| 190 | - } | ||
| 191 | - let frames = decode(&injected).unwrap(); | ||
| 192 | - assert!(!frames.is_empty(), "{name}: no frames"); | ||
| 193 | - for f in &frames { | ||
| 194 | - let md: &MasteringDisplay = f.mastering_display().expect("MDCV on every frame"); | ||
| 195 | - assert_eq!(md.display_primaries[0], (8500, 39_850)); | ||
| 196 | - assert_eq!(md.white_point, (15_635, 16_450)); | ||
| 197 | - assert_eq!(md.max_nits(), 1000.0); | ||
| 198 | - assert!((md.min_nits() - 0.005).abs() < 1e-6); | ||
| 199 | - let cll: &ContentLightLevel = f.content_light_level().expect("CLL on every frame"); | ||
| 200 | - assert_eq!( | ||
| 201 | - (cll.max_content_light_level, cll.max_pic_average_light_level), | ||
| 202 | - (1000, 400) | ||
| 203 | - ); | ||
| 204 | - assert_eq!(f.alternative_transfer_characteristics(), None); | ||
| 205 | - } | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -#[test] | ||
| 209 | -fn picture_hash_attaches_to_the_picture_it_follows() { | ||
| 210 | - let (name, nals) = require_stream(); | ||
| 211 | - // One MD5 plane: payloadType 132, payloadSize 17, hash_type 0, the digest. | ||
| 212 | - let digest = [0x5au8; 16]; | ||
| 213 | - let mut hash_rbsp = vec![132, 17, 0]; | ||
| 214 | - hash_rbsp.extend_from_slice(&digest); | ||
| 215 | - hash_rbsp.push(0x80); | ||
| 216 | - | ||
| 217 | - let mut injected = Vec::new(); | ||
| 218 | - let mut placed = false; | ||
| 219 | - for nal in &nals { | ||
| 220 | - injected.push(nal.clone()); | ||
| 221 | - // A suffix SEI right after the first slice: it belongs to access unit 0. | ||
| 222 | - if !placed && is_vcl(nal) { | ||
| 223 | - injected.push(nal_unit(40, &hash_rbsp)); | ||
| 224 | - placed = true; | ||
| 225 | - } | ||
| 226 | - } | ||
| 227 | - let frames = decode(&injected).unwrap(); | ||
| 228 | - assert!(placed, "{name}: no slice NAL unit"); | ||
| 229 | - let first = frames | ||
| 230 | - .iter() | ||
| 231 | - .find(|f| f.au_index == 0) | ||
| 232 | - .expect("access unit 0 is output"); | ||
| 233 | - match first.picture_hash() { | ||
| 234 | - Some(PictureHash::Md5(d)) => assert_eq!(d, &[digest]), | ||
| 235 | - other => panic!("{name}: access unit 0 hash is {other:?}"), | ||
| 236 | - } | ||
| 237 | - assert!( | ||
| 238 | - frames | ||
| 239 | - .iter() | ||
| 240 | - .filter(|f| f.au_index != 0) | ||
| 241 | - .all(|f| f.picture_hash().is_none()), | ||
| 242 | - "{name}: a hash leaked to another picture" | ||
| 243 | - ); | ||
| 244 | -} | ||
crates/ec-h265/tests/it/dec_shell.rsdeleted+0 -454
| @@ -1,454 +0,0 @@ | |||
| 1 | -//! Picture management of the stateful decoder (`ec_h265::dec`): POC, RPS and | ||
| 2 | -//! marking, bumping, reference lists, and the JCT-VC conformance sweep. | ||
| 3 | -//! | ||
| 4 | -//! The sweep parses every slice of every stream through the picture-management | ||
| 5 | -//! path (pixel decode off) and checks the output order against ffprobe. Streams | ||
| 6 | -//! whose slices are all intra are also pixel-decoded and compared with ffmpeg's | ||
| 7 | - | ||
| 8 | -use std::collections::VecDeque; | ||
| 9 | -use std::path::{Path, PathBuf}; | ||
| 10 | - | ||
| 11 | -use ec_h265::dec::dpb::{Dpb, DpbLimits, Marking, PendingFrame}; | ||
| 12 | -use ec_h265::dec::poc::derive_poc; | ||
| 13 | -use ec_h265::dec::rps::{RpsInput, build_ref_lists}; | ||
| 14 | -use ec_h265::dec::shared::SharedPic; | ||
| 15 | -use ec_h265::dec::{Decoder, NalOutcome}; | ||
| 16 | -use ec_h265::decode::DecodedPicture; | ||
| 17 | -use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType}; | ||
| 18 | -use ec_h265_syntax::{ConformanceWindow, Pps, ShortTermRefPicSet}; | ||
| 19 | - | ||
| 20 | -fn picture(w: usize, h: usize) -> DecodedPicture { | ||
| 21 | - DecodedPicture { | ||
| 22 | - width: w, | ||
| 23 | - height: h, | ||
| 24 | - bit_depth: 8, | ||
| 25 | - bit_depth_c: 8, | ||
| 26 | - chroma_format_idc: 1, | ||
| 27 | - y: Vec::new(), | ||
| 28 | - cb: Vec::new(), | ||
| 29 | - cr: Vec::new(), | ||
| 30 | - } | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -fn st_set(before: &[i32], after: &[i32]) -> ShortTermRefPicSet { | ||
| 34 | - let mut st = ShortTermRefPicSet { | ||
| 35 | - num_negative: before.len() as u32, | ||
| 36 | - num_positive: after.len() as u32, | ||
| 37 | - ..ShortTermRefPicSet::default() | ||
| 38 | - }; | ||
| 39 | - for (i, &d) in before.iter().enumerate() { | ||
| 40 | - st.delta_poc_s0[i] = d; | ||
| 41 | - st.used_s0[i] = true; | ||
| 42 | - } | ||
| 43 | - for (i, &d) in after.iter().enumerate() { | ||
| 44 | - st.delta_poc_s1[i] = d; | ||
| 45 | - st.used_s1[i] = true; | ||
| 46 | - } | ||
| 47 | - st | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | -fn rps_input<'a>( | ||
| 51 | - poc: i32, | ||
| 52 | - st: &'a ShortTermRefPicSet, | ||
| 53 | - lt: &'a [LongTermRef], | ||
| 54 | - fill: Option<(u32, u32)>, | ||
| 55 | -) -> RpsInput<'a> { | ||
| 56 | - RpsInput { | ||
| 57 | - poc, | ||
| 58 | - log2_max_poc_lsb: 4, | ||
| 59 | - st, | ||
| 60 | - lt, | ||
| 61 | - irap_no_rasl: false, | ||
| 62 | - width: 16, | ||
| 63 | - height: 16, | ||
| 64 | - chroma_format_idc: 1, | ||
| 65 | - fill, | ||
| 66 | - } | ||
| 67 | -} | ||
| 68 | - | ||
| 69 | -fn add(dpb: &mut Dpb, poc: i32, marking: Marking, output: bool) -> u32 { | ||
| 70 | - dpb.insert( | ||
| 71 | - poc, | ||
| 72 | - marking, | ||
| 73 | - output, | ||
| 74 | - std::sync::Arc::new(SharedPic::from_planes(poc, picture(16, 16))), | ||
| 75 | - ConformanceWindow::default(), | ||
| 76 | - poc as u32, | ||
| 77 | - ) | ||
| 78 | -} | ||
| 79 | - | ||
| 80 | -#[test] | ||
| 81 | -fn poc_follows_the_lsb_without_wrapping() { | ||
| 82 | - assert_eq!(derive_poc(5, 4, 7, false), 7); | ||
| 83 | - assert_eq!(derive_poc(0, 4, 0, false), 0); | ||
| 84 | -} | ||
| 85 | - | ||
| 86 | -#[test] | ||
| 87 | -fn poc_msb_wraps_forward_at_the_half_window() { | ||
| 88 | - // prevTid0 = 0, lsb 14 of 16: 14 - 0 > 8, so the MSB is -16 and POC is -2. | ||
| 89 | - assert_eq!(derive_poc(0, 4, 14, false), -2); | ||
| 90 | -} | ||
| 91 | - | ||
| 92 | -#[test] | ||
| 93 | -fn poc_msb_wraps_backward_past_the_maximum() { | ||
| 94 | - // prevTid0 = 14 (lsb 14), lsb 2: 14 - 2 >= 8, so the MSB advances to 16. | ||
| 95 | - assert_eq!(derive_poc(14, 4, 2, false), 18); | ||
| 96 | -} | ||
| 97 | - | ||
| 98 | -#[test] | ||
| 99 | -fn poc_of_an_irap_with_no_rasl_output_has_no_msb() { | ||
| 100 | - assert_eq!(derive_poc(37, 4, 5, true), 5); | ||
| 101 | -} | ||
| 102 | - | ||
| 103 | -#[test] | ||
| 104 | -fn rps_marks_what_it_names_and_drops_the_rest() { | ||
| 105 | - let mut dpb = Dpb::new(); | ||
| 106 | - let ids: Vec<u32> = [0, 1, 2, 3, 4, 5, 6, 7] | ||
| 107 | - .iter() | ||
| 108 | - .map(|&p| add(&mut dpb, p, Marking::ShortTerm, false)) | ||
| 109 | - .collect(); | ||
| 110 | - // Current POC 8 names 7, 5 and 4 (deltas -1, -3, -4). 0..3 and 6 drop out. | ||
| 111 | - let st = st_set(&[-1, -3, -4], &[]); | ||
| 112 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 113 | - let before: Vec<i32> = set.st_curr_before.iter().map(|e| e.poc).collect(); | ||
| 114 | - assert_eq!(before, vec![7, 5, 4]); | ||
| 115 | - assert!(set.st_curr_after.is_empty()); | ||
| 116 | - assert!(set.lt_curr.is_empty()); | ||
| 117 | - assert_eq!(set.st_curr_before[0].id, ids[7]); | ||
| 118 | - for &p in &[0usize, 1, 2, 3, 6] { | ||
| 119 | - assert_eq!(dpb.get(ids[p]).unwrap().marking, Marking::Unused, "POC {p}"); | ||
| 120 | - } | ||
| 121 | - assert_eq!(dpb.get(ids[5]).unwrap().marking, Marking::ShortTerm); | ||
| 122 | - dpb.remove_unneeded(); | ||
| 123 | - assert_eq!(dpb.len(), 3); | ||
| 124 | -} | ||
| 125 | - | ||
| 126 | -#[test] | ||
| 127 | -fn rps_generates_a_missing_reference_as_grey() { | ||
| 128 | - let mut dpb = Dpb::new(); | ||
| 129 | - add(&mut dpb, 4, Marking::ShortTerm, false); | ||
| 130 | - // Current POC 8 names POC 6 (absent) and POC 4. | ||
| 131 | - let st = st_set(&[-2, -4], &[]); | ||
| 132 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 133 | - assert_eq!(set.st_curr_before.len(), 2); | ||
| 134 | - let generated = dpb | ||
| 135 | - .get(set.st_curr_before[0].id) | ||
| 136 | - .expect("generated picture"); | ||
| 137 | - assert_eq!(generated.poc, 6); | ||
| 138 | - assert!(!generated.needed_for_output); | ||
| 139 | - let planes = generated.picture.read_planes(); | ||
| 140 | - assert_eq!(planes.y.len(), 16 * 16); | ||
| 141 | - assert!(planes.y.iter().all(|&v| v == 128)); | ||
| 142 | -} | ||
| 143 | - | ||
| 144 | -#[test] | ||
| 145 | -fn rps_long_term_entry_matches_by_lsb_and_converts_marking() { | ||
| 146 | - let mut dpb = Dpb::new(); | ||
| 147 | - let lt_id = add(&mut dpb, 16, Marking::ShortTerm, false); | ||
| 148 | - // PocLsbLt 0 with no MSB: the picture with POC & 15 == 0 is POC 16. | ||
| 149 | - let lt = [LongTermRef { | ||
| 150 | - poc_lsb_lt: 0, | ||
| 151 | - used_by_curr: true, | ||
| 152 | - delta_poc_msb_present: false, | ||
| 153 | - delta_poc_msb_cycle: 0, | ||
| 154 | - }]; | ||
| 155 | - let st = ShortTermRefPicSet::default(); | ||
| 156 | - let set = dpb.apply_rps(&rps_input(20, &st, <, Some((8, 8)))); | ||
| 157 | - assert_eq!(set.lt_curr.len(), 1); | ||
| 158 | - assert_eq!(set.lt_curr[0].id, lt_id); | ||
| 159 | - assert!(set.lt_curr[0].long_term); | ||
| 160 | - assert_eq!(dpb.get(lt_id).unwrap().marking, Marking::LongTerm); | ||
| 161 | -} | ||
| 162 | - | ||
| 163 | -#[test] | ||
| 164 | -fn bumping_outputs_in_poc_order_under_the_reorder_limit() { | ||
| 165 | - let limits = DpbLimits { | ||
| 166 | - max_dec_pic_buffering: 6, | ||
| 167 | - max_num_reorder: 2, | ||
| 168 | - max_latency_plus1: 0, | ||
| 169 | - }; | ||
| 170 | - let mut dpb = Dpb::new(); | ||
| 171 | - let mut out: VecDeque<PendingFrame> = VecDeque::new(); | ||
| 172 | - // Decode order 0, 8, 4, 2: a reorder limit of 2 forces output as it goes. | ||
| 173 | - for poc in [0, 8, 4, 2] { | ||
| 174 | - add(&mut dpb, poc, Marking::Unused, true); | ||
| 175 | - while dpb.needs_bumping(&limits, false) && dpb.bump(&mut out) {} | ||
| 176 | - } | ||
| 177 | - let early: Vec<i32> = out.iter().map(|f| f.poc).collect(); | ||
| 178 | - assert_eq!(early, vec![0, 2]); | ||
| 179 | - dpb.drain(&mut out); | ||
| 180 | - let all: Vec<i32> = out.iter().map(|f| f.poc).collect(); | ||
| 181 | - assert_eq!(all, vec![0, 2, 4, 8]); | ||
| 182 | - assert!(dpb.is_empty()); | ||
| 183 | -} | ||
| 184 | - | ||
| 185 | -#[test] | ||
| 186 | -fn bumping_honours_the_latency_limit() { | ||
| 187 | - let limits = DpbLimits { | ||
| 188 | - max_dec_pic_buffering: 6, | ||
| 189 | - max_num_reorder: 4, | ||
| 190 | - max_latency_plus1: 1, | ||
| 191 | - }; | ||
| 192 | - let mut dpb = Dpb::new(); | ||
| 193 | - let mut out = VecDeque::new(); | ||
| 194 | - add(&mut dpb, 0, Marking::Unused, true); | ||
| 195 | - assert!(!dpb.needs_bumping(&limits, false)); | ||
| 196 | - // SpsMaxLatencyPictures = 4 + 1 - 1 = 4: a picture that waited 4 times goes out. | ||
| 197 | - dpb.pictures_mut()[0].latency = 4; | ||
| 198 | - assert!(dpb.needs_bumping(&limits, false)); | ||
| 199 | - assert!(dpb.bump(&mut out)); | ||
| 200 | - assert_eq!(out.len(), 1); | ||
| 201 | -} | ||
| 202 | - | ||
| 203 | -#[test] | ||
| 204 | -fn bumping_drops_a_full_buffer_only_when_asked() { | ||
| 205 | - let limits = DpbLimits { | ||
| 206 | - max_dec_pic_buffering: 2, | ||
| 207 | - max_num_reorder: 8, | ||
| 208 | - max_latency_plus1: 0, | ||
| 209 | - }; | ||
| 210 | - let mut dpb = Dpb::new(); | ||
| 211 | - add(&mut dpb, 0, Marking::ShortTerm, false); | ||
| 212 | - add(&mut dpb, 2, Marking::ShortTerm, false); | ||
| 213 | - assert!(dpb.needs_bumping(&limits, true)); | ||
| 214 | - assert!(!dpb.needs_bumping(&limits, false)); | ||
| 215 | -} | ||
| 216 | - | ||
| 217 | -#[test] | ||
| 218 | -fn reference_lists_cycle_and_follow_the_modification() { | ||
| 219 | - let mut dpb = Dpb::new(); | ||
| 220 | - let a = add(&mut dpb, 4, Marking::ShortTerm, false); | ||
| 221 | - let b = add(&mut dpb, 6, Marking::ShortTerm, false); | ||
| 222 | - let c = add(&mut dpb, 10, Marking::ShortTerm, false); | ||
| 223 | - let st = st_set(&[-4, -2], &[2]); | ||
| 224 | - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); | ||
| 225 | - assert_eq!( | ||
| 226 | - set.st_curr_before.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 227 | - vec![a, b] | ||
| 228 | - ); | ||
| 229 | - assert_eq!( | ||
| 230 | - set.st_curr_after.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 231 | - vec![c] | ||
| 232 | - ); | ||
| 233 | - | ||
| 234 | - let pps = Pps::default(); | ||
| 235 | - let mut header = SliceHeader::intra(&pps, 0); | ||
| 236 | - header.slice_type = SliceType::B; | ||
| 237 | - header.num_ref_idx_l0_active_minus1 = 3; | ||
| 238 | - header.num_ref_idx_l1_active_minus1 = 1; | ||
| 239 | - let lists = build_ref_lists(&set, &header).expect("lists"); | ||
| 240 | - let l0: Vec<u32> = lists.l0.iter().map(|e| e.id).collect(); | ||
| 241 | - assert_eq!(l0, vec![a, b, c, a]); | ||
| 242 | - let l1: Vec<u32> = lists.l1.iter().map(|e| e.id).collect(); | ||
| 243 | - assert_eq!(l1, vec![c, a]); | ||
| 244 | - | ||
| 245 | - header.list_entry = [vec![2, 2, 0, 1], vec![1, 0]]; | ||
| 246 | - let lists = build_ref_lists(&set, &header).expect("modified lists"); | ||
| 247 | - assert_eq!( | ||
| 248 | - lists.l0.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 249 | - vec![c, c, a, b] | ||
| 250 | - ); | ||
| 251 | - assert_eq!( | ||
| 252 | - lists.l1.iter().map(|e| e.id).collect::<Vec<_>>(), | ||
| 253 | - vec![a, c] | ||
| 254 | - ); | ||
| 255 | -} | ||
| 256 | - | ||
| 257 | -#[test] | ||
| 258 | -fn decoder_refuses_out_of_scope_parameter_sets_and_skips_layers() { | ||
| 259 | - let mut dec = Decoder::new(); | ||
| 260 | - // A VPS-typed NAL on layer 1 is skipped whatever its payload. | ||
| 261 | - let layer1 = [32u8 << 1, 0b0000_1001, 0xff]; | ||
| 262 | - assert_eq!(dec.push_nal(&layer1).unwrap(), NalOutcome::Skipped); | ||
| 263 | - // SEI and filler are ignored. | ||
| 264 | - assert_eq!( | ||
| 265 | - dec.push_nal(&[39 << 1, 1, 0x80]).unwrap(), | ||
| 266 | - NalOutcome::Skipped | ||
| 267 | - ); | ||
| 268 | - assert_eq!( | ||
| 269 | - dec.push_nal(&[62 << 1, 1, 0x80]).unwrap(), | ||
| 270 | - NalOutcome::Skipped | ||
| 271 | - ); | ||
| 272 | - assert!(dec.next_frame().is_none()); | ||
| 273 | -} | ||
| 274 | - | ||
| 275 | -fn run(args: &[&str], file: &Path) -> Result<Vec<u8>, String> { | ||
| 276 | - let out = ec_testkit::ffprobe() | ||
| 277 | - .args(["-v", "error"]) | ||
| 278 | - .args(args) | ||
| 279 | - .arg(file) | ||
| 280 | - .output() | ||
| 281 | - .map_err(|e| e.to_string())?; | ||
| 282 | - if !out.status.success() { | ||
| 283 | - return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); | ||
| 284 | - } | ||
| 285 | - Ok(out.stdout) | ||
| 286 | -} | ||
| 287 | - | ||
| 288 | -fn numbers(text: &[u8]) -> Vec<u64> { | ||
| 289 | - String::from_utf8_lossy(text) | ||
| 290 | - .lines() | ||
| 291 | - .filter_map(|l| l.trim().trim_end_matches(',').parse().ok()) | ||
| 292 | - .collect() | ||
| 293 | -} | ||
| 294 | - | ||
| 295 | -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's | ||
| 296 | -/// by name. Some zips extract one directory deeper, so two levels are searched. | ||
| 297 | -fn streams() -> Vec<PathBuf> { | ||
| 298 | - let root = ec_testkit::fixture("vectors/hevc-jctvc"); | ||
| 299 | - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) { | ||
| 300 | - let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 301 | - return; | ||
| 302 | - }; | ||
| 303 | - let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 304 | - paths.sort(); | ||
| 305 | - for p in paths { | ||
| 306 | - if p.is_dir() && depth > 0 { | ||
| 307 | - bitstreams_in(&p, depth - 1, out); | ||
| 308 | - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { | ||
| 309 | - out.push(p); | ||
| 310 | - } | ||
| 311 | - } | ||
| 312 | - } | ||
| 313 | - let dirs = std::fs::read_dir(&root).expect("fixture directory"); | ||
| 314 | - let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); | ||
| 315 | - dirs.sort(); | ||
| 316 | - dirs.into_iter() | ||
| 317 | - .filter(|d| d.is_dir()) | ||
| 318 | - .filter_map(|d| { | ||
| 319 | - let mut found = Vec::new(); | ||
| 320 | - bitstreams_in(&d, 2, &mut found); | ||
| 321 | - found.into_iter().next() | ||
| 322 | - }) | ||
| 323 | - .collect() | ||
| 324 | -} | ||
| 325 | - | ||
| 326 | -/// Output order from our decoder, picture management only: (POC, AU index). | ||
| 327 | -fn our_order(data: &[u8]) -> Result<Vec<(i32, u32)>, String> { | ||
| 328 | - let mut dec = Decoder::new(); | ||
| 329 | - dec.set_pixel_decode(false); | ||
| 330 | - dec.decode_annex_b(data).map_err(|e| e.to_string())?; | ||
| 331 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 332 | - let mut order = Vec::new(); | ||
| 333 | - while let Some(f) = dec.next_frame() { | ||
| 334 | - order.push((f.poc, f.au_index)); | ||
| 335 | - } | ||
| 336 | - Ok(order) | ||
| 337 | -} | ||
| 338 | - | ||
| 339 | -/// Output order from ffprobe: the access-unit index (by packet position in | ||
| 340 | -/// decode order) of each frame, in display order. | ||
| 341 | -fn ffprobe_order(path: &Path) -> Result<Vec<u32>, String> { | ||
| 342 | - let packets = numbers(&run( | ||
| 343 | - &[ | ||
| 344 | - "-select_streams", | ||
| 345 | - "v:0", | ||
| 346 | - "-show_entries", | ||
| 347 | - "packet=pos", | ||
| 348 | - "-of", | ||
| 349 | - "csv=p=0", | ||
| 350 | - ], | ||
| 351 | - path, | ||
| 352 | - )?); | ||
| 353 | - let frames = numbers(&run( | ||
| 354 | - &[ | ||
| 355 | - "-select_streams", | ||
| 356 | - "v:0", | ||
| 357 | - "-show_entries", | ||
| 358 | - "frame=pkt_pos", | ||
| 359 | - "-of", | ||
| 360 | - "csv=p=0", | ||
| 361 | - ], | ||
| 362 | - path, | ||
| 363 | - )?); | ||
| 364 | - frames | ||
| 365 | - .iter() | ||
| 366 | - .map(|pos| { | ||
| 367 | - packets | ||
| 368 | - .iter() | ||
| 369 | - .position(|p| p == pos) | ||
| 370 | - .map(|i| i as u32) | ||
| 371 | - .ok_or_else(|| format!("frame position {pos} is no packet position")) | ||
| 372 | - }) | ||
| 373 | - .collect() | ||
| 374 | -} | ||
| 375 | - | ||
| 376 | -/// Streams where ffprobe is not the reference: the spec's frame count (from the | ||
| 377 | -/// conformance description) and why ffprobe differs. Our count must equal the spec's. | ||
| 378 | -fn spec_expectation(name: &str) -> Option<(usize, &'static str)> { | ||
| 379 | - match name { | ||
| 380 | - // Unequal luma (10) and chroma (9) bit depth: ffmpeg decodes nothing. | ||
| 381 | - "TSUNEQBD_A_MAIN10_Technicolor_2" => Some((8, "ffmpeg unsupported (unequal bit depths)")), | ||
| 382 | - // Six IDR pictures, each with its own VPS/SPS/PPS and resolution: ffmpeg outputs 2. | ||
| 383 | - "VPSSPSPPS_A_MainConcept_1" => Some((6, "ffmpeg outputs 2")), | ||
| 384 | - _ => None, | ||
| 385 | - } | ||
| 386 | -} | ||
| 387 | - | ||
| 388 | -#[test] | ||
| 389 | -fn conformance_output_order_matches_ffprobe() { | ||
| 390 | - let streams = streams(); | ||
| 391 | - assert!(!streams.is_empty(), "no conformance streams"); | ||
| 392 | - let mut table = String::from("stream\tpictures_out\tffprobe_out\tresult\tdetail\n"); | ||
| 393 | - let mut pass = 0usize; | ||
| 394 | - let mut spec_ok = 0usize; | ||
| 395 | - for path in &streams { | ||
| 396 | - let name = path | ||
| 397 | - .file_stem() | ||
| 398 | - .unwrap_or_default() | ||
| 399 | - .to_string_lossy() | ||
| 400 | - .to_string(); | ||
| 401 | - let data = match std::fs::read(path) { | ||
| 402 | - Ok(d) => d, | ||
| 403 | - Err(e) => { | ||
| 404 | - table.push_str(&format!("{name}\t-\t-\tFAIL\tread: {e}\n")); | ||
| 405 | - continue; | ||
| 406 | - } | ||
| 407 | - }; | ||
| 408 | - let ours = our_order(&data); | ||
| 409 | - let theirs = ffprobe_order(path); | ||
| 410 | - let row = match (ours, theirs) { | ||
| 411 | - (Ok(ours), Ok(theirs)) => { | ||
| 412 | - let our_aus: Vec<u32> = ours.iter().map(|(_, au)| *au).collect(); | ||
| 413 | - let pocs: Vec<String> = ours.iter().take(8).map(|(p, _)| p.to_string()).collect(); | ||
| 414 | - let detail = format!("first POCs {}", pocs.join(",")); | ||
| 415 | - match spec_expectation(&name) { | ||
| 416 | - // The spec's own count is the reference where ffprobe is wrong. | ||
| 417 | - Some((frames, why)) => { | ||
| 418 | - let verdict = if ours.len() == frames { "SPEC" } else { "FAIL" }; | ||
| 419 | - if verdict == "SPEC" { | ||
| 420 | - spec_ok += 1; | ||
| 421 | - } | ||
| 422 | - format!( | ||
| 423 | - "{name}\t{}\t{}\t{verdict}\tspec: {frames} frames, {why}; {detail}\n", | ||
| 424 | - ours.len(), | ||
| 425 | - theirs.len(), | ||
| 426 | - ) | ||
| 427 | - } | ||
| 428 | - None => { | ||
| 429 | - let verdict = if our_aus == theirs { "PASS" } else { "FAIL" }; | ||
| 430 | - if verdict == "PASS" { | ||
| 431 | - pass += 1; | ||
| 432 | - } | ||
| 433 | - format!( | ||
| 434 | - "{name}\t{}\t{}\t{verdict}\t{detail}\n", | ||
| 435 | - ours.len(), | ||
| 436 | - theirs.len(), | ||
| 437 | - ) | ||
| 438 | - } | ||
| 439 | - } | ||
| 440 | - } | ||
| 441 | - (Err(e), _) => format!("{name}\t-\t-\tREFUSED\t{e}\n"), | ||
| 442 | - (_, Err(e)) => format!("{name}\t-\t-\tSKIP\tffprobe: {e}\n"), | ||
| 443 | - }; | ||
| 444 | - table.push_str(&row); | ||
| 445 | - } | ||
| 446 | - match std::env::var("EC_H265_POC_TABLE") { | ||
| 447 | - Ok(path) => std::fs::write(&path, &table).expect("write POC table"), | ||
| 448 | - Err(_) => print!("{table}"), | ||
| 449 | - } | ||
| 450 | - eprintln!( | ||
| 451 | - "POC/output order: {pass}/{} streams PASS, {spec_ok} SPEC (spec frame count, ffprobe differs)", | ||
| 452 | - streams.len() | ||
| 453 | - ); | ||
| 454 | -} | ||
crates/ec-h265/tests/it/dolby_vision_p8.rsdeleted+0 -197
| @@ -1,197 +0,0 @@ | |||
| 1 | -//! Dolby Vision profile 8 layout: the HEVC base layer decodes, and the RPU NAL | ||
| 2 | -//! units (type 62) are ignored. | ||
| 3 | -//! | ||
| 4 | -//! The base layer is generated here with ffmpeg's libx265 from a test pattern, so no | ||
| 5 | -//! copyrighted media is involved. Type 62 NAL units with arbitrary payload are then | ||
| 6 | -//! inserted in front of every VCL NAL unit. ec-h265 must decode the injected stream | ||
| 7 | -//! to exactly the pictures it decodes from the clean one, and ffmpeg must decode the | ||
| 8 | -//! injected stream to the same bytes. | ||
| 9 | - | ||
| 10 | -use ec_h265::Decoder; | ||
| 11 | -use ec_h265::dec::Frame; | ||
| 12 | -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; | ||
| 13 | -use std::path::Path; | ||
| 14 | - | ||
| 15 | -const WIDTH: usize = 352; | ||
| 16 | -const HEIGHT: usize = 288; | ||
| 17 | -const FRAMES: usize = 12; | ||
| 18 | - | ||
| 19 | -/// The base layer: libx265, an IDR every 4 pictures, P pictures in between, no B. | ||
| 20 | -fn encode_base_layer(dir: &Path) -> Result<Vec<u8>, String> { | ||
| 21 | - let out = dir.join("base.hevc"); | ||
| 22 | - let frames = FRAMES.to_string(); | ||
| 23 | - let source = format!("testsrc2=size={WIDTH}x{HEIGHT}:rate=30"); | ||
| 24 | - let status = ec_testkit::ffmpeg() | ||
| 25 | - .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) | ||
| 26 | - .arg(&source) | ||
| 27 | - .arg("-frames:v") | ||
| 28 | - .arg(&frames) | ||
| 29 | - .args([ | ||
| 30 | - "-c:v", "libx265", "-preset", "veryfast", "-pix_fmt", "yuv420p", | ||
| 31 | - ]) | ||
| 32 | - .args([ | ||
| 33 | - "-x265-params", | ||
| 34 | - "keyint=4:min-keyint=4:bframes=0:scenecut=0:log-level=error", | ||
| 35 | - "-f", | ||
| 36 | - "hevc", | ||
| 37 | - ]) | ||
| 38 | - .arg(&out) | ||
| 39 | - .output() | ||
| 40 | - .map_err(|e| e.to_string())?; | ||
| 41 | - if !status.status.success() { | ||
| 42 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 43 | - } | ||
| 44 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 45 | -} | ||
| 46 | - | ||
| 47 | -/// A type 62 NAL unit with arbitrary payload: zero runs, start-code-like bytes and | ||
| 48 | -/// a trailing zero, escaped as a NAL unit must be. `seed` varies it per slice. | ||
| 49 | -fn rpu_nal(seed: u8) -> Vec<u8> { | ||
| 50 | - let rbsp = [ | ||
| 51 | - 0x19, 0x08, 0x00, 0x00, 0x01, seed, 0x00, 0x00, 0x03, 0xff, 0x80, 0x00, | ||
| 52 | - ]; | ||
| 53 | - let mut v = vec![62 << 1, 1]; | ||
| 54 | - escape_rbsp(&rbsp, &mut v); | ||
| 55 | - v | ||
| 56 | -} | ||
| 57 | - | ||
| 58 | -/// The stream with a type 62 NAL unit in front of every VCL NAL unit, each with | ||
| 59 | -/// a four-byte start code. | ||
| 60 | -fn inject_rpu(annex_b: &[u8]) -> Vec<u8> { | ||
| 61 | - let mut out = Vec::with_capacity(annex_b.len() * 2); | ||
| 62 | - let mut slice = 0u8; | ||
| 63 | - for n in split_annex_b(annex_b) { | ||
| 64 | - let mut nal = n.header.to_bytes().to_vec(); | ||
| 65 | - nal.extend_from_slice(n.payload); | ||
| 66 | - if matches!((nal[0] >> 1) & 0x3f, 0..=21) { | ||
| 67 | - out.extend_from_slice(&[0, 0, 0, 1]); | ||
| 68 | - out.extend_from_slice(&rpu_nal(slice)); | ||
| 69 | - slice = slice.wrapping_add(1); | ||
| 70 | - } | ||
| 71 | - out.extend_from_slice(&[0, 0, 0, 1]); | ||
| 72 | - out.extend_from_slice(&nal); | ||
| 73 | - } | ||
| 74 | - out | ||
| 75 | -} | ||
| 76 | - | ||
| 77 | -/// Count of NAL units of `nal_type` in an Annex B stream. | ||
| 78 | -fn count_nal_type(annex_b: &[u8], nal_type: u8) -> usize { | ||
| 79 | - split_annex_b(annex_b) | ||
| 80 | - .iter() | ||
| 81 | - .filter(|n| (n.header.to_bytes()[0] >> 1) & 0x3f == nal_type) | ||
| 82 | - .count() | ||
| 83 | -} | ||
| 84 | - | ||
| 85 | -/// One picture as 4:2:0 bytes, cropped to the conformance window. | ||
| 86 | -fn cropped_yuv(frame: &Frame) -> Vec<u8> { | ||
| 87 | - let pic = &frame.picture; | ||
| 88 | - let win = &frame.window; | ||
| 89 | - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); | ||
| 90 | - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); | ||
| 91 | - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); | ||
| 92 | - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); | ||
| 93 | - let mut out = Vec::new(); | ||
| 94 | - for row in ly0..ly1 { | ||
| 95 | - out.extend( | ||
| 96 | - pic.y[row * pic.width + lx0..row * pic.width + lx1] | ||
| 97 | - .iter() | ||
| 98 | - .map(|&v| v as u8), | ||
| 99 | - ); | ||
| 100 | - } | ||
| 101 | - let cw = pic.width / 2; | ||
| 102 | - for plane in [&pic.cb, &pic.cr] { | ||
| 103 | - for row in cy0..cy1 { | ||
| 104 | - out.extend( | ||
| 105 | - plane[row * cw + cx0..row * cw + cx1] | ||
| 106 | - .iter() | ||
| 107 | - .map(|&v| v as u8), | ||
| 108 | - ); | ||
| 109 | - } | ||
| 110 | - } | ||
| 111 | - out | ||
| 112 | -} | ||
| 113 | - | ||
| 114 | -/// Every picture ec-h265 outputs, as one yuv420p byte string, and the picture count. | ||
| 115 | -fn decode_ec(annex_b: &[u8]) -> Result<(Vec<u8>, usize), String> { | ||
| 116 | - let mut dec = Decoder::new(); | ||
| 117 | - dec.decode_annex_b(annex_b).map_err(|e| e.to_string())?; | ||
| 118 | - dec.flush().map_err(|e| e.to_string())?; | ||
| 119 | - let mut out = Vec::new(); | ||
| 120 | - let mut count = 0; | ||
| 121 | - while let Some(frame) = dec.next_frame() { | ||
| 122 | - out.extend(cropped_yuv(&frame)); | ||
| 123 | - count += 1; | ||
| 124 | - } | ||
| 125 | - Ok((out, count)) | ||
| 126 | -} | ||
| 127 | - | ||
| 128 | -/// Every picture ffmpeg outputs, as yuv420p. | ||
| 129 | -fn decode_ffmpeg(path: &Path, out: &Path) -> Result<Vec<u8>, String> { | ||
| 130 | - let status = ec_testkit::ffmpeg() | ||
| 131 | - .args(["-v", "error", "-y", "-i"]) | ||
| 132 | - .arg(path) | ||
| 133 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 134 | - .arg(out) | ||
| 135 | - .output() | ||
| 136 | - .map_err(|e| e.to_string())?; | ||
| 137 | - if !status.status.success() { | ||
| 138 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 139 | - } | ||
| 140 | - std::fs::read(out).map_err(|e| e.to_string()) | ||
| 141 | -} | ||
| 142 | - | ||
| 143 | -fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> { | ||
| 144 | - a.iter() | ||
| 145 | - .zip(b) | ||
| 146 | - .position(|(x, y)| x != y) | ||
| 147 | - .or_else(|| (a.len() != b.len()).then(|| a.len().min(b.len()))) | ||
| 148 | -} | ||
| 149 | - | ||
| 150 | -#[test] | ||
| 151 | -fn dolby_vision_p8_base_layer_decodes_and_rpu_is_ignored() { | ||
| 152 | - let dir = std::env::temp_dir().join(format!("ec-h265-dvp8-{}", std::process::id())); | ||
| 153 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 154 | - | ||
| 155 | - let clean = encode_base_layer(&dir).expect("libx265 base layer"); | ||
| 156 | - let injected = inject_rpu(&clean); | ||
| 157 | - let vcl = split_annex_b(&clean) | ||
| 158 | - .iter() | ||
| 159 | - .filter(|n| matches!((n.header.to_bytes()[0] >> 1) & 0x3f, 0..=21)) | ||
| 160 | - .count(); | ||
| 161 | - assert_eq!( | ||
| 162 | - count_nal_type(&clean, 62), | ||
| 163 | - 0, | ||
| 164 | - "clean base layer has type 62 NAL units" | ||
| 165 | - ); | ||
| 166 | - assert_eq!( | ||
| 167 | - count_nal_type(&injected, 62), | ||
| 168 | - vcl, | ||
| 169 | - "one type 62 NAL unit per slice" | ||
| 170 | - ); | ||
| 171 | - | ||
| 172 | - let (ec_clean, n_clean) = decode_ec(&clean).expect("ec-h265 decodes the clean base layer"); | ||
| 173 | - let (ec_injected, n_injected) = | ||
| 174 | - decode_ec(&injected).expect("ec-h265 decodes the stream with type 62 NAL units"); | ||
| 175 | - assert_eq!(n_clean, FRAMES, "clean stream picture count"); | ||
| 176 | - assert_eq!(n_injected, FRAMES, "injected stream picture count"); | ||
| 177 | - let frame_bytes = WIDTH * HEIGHT * 3 / 2; | ||
| 178 | - assert_eq!(ec_clean.len(), FRAMES * frame_bytes); | ||
| 179 | - if let Some(at) = first_difference(&ec_clean, &ec_injected) { | ||
| 180 | - panic!("type 62 NAL units changed ec-h265's output at byte {at}"); | ||
| 181 | - } | ||
| 182 | - | ||
| 183 | - let injected_path = dir.join("dv-p8.hevc"); | ||
| 184 | - std::fs::write(&injected_path, &injected).expect("write injected stream"); | ||
| 185 | - let ffmpeg = decode_ffmpeg(&injected_path, &dir.join("ffmpeg.yuv")) | ||
| 186 | - .expect("ffmpeg decodes the injected stream"); | ||
| 187 | - assert_eq!( | ||
| 188 | - ffmpeg.len(), | ||
| 189 | - ec_injected.len(), | ||
| 190 | - "ffmpeg picture bytes differ from ec-h265's" | ||
| 191 | - ); | ||
| 192 | - if let Some(at) = first_difference(&ec_injected, &ffmpeg) { | ||
| 193 | - panic!("ec-h265 and ffmpeg differ on the injected stream at byte {at}"); | ||
| 194 | - } | ||
| 195 | - | ||
| 196 | - let _ = std::fs::remove_dir_all(&dir); | ||
| 197 | -} | ||
crates/ec-h265/tests/it/encode.rsdeleted+0 -922
| @@ -1,922 +0,0 @@ | |||
| 1 | -//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched | ||
| 2 | -//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`. | ||
| 3 | -//! | ||
| 4 | -//! Both encoders code the same synthetic 352x288 24-picture clip, both are read | ||
| 5 | -//! the same way — on ffmpeg's decode of the stream, not on either encoder's | ||
| 6 | -//! own reconstruction — and x265's psychovisual and adaptive tools are off so | ||
| 7 | -//! the comparison is at matched features, not at matched marketing. | ||
| 8 | - | ||
| 9 | -use crate::common::{pin_loud, pin_or_bail}; | ||
| 10 | -use ec_core::frame::VideoFrame; | ||
| 11 | -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; | ||
| 12 | - | ||
| 13 | -/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. | ||
| 14 | -type Planes = (Vec<u8>, Vec<u8>, Vec<u8>); | ||
| 15 | - | ||
| 16 | -/// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the | ||
| 17 | -/// measured value with 0.15 dB of room for platform noise, so the advantage can | ||
| 18 | -/// shrink but not grow unnoticed; it is not a claim that the number is fine. | ||
| 19 | -/// | ||
| 20 | -/// Measured +2.507 dB luma / +3.238 dB YUV at `rdo_candidates: 5` (352x288, | ||
| 21 | -/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder | ||
| 22 | -/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through | ||
| 23 | -/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a | ||
| 24 | -/// smooth-gradient result: it does NOT hold on real content, where our | ||
| 25 | -/// encoder is no leaner than x265 at matched QP (the probe measures a shift of | ||
| 26 | -/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after | ||
| 27 | -/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides: | ||
| 28 | -/// • 3840x1608 film: -0.685 dB luma / -0.703 dB YUV | ||
| 29 | -/// • 1138x640 web clip: -0.507 dB luma / -0.556 dB YUV | ||
| 30 | -/// • 2560x1440 screen capture: -2.465 dB luma / -2.360 dB YUV | ||
| 31 | -/// • 1080p phone clip: -0.366 dB luma / -0.387 dB YUV | ||
| 32 | -/// Those two are the real gap to close; the synthetic number only guards | ||
| 33 | -/// against regression on a clip whose content is pinned. | ||
| 34 | -/// | ||
| 35 | -/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; | ||
| 36 | -/// that number was meaningless because the two curves' bitrate ranges did not | ||
| 37 | -/// overlap (50% extrapolation on our side) — a fixed QP offset could not | ||
| 38 | -/// bridge encoders whose relative leanness varies with content. The shallow | ||
| 39 | -/// all-intra rate-quality slope is genuine content behaviour (x264 forced | ||
| 40 | -/// all-intra shows the same shape); the fix is to auto-align the ladders from | ||
| 41 | -/// a probe encode, not to change x265's rate control. | ||
| 42 | -const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; | ||
| 43 | - | ||
| 44 | -/// A synthetic source with real structure: smooth gradients, a band of | ||
| 45 | -/// sinusoidal texture and a translating box, so prediction matters — the half | ||
| 46 | -/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip` | ||
| 47 | -/// (minus the `view()` method this encoder's `encode_idr_planes` does not | ||
| 48 | -/// need). | ||
| 49 | -struct Clip { | ||
| 50 | - w: usize, | ||
| 51 | - h: usize, | ||
| 52 | - y: Vec<u8>, | ||
| 53 | - u: Vec<u8>, | ||
| 54 | - v: Vec<u8>, | ||
| 55 | -} | ||
| 56 | - | ||
| 57 | -impl Clip { | ||
| 58 | - fn new(w: usize, h: usize) -> Clip { | ||
| 59 | - Clip { | ||
| 60 | - w, | ||
| 61 | - h, | ||
| 62 | - y: vec![0; w * h], | ||
| 63 | - u: vec![0; w / 2 * h / 2], | ||
| 64 | - v: vec![0; w / 2 * h / 2], | ||
| 65 | - } | ||
| 66 | - } | ||
| 67 | - | ||
| 68 | - /// Frame `t` without a per-sample noise field: smooth gradients, a band of | ||
| 69 | - /// sinusoidal texture and a box translating by whole and sub-sample | ||
| 70 | - /// amounts. Content where prediction matters, not where residual is | ||
| 71 | - /// incompressible. | ||
| 72 | - fn render_smooth(&mut self, t: usize) { | ||
| 73 | - let (w, h) = (self.w, self.h); | ||
| 74 | - let ft = t as f64; | ||
| 75 | - for y in 0..h { | ||
| 76 | - for x in 0..w { | ||
| 77 | - let (fx, fy) = (x as f64, y as f64); | ||
| 78 | - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; | ||
| 79 | - let texture = if y > h / 3 && y < 2 * h / 3 { | ||
| 80 | - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) | ||
| 81 | - } else { | ||
| 82 | - 0.0 | ||
| 83 | - }; | ||
| 84 | - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); | ||
| 85 | - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; | ||
| 86 | - let v = if inside { | ||
| 87 | - 196.0 - texture * 0.5 | ||
| 88 | - } else { | ||
| 89 | - 40.0 + (ramp % 90.0).abs() + texture | ||
| 90 | - }; | ||
| 91 | - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; | ||
| 92 | - } | ||
| 93 | - } | ||
| 94 | - for y in 0..h / 2 { | ||
| 95 | - for x in 0..w / 2 { | ||
| 96 | - let (fx, fy) = (x as f64, y as f64); | ||
| 97 | - self.u[y * (w / 2) + x] = | ||
| 98 | - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; | ||
| 99 | - self.v[y * (w / 2) + x] = | ||
| 100 | - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; | ||
| 101 | - } | ||
| 102 | - } | ||
| 103 | - } | ||
| 104 | -} | ||
| 105 | - | ||
| 106 | -/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction. | ||
| 107 | -fn planes_of(frame: &VideoFrame) -> Planes { | ||
| 108 | - let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 109 | - let mut out = Vec::new(); | ||
| 110 | - for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] | ||
| 111 | - .into_iter() | ||
| 112 | - .enumerate() | ||
| 113 | - { | ||
| 114 | - let plane = &frame.planes[i]; | ||
| 115 | - let mut buf = Vec::with_capacity(pw * ph); | ||
| 116 | - for row in 0..ph { | ||
| 117 | - buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); | ||
| 118 | - } | ||
| 119 | - out.push(buf); | ||
| 120 | - } | ||
| 121 | - let v = out.pop().unwrap(); | ||
| 122 | - let u = out.pop().unwrap(); | ||
| 123 | - let y = out.pop().unwrap(); | ||
| 124 | - (y, u, v) | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -/// Mean squared error between two equal-length planes. | ||
| 128 | -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { | ||
| 129 | - a.iter() | ||
| 130 | - .zip(b) | ||
| 131 | - .map(|(&x, &y)| { | ||
| 132 | - let d = f64::from(x) - f64::from(y); | ||
| 133 | - d * d | ||
| 134 | - }) | ||
| 135 | - .sum::<f64>() | ||
| 136 | - / a.len() as f64 | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | -/// PSNR over all three planes, pooled by sample count the way x265 reports it: | ||
| 140 | -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number | ||
| 141 | -/// rewards an encoder for throwing chroma away, so any decision that can move | ||
| 142 | -/// chroma bits is read here instead. | ||
| 143 | -fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { | ||
| 144 | - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); | ||
| 145 | - let sse = | ||
| 146 | - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; | ||
| 147 | - let mse = sse / (n_y + 2.0 * n_c); | ||
| 148 | - if mse == 0.0 { | ||
| 149 | - 99.0 | ||
| 150 | - } else { | ||
| 151 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 152 | - } | ||
| 153 | -} | ||
| 154 | - | ||
| 155 | -fn psnr(a: &[u8], b: &[u8]) -> f64 { | ||
| 156 | - let mse: f64 = a | ||
| 157 | - .iter() | ||
| 158 | - .zip(b) | ||
| 159 | - .map(|(&x, &y)| { | ||
| 160 | - let d = f64::from(x) - f64::from(y); | ||
| 161 | - d * d | ||
| 162 | - }) | ||
| 163 | - .sum::<f64>() | ||
| 164 | - / a.len() as f64; | ||
| 165 | - if mse == 0.0 { | ||
| 166 | - 99.0 | ||
| 167 | - } else { | ||
| 168 | - 10.0 * (255.0 * 255.0 / mse).log10() | ||
| 169 | - } | ||
| 170 | -} | ||
| 171 | - | ||
| 172 | -#[allow(clippy::needless_range_loop)] | ||
| 173 | -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { | ||
| 174 | - let mut a = [[0.0; 5]; 4]; | ||
| 175 | - for i in 0..4 { | ||
| 176 | - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; | ||
| 177 | - } | ||
| 178 | - for col in 0..4 { | ||
| 179 | - let mut pivot = col; | ||
| 180 | - for row in col + 1..4 { | ||
| 181 | - if a[row][col].abs() > a[pivot][col].abs() { | ||
| 182 | - pivot = row; | ||
| 183 | - } | ||
| 184 | - } | ||
| 185 | - a.swap(col, pivot); | ||
| 186 | - let div = a[col][col]; | ||
| 187 | - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); | ||
| 188 | - for j in col..5 { | ||
| 189 | - a[col][j] /= div; | ||
| 190 | - } | ||
| 191 | - for row in 0..4 { | ||
| 192 | - if row == col { | ||
| 193 | - continue; | ||
| 194 | - } | ||
| 195 | - let f = a[row][col]; | ||
| 196 | - for j in col..5 { | ||
| 197 | - a[row][j] -= f * a[col][j]; | ||
| 198 | - } | ||
| 199 | - } | ||
| 200 | - } | ||
| 201 | - [a[0][4], a[1][4], a[2][4], a[3][4]] | ||
| 202 | -} | ||
| 203 | - | ||
| 204 | -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { | ||
| 205 | - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 | ||
| 206 | -} | ||
| 207 | - | ||
| 208 | -/// BD-PSNR: average PSNR difference between two rate-quality curves over a | ||
| 209 | -/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one | ||
| 210 | -/// departure: the integration range is the *union* of the two curves' bitrate | ||
| 211 | -/// extents, not their intersection. | ||
| 212 | -/// | ||
| 213 | -/// The h264 gate's encoders land in the same bitrate band at the same QP, so | ||
| 214 | -/// the intersection is non-empty and the standard Bjøntegaard cubic integral | ||
| 215 | -/// over it is well defined. Our h265 encoder's bitrate at matched QP can be | ||
| 216 | -/// leaner or fatter than x265's depending on content, so the QP-ladder shift | ||
| 217 | -/// is measured from a probe encode, not fixed — the union range is kept (not | ||
| 218 | -/// clipped to the intersection) so the extrapolation share can be measured: | ||
| 219 | -/// if either curve is extrapolated over more than 20% of the range, the test | ||
| 220 | -/// fails with a named message instead of reporting a BD number that is a cubic | ||
| 221 | -/// guess, not a measurement. The extrapolation shares are returned alongside | ||
| 222 | -/// the number. | ||
| 223 | -/// | ||
| 224 | -/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the | ||
| 225 | -/// fraction of the integration range that each curve's measured bitrate span | ||
| 226 | -/// does not cover (0 = fully measured, 1 = entirely extrapolated). | ||
| 227 | -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) { | ||
| 228 | - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); | ||
| 229 | - let ys_candidate = std::array::from_fn(|i| candidate[i].1); | ||
| 230 | - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); | ||
| 231 | - let ys_anchor = std::array::from_fn(|i| anchor[i].1); | ||
| 232 | - // Union, not intersection: see the doc comment above. | ||
| 233 | - let lo = xs_candidate | ||
| 234 | - .iter() | ||
| 235 | - .copied() | ||
| 236 | - .fold(f64::INFINITY, f64::min) | ||
| 237 | - .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); | ||
| 238 | - let hi = xs_candidate | ||
| 239 | - .iter() | ||
| 240 | - .copied() | ||
| 241 | - .fold(f64::NEG_INFINITY, f64::max) | ||
| 242 | - .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); | ||
| 243 | - let c_candidate = cubic_fit(xs_candidate, ys_candidate); | ||
| 244 | - let c_anchor = cubic_fit(xs_anchor, ys_anchor); | ||
| 245 | - let (cand_lo, cand_hi) = ( | ||
| 246 | - xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 247 | - xs_candidate | ||
| 248 | - .iter() | ||
| 249 | - .copied() | ||
| 250 | - .fold(f64::NEG_INFINITY, f64::max), | ||
| 251 | - ); | ||
| 252 | - let (anc_lo, anc_hi) = ( | ||
| 253 | - xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), | ||
| 254 | - xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), | ||
| 255 | - ); | ||
| 256 | - let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); | ||
| 257 | - let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); | ||
| 258 | - eprintln!( | ||
| 259 | - " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" | ||
| 260 | - ); | ||
| 261 | - let bd = (cubic_integral(c_candidate, hi) | ||
| 262 | - - cubic_integral(c_candidate, lo) | ||
| 263 | - - cubic_integral(c_anchor, hi) | ||
| 264 | - + cubic_integral(c_anchor, lo)) | ||
| 265 | - / (hi - lo); | ||
| 266 | - (bd, cand_extrap, anc_extrap) | ||
| 267 | -} | ||
| 268 | - | ||
| 269 | -fn have_x265() -> bool { | ||
| 270 | - ec_testkit::ffmpeg() | ||
| 271 | - .args(["-v", "error", "-hide_banner", "-encoders"]) | ||
| 272 | - .output() | ||
| 273 | - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) | ||
| 274 | -} | ||
| 275 | - | ||
| 276 | -#[cfg(unix)] | ||
| 277 | -#[test] | ||
| 278 | -fn pin_loud_reds_on_an_ok_but_short_write() { | ||
| 279 | - // The shape the two sites above left open: a write that reports success and | ||
| 280 | - // leaves a file of a different length. A symlink to /dev/null accepts every | ||
| 281 | - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- | ||
| 282 | - // a stream path, silently empty. | ||
| 283 | - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id())); | ||
| 284 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 285 | - let path = dir.join("ok-but-short.265"); | ||
| 286 | - let _ = std::fs::remove_file(&path); | ||
| 287 | - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); | ||
| 288 | - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); | ||
| 289 | - assert!(why.contains(&path.display().to_string()), "{why}"); | ||
| 290 | - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); | ||
| 291 | - std::fs::remove_file(&path).ok(); | ||
| 292 | - | ||
| 293 | - // The control: the same call on a real file succeeds and leaves every byte. | ||
| 294 | - let good = dir.join("whole.265"); | ||
| 295 | - let bytes = vec![7u8; 1234]; | ||
| 296 | - pin_loud("control", &good, &bytes).expect("a whole write is not short"); | ||
| 297 | - assert_eq!(std::fs::read(&good).expect("read back"), bytes); | ||
| 298 | - std::fs::remove_file(&good).ok(); | ||
| 299 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -#[cfg(unix)] | ||
| 303 | -#[test] | ||
| 304 | -fn pin_loud_reports_what_landed_under_a_size_cap() { | ||
| 305 | - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores | ||
| 306 | - // everything up to the cap and only then returns EFBIG. The line must carry | ||
| 307 | - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count | ||
| 308 | - // the writer confirmed, which is zero. | ||
| 309 | - use std::process::Command; | ||
| 310 | - let Ok(exe) = std::env::current_exe() else { | ||
| 311 | - return; | ||
| 312 | - }; | ||
| 313 | - // SIGXFSZ's default action would kill the child before it can print; | ||
| 314 | - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. | ||
| 315 | - let script = format!( | ||
| 316 | - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", | ||
| 317 | - exe.display() | ||
| 318 | - ); | ||
| 319 | - let out = Command::new("sh") | ||
| 320 | - .args(["-c", &script]) | ||
| 321 | - .env("EC_PINLOUD_CHILD", "1") | ||
| 322 | - .output() | ||
| 323 | - .expect("run the capped child"); | ||
| 324 | - let text = format!( | ||
| 325 | - "{}{}", | ||
| 326 | - String::from_utf8_lossy(&out.stdout), | ||
| 327 | - String::from_utf8_lossy(&out.stderr) | ||
| 328 | - ); | ||
| 329 | - assert!(!out.status.success(), "the capped write must fail: {text}"); | ||
| 330 | - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); | ||
| 331 | - assert!( | ||
| 332 | - text.contains("EFBIG") || text.contains("File too large"), | ||
| 333 | - "{text}" | ||
| 334 | - ); | ||
| 335 | -} | ||
| 336 | - | ||
| 337 | -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under | ||
| 338 | -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails | ||
| 339 | -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. | ||
| 340 | -#[test] | ||
| 341 | -fn pin_loud_cap_child() { | ||
| 342 | - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { | ||
| 343 | - return; | ||
| 344 | - } | ||
| 345 | - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id())); | ||
| 346 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 347 | - let path = dir.join("capped.265"); | ||
| 348 | - let why = | ||
| 349 | - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); | ||
| 350 | - std::fs::remove_file(&path).ok(); | ||
| 351 | - std::fs::remove_dir_all(&dir).ok(); | ||
| 352 | - panic!("{why}"); | ||
| 353 | -} | ||
| 354 | - | ||
| 355 | -/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture. | ||
| 356 | -fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option<Vec<Planes>> { | ||
| 357 | - let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); | ||
| 358 | - std::fs::create_dir_all(&dir).ok()?; | ||
| 359 | - let path = dir.join(format!("s{}.265", stream.len())); | ||
| 360 | - pin_or_bail("ffmpeg_decode", &path, stream)?; | ||
| 361 | - let out = ec_testkit::ffmpeg() | ||
| 362 | - .args(["-v", "error"]) | ||
| 363 | - .arg("-i") | ||
| 364 | - .arg(&path) | ||
| 365 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) | ||
| 366 | - .output() | ||
| 367 | - .ok()?; | ||
| 368 | - let _ = std::fs::remove_file(&path); | ||
| 369 | - if !out.status.success() { | ||
| 370 | - eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); | ||
| 371 | - return None; | ||
| 372 | - } | ||
| 373 | - let frame = w * h * 3 / 2; | ||
| 374 | - if frame == 0 || out.stdout.len() % frame != 0 { | ||
| 375 | - eprintln!( | ||
| 376 | - "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", | ||
| 377 | - out.stdout.len() | ||
| 378 | - ); | ||
| 379 | - return None; | ||
| 380 | - } | ||
| 381 | - Some( | ||
| 382 | - out.stdout | ||
| 383 | - .chunks(frame) | ||
| 384 | - .map(|f| { | ||
| 385 | - let (y, rest) = f.split_at(w * h); | ||
| 386 | - let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 387 | - (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 388 | - }) | ||
| 389 | - .collect(), | ||
| 390 | - ) | ||
| 391 | -} | ||
| 392 | - | ||
| 393 | -/// Encode raw I420 pictures with x265 at constant QP, matched to what this | ||
| 394 | -/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut | ||
| 395 | -/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off, | ||
| 396 | -/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU | ||
| 397 | -/// depth x265 allows (1, the closest it has to our | ||
| 398 | -/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so | ||
| 399 | -/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B | ||
| 400 | -/// stream. | ||
| 401 | -fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec<u8>> { | ||
| 402 | - let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); | ||
| 403 | - std::fs::create_dir_all(&dir).ok()?; | ||
| 404 | - let raw = dir.join(format!("in-q{qp}.yuv")); | ||
| 405 | - let out = dir.join(format!("out-q{qp}.265")); | ||
| 406 | - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); | ||
| 407 | - for (y, u, v) in sources { | ||
| 408 | - buf.extend_from_slice(y); | ||
| 409 | - buf.extend_from_slice(u); | ||
| 410 | - buf.extend_from_slice(v); | ||
| 411 | - } | ||
| 412 | - pin_or_bail("x265_encode_qp", &raw, &buf)?; | ||
| 413 | - // The param list is the h264 gate's x264 list translated to x265's option | ||
| 414 | - // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off, | ||
| 415 | - // plus the in-loop filters x265 adds and x264 does not have (no-sao, | ||
| 416 | - // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits | ||
| 417 | - // the same way ours does. The quantiser goes inside the param string as | ||
| 418 | - // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce | ||
| 419 | - // byte-identical streams, so the `rc=cqp:` prefix is unnecessary. | ||
| 420 | - // EC_H265_X265_PARAMS appends to attribute a single feature the same way | ||
| 421 | - // EC_H264_X264_PARAMS does. | ||
| 422 | - let params = format!( | ||
| 423 | - "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\ | ||
| 424 | - aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ | ||
| 425 | - pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}", | ||
| 426 | - // x265 deblocks by default; `no-deblock` matches an encoder that does | ||
| 427 | - // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter. | ||
| 428 | - deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") { | ||
| 429 | - "" | ||
| 430 | - } else { | ||
| 431 | - "no-deblock:" | ||
| 432 | - }, | ||
| 433 | - extra = match std::env::var("EC_H265_X265_PARAMS") { | ||
| 434 | - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => | ||
| 435 | - format!(":{}", extra.trim().trim_matches(':')), | ||
| 436 | - _ => String::new(), | ||
| 437 | - } | ||
| 438 | - ); | ||
| 439 | - let status = ec_testkit::ffmpeg() | ||
| 440 | - .args(["-v", "error", "-y"]) | ||
| 441 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 442 | - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) | ||
| 443 | - .arg("-i") | ||
| 444 | - .arg(&raw) | ||
| 445 | - .args(["-c:v", "libx265", "-preset", "medium"]) | ||
| 446 | - .args(["-x265-params", ¶ms]) | ||
| 447 | - .args(["-f", "hevc"]) | ||
| 448 | - .arg(&out) | ||
| 449 | - .status() | ||
| 450 | - .ok()?; | ||
| 451 | - let _ = std::fs::remove_file(&raw); | ||
| 452 | - if !status.success() { | ||
| 453 | - return None; | ||
| 454 | - } | ||
| 455 | - let stream = std::fs::read(&out).ok(); | ||
| 456 | - let _ = std::fs::remove_file(&out); | ||
| 457 | - stream | ||
| 458 | -} | ||
| 459 | - | ||
| 460 | -/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored | ||
| 461 | -/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a | ||
| 462 | -/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the | ||
| 463 | -/// cubic fit interpolates instead of extrapolating — regardless of whether | ||
| 464 | -/// our encoder is leaner or fatter than x265 at matched QP on the content at | ||
| 465 | -/// hand. Runs on the synthetic clip by default, so the number cannot rot | ||
| 466 | -/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the | ||
| 467 | -/// same thing on real content. | ||
| 468 | -/// | ||
| 469 | -/// Both curves are (bits, luma PSNR against the same source pictures), and | ||
| 470 | -/// both are measured on ffmpeg's decode of the stream rather than on an | ||
| 471 | -/// encoder's own reconstruction, so the two halves are read the same way. | ||
| 472 | -/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each | ||
| 473 | -/// chroma 1 for 4:2:0), the way x265 reports it. | ||
| 474 | -/// | ||
| 475 | -/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture | ||
| 476 | -/// EC_H265_CLIP=<file> cargo test --release -p ec-h265 --test encode \ | ||
| 477 | -/// bd_psnr_vs_x265 -- --nocapture | ||
| 478 | -#[test] | ||
| 479 | -fn bd_psnr_vs_x265() { | ||
| 480 | - assert!(have_x265(), "the pinned ffmpeg has no libx265"); | ||
| 481 | - let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { | ||
| 482 | - Some(path) => clip_sources(&path, 24), | ||
| 483 | - None => { | ||
| 484 | - let (w, h, frames) = (352, 288, 24); | ||
| 485 | - let mut clip = Clip::new(w, h); | ||
| 486 | - let mut sources = Vec::with_capacity(frames); | ||
| 487 | - for t in 0..frames { | ||
| 488 | - clip.render_smooth(t); | ||
| 489 | - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); | ||
| 490 | - } | ||
| 491 | - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); | ||
| 492 | - (w, h, sources) | ||
| 493 | - } | ||
| 494 | - }; | ||
| 495 | - | ||
| 496 | - let ours = |qp: i32| { | ||
| 497 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 498 | - cfg.rate_control = RateControl::ConstantQp(qp); | ||
| 499 | - cfg.keep_recon = true; | ||
| 500 | - cfg.threads = 0; | ||
| 501 | - // Ablation knob: how many SATD survivors reach the full rate-distortion | ||
| 502 | - // trial in the luma mode search. The shipped default is 5. | ||
| 503 | - if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { | ||
| 504 | - cfg.chroma_mode_search = v != "0"; | ||
| 505 | - } | ||
| 506 | - if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { | ||
| 507 | - cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); | ||
| 508 | - } | ||
| 509 | - if let Ok(v) = std::env::var("EC_H265_SDH") { | ||
| 510 | - cfg.sign_hiding = v != "0"; | ||
| 511 | - } | ||
| 512 | - if let Ok(v) = std::env::var("EC_H265_RDOQ") { | ||
| 513 | - cfg.rdoq = v != "0"; | ||
| 514 | - } | ||
| 515 | - if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") { | ||
| 516 | - cfg.rdoq_estimate = v != "0"; | ||
| 517 | - } | ||
| 518 | - if let Ok(v) = std::env::var("EC_H265_TSKIP") { | ||
| 519 | - cfg.transform_skip = match v.as_str() { | ||
| 520 | - "0" => TransformSkip::Off, | ||
| 521 | - "always" => TransformSkip::AlwaysFor4x4, | ||
| 522 | - _ => TransformSkip::Rd, | ||
| 523 | - }; | ||
| 524 | - } | ||
| 525 | - if let Ok(v) = std::env::var("EC_H265_NXN") { | ||
| 526 | - cfg.intra_nxn = v != "0"; | ||
| 527 | - } | ||
| 528 | - if let Ok(v) = std::env::var("EC_H265_CTB") { | ||
| 529 | - cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); | ||
| 530 | - } | ||
| 531 | - if let Ok(v) = std::env::var("EC_H265_CU64") { | ||
| 532 | - cfg.cu64 = v != "0"; | ||
| 533 | - } | ||
| 534 | - if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { | ||
| 535 | - cfg.deblock = v != "0"; | ||
| 536 | - } | ||
| 537 | - if let Ok(v) = std::env::var("EC_H265_RQT") { | ||
| 538 | - cfg.rqt = v != "0"; | ||
| 539 | - } | ||
| 540 | - if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { | ||
| 541 | - cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); | ||
| 542 | - } | ||
| 543 | - let enc = Encoder::new(cfg).expect("encoder"); | ||
| 544 | - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); | ||
| 545 | - for (y, u, v) in &sources { | ||
| 546 | - let coded = enc | ||
| 547 | - .encode_idr_planes(y, w, u, w / 2, v, w / 2) | ||
| 548 | - .expect("encode"); | ||
| 549 | - stream.extend_from_slice(&coded.au); | ||
| 550 | - let recon = coded.recon.as_ref().expect("reconstruction"); | ||
| 551 | - let (ry, _ru, _rv) = planes_of(recon); | ||
| 552 | - sum_recon += psnr(y, &ry); | ||
| 553 | - } | ||
| 554 | - // Measured the same way x265 is: on what a decoder shows, not on the | ||
| 555 | - // encoder's own reconstruction. The two are printed together because a | ||
| 556 | - // gap between them is a bug in one of the halves, not a rate-quality | ||
| 557 | - // result. | ||
| 558 | - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); | ||
| 559 | - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); | ||
| 560 | - let n = sources.len() as f64; | ||
| 561 | - let sum: f64 = sources | ||
| 562 | - .iter() | ||
| 563 | - .zip(&decoded) | ||
| 564 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 565 | - .sum(); | ||
| 566 | - let sum_yuv: f64 = sources | ||
| 567 | - .iter() | ||
| 568 | - .zip(&decoded) | ||
| 569 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 570 | - .sum(); | ||
| 571 | - let (sum_u, sum_v) = ( | ||
| 572 | - sources | ||
| 573 | - .iter() | ||
| 574 | - .zip(&decoded) | ||
| 575 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 576 | - .sum::<f64>(), | ||
| 577 | - sources | ||
| 578 | - .iter() | ||
| 579 | - .zip(&decoded) | ||
| 580 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 581 | - .sum::<f64>(), | ||
| 582 | - ); | ||
| 583 | - eprintln!( | ||
| 584 | - " ours qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 585 | - sum_u / n, | ||
| 586 | - sum_v / n | ||
| 587 | - ); | ||
| 588 | - let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); | ||
| 589 | - assert!( | ||
| 590 | - (decoded_psnr - recon_psnr).abs() < 0.05, | ||
| 591 | - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ | ||
| 592 | - stream decodes to {decoded_psnr:.2} dB" | ||
| 593 | - ); | ||
| 594 | - ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) | ||
| 595 | - }; | ||
| 596 | - let x265 = |qp: i32| { | ||
| 597 | - let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); | ||
| 598 | - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); | ||
| 599 | - assert_eq!( | ||
| 600 | - decoded.len(), | ||
| 601 | - sources.len(), | ||
| 602 | - "x265 returned {} pictures for {} sources", | ||
| 603 | - decoded.len(), | ||
| 604 | - sources.len() | ||
| 605 | - ); | ||
| 606 | - let n = sources.len() as f64; | ||
| 607 | - let sum: f64 = sources | ||
| 608 | - .iter() | ||
| 609 | - .zip(&decoded) | ||
| 610 | - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) | ||
| 611 | - .sum(); | ||
| 612 | - let sum_yuv: f64 = sources | ||
| 613 | - .iter() | ||
| 614 | - .zip(&decoded) | ||
| 615 | - .map(|(s, d)| psnr_yuv(s, d)) | ||
| 616 | - .sum(); | ||
| 617 | - eprintln!( | ||
| 618 | - " x265 qp {qp}: u {:.2} dB v {:.2} dB", | ||
| 619 | - sources | ||
| 620 | - .iter() | ||
| 621 | - .zip(&decoded) | ||
| 622 | - .map(|(s, d)| psnr(&s.1, &d.1)) | ||
| 623 | - .sum::<f64>() | ||
| 624 | - / n, | ||
| 625 | - sources | ||
| 626 | - .iter() | ||
| 627 | - .zip(&decoded) | ||
| 628 | - .map(|(s, d)| psnr(&s.2, &d.2)) | ||
| 629 | - .sum::<f64>() | ||
| 630 | - / n | ||
| 631 | - ); | ||
| 632 | - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) | ||
| 633 | - }; | ||
| 634 | - | ||
| 635 | - // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP | ||
| 636 | - // delta measured from a single probe encode, not a constant: both sides | ||
| 637 | - // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP | ||
| 638 | - // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that | ||
| 639 | - // shift. If the extrapolation share still exceeds 20% after measuring, the | ||
| 640 | - // shift is re-estimated from the geometric-mean bit ratio of the two full | ||
| 641 | - // curves and the ladder is rebuilt; once the rates match and the curves | ||
| 642 | - // still do not meet, our ladder is drawn in towards its own centre until | ||
| 643 | - // its bitrate range fits inside the anchor's — at most 8 alignment rounds | ||
| 644 | - // before the existing panic fires. | ||
| 645 | - const EXTRAP_LIMIT: f64 = 0.20; | ||
| 646 | - let x265_qps = [22, 26, 30, 34]; | ||
| 647 | - let probe_qp = 26; | ||
| 648 | - | ||
| 649 | - // Probe both encoders at QP 26 to measure the bit ratio. | ||
| 650 | - let probe_ours = ours(probe_qp); | ||
| 651 | - let probe_x265 = x265(probe_qp); | ||
| 652 | - // A sample window with nothing in it (a film's black head, a fade) codes | ||
| 653 | - // to a handful of bits and decodes back to the source exactly, so every | ||
| 654 | - // point on both curves sits at the PSNR cap and the BD number is a flat | ||
| 655 | - // +0.000 that looks like a measurement. Refuse it by name. | ||
| 656 | - const FLAT_WINDOW_DB: f64 = 90.0; | ||
| 657 | - assert!( | ||
| 658 | - probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB, | ||
| 659 | - "the sample window is flat — both encoders reach the PSNR cap on it \ | ||
| 660 | - (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \ | ||
| 661 | - or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it", | ||
| 662 | - probe_ours.1, | ||
| 663 | - probe_x265.1, | ||
| 664 | - ); | ||
| 665 | - let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; | ||
| 666 | - eprintln!( | ||
| 667 | - "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", | ||
| 668 | - probe_ours.0 / 1e6, | ||
| 669 | - probe_x265.0 / 1e6, | ||
| 670 | - ); | ||
| 671 | - | ||
| 672 | - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { | ||
| 673 | - v.iter() | ||
| 674 | - .map(|&(b, p, y)| (b, if luma { p } else { y })) | ||
| 675 | - .collect() | ||
| 676 | - }; | ||
| 677 | - | ||
| 678 | - // x265 ladder is fixed; reuse the probe for its QP-26 point. | ||
| 679 | - let theirs: Vec<(f64, f64, f64)> = x265_qps | ||
| 680 | - .iter() | ||
| 681 | - .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) | ||
| 682 | - .collect(); | ||
| 683 | - | ||
| 684 | - let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); | ||
| 685 | - let qps_str = |qs: &[i32; 4]| { | ||
| 686 | - qs.iter() | ||
| 687 | - .map(|q| q.to_string()) | ||
| 688 | - .collect::<Vec<_>>() | ||
| 689 | - .join("/") | ||
| 690 | - }; | ||
| 691 | - | ||
| 692 | - #[allow(unused_assignments)] | ||
| 693 | - let ( | ||
| 694 | - mut bd, | ||
| 695 | - mut bd_yuv, | ||
| 696 | - mut cand_extrap, | ||
| 697 | - mut anc_extrap, | ||
| 698 | - mut cand_extrap_yuv, | ||
| 699 | - mut anc_extrap_yuv, | ||
| 700 | - ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); | ||
| 701 | - let mut mine: Vec<(f64, f64, f64)>; | ||
| 702 | - let mut our_qps: [i32; 4]; | ||
| 703 | - // How wide our QP ladder is against the anchor's, as a fraction of its | ||
| 704 | - // spacing: one encoder can answer a QP step with far more bitrate than the | ||
| 705 | - // other, and a BD number needs both curves over the same range. | ||
| 706 | - let mut spread = 1.0_f64; | ||
| 707 | - | ||
| 708 | - for round in 0..=8u32 { | ||
| 709 | - our_qps = x265_qps.map(|q| { | ||
| 710 | - let centre = f64::from(probe_qp + shift); | ||
| 711 | - let offset = f64::from(q - probe_qp) * spread; | ||
| 712 | - ((centre + offset).round() as i32).clamp(1, 45) | ||
| 713 | - }); | ||
| 714 | - let mut distinct = our_qps; | ||
| 715 | - distinct.sort_unstable(); | ||
| 716 | - let collapsed = distinct.windows(2).any(|w| w[0] == w[1]); | ||
| 717 | - assert!( | ||
| 718 | - !collapsed, | ||
| 719 | - "our QP ladder collapsed to {:?}: the shift has pushed it into the \ | ||
| 720 | - qp floor, so two points share an x and the cubic has no unique fit", | ||
| 721 | - our_qps, | ||
| 722 | - ); | ||
| 723 | - mine = our_qps | ||
| 724 | - .iter() | ||
| 725 | - .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) | ||
| 726 | - .collect(); | ||
| 727 | - for (i, &qp) in our_qps.iter().enumerate() { | ||
| 728 | - let (ob, op, oy) = mine[i]; | ||
| 729 | - eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); | ||
| 730 | - } | ||
| 731 | - for (i, &qp) in x265_qps.iter().enumerate() { | ||
| 732 | - let (xb, xp, xy) = theirs[i]; | ||
| 733 | - eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); | ||
| 734 | - } | ||
| 735 | - (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); | ||
| 736 | - (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = | ||
| 737 | - bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); | ||
| 738 | - eprintln!( | ||
| 739 | - "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", | ||
| 740 | - qps_str(&our_qps), | ||
| 741 | - qps_str(&x265_qps), | ||
| 742 | - ); | ||
| 743 | - eprintln!( | ||
| 744 | - "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", | ||
| 745 | - qps_str(&our_qps), | ||
| 746 | - qps_str(&x265_qps), | ||
| 747 | - ); | ||
| 748 | - let aligned = cand_extrap <= EXTRAP_LIMIT | ||
| 749 | - && anc_extrap <= EXTRAP_LIMIT | ||
| 750 | - && cand_extrap_yuv <= EXTRAP_LIMIT | ||
| 751 | - && anc_extrap_yuv <= EXTRAP_LIMIT; | ||
| 752 | - if aligned || round == 8 { | ||
| 753 | - break; | ||
| 754 | - } | ||
| 755 | - // Re-estimate the shift from the geometric-mean bit ratio of the two | ||
| 756 | - // full curves, then rebuild the ladder. A single-QP correction is | ||
| 757 | - // ignored: it is within the rounding of the estimate and only makes the | ||
| 758 | - // ladder oscillate between two neighbouring shifts. | ||
| 759 | - let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; | ||
| 760 | - if delta.abs() > 1 { | ||
| 761 | - shift += delta; | ||
| 762 | - eprintln!( | ||
| 763 | - "alignment round {}: shift {delta:+} -> {shift:+} \ | ||
| 764 | - (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", | ||
| 765 | - round + 1, | ||
| 766 | - gm(&mine) / 1e6, | ||
| 767 | - gm(&theirs) / 1e6, | ||
| 768 | - ); | ||
| 769 | - continue; | ||
| 770 | - } | ||
| 771 | - // The rates match and the curves still do not overlap, so our ladder | ||
| 772 | - // spans a much wider bitrate range than the anchor's: their union is | ||
| 773 | - // then mostly outside what x265 measured and the cubic through its four | ||
| 774 | - // points extrapolates over most of it. Draw our ladder in. | ||
| 775 | - spread *= 0.5; | ||
| 776 | - eprintln!( | ||
| 777 | - "alignment round {}: ladder spread -> {spread:.2} of the anchor's", | ||
| 778 | - round + 1 | ||
| 779 | - ); | ||
| 780 | - } | ||
| 781 | - | ||
| 782 | - // A BD number over a range where the two QP ladders do not overlap is not a | ||
| 783 | - // measurement — the cubic is extrapolating, not interpolating. Fail loudly | ||
| 784 | - // with the side that is out of range instead of reporting a meaningless gap. | ||
| 785 | - let out_of_range = |c: f64, a: f64| { | ||
| 786 | - let mut parts = Vec::new(); | ||
| 787 | - if c > EXTRAP_LIMIT { | ||
| 788 | - parts.push(format!("ours {:.0}%", c * 100.0)); | ||
| 789 | - } | ||
| 790 | - if a > EXTRAP_LIMIT { | ||
| 791 | - parts.push(format!("x265 {:.0}%", a * 100.0)); | ||
| 792 | - } | ||
| 793 | - parts | ||
| 794 | - }; | ||
| 795 | - let luma_oor = out_of_range(cand_extrap, anc_extrap); | ||
| 796 | - let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv); | ||
| 797 | - if !luma_oor.is_empty() { | ||
| 798 | - panic!( | ||
| 799 | - "BD-PSNR luma: the two QP ladders do not overlap — {} of the \ | ||
| 800 | - integration range is extrapolated (limit {:.0}%); widen the QP \ | ||
| 801 | - sweep until the curves meet", | ||
| 802 | - luma_oor.join(", "), | ||
| 803 | - EXTRAP_LIMIT * 100.0 | ||
| 804 | - ); | ||
| 805 | - } | ||
| 806 | - if !yuv_oor.is_empty() { | ||
| 807 | - panic!( | ||
| 808 | - "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \ | ||
| 809 | - integration range is extrapolated (limit {:.0}%); widen the QP \ | ||
| 810 | - sweep until the curves meet", | ||
| 811 | - yuv_oor.join(", "), | ||
| 812 | - EXTRAP_LIMIT * 100.0 | ||
| 813 | - ); | ||
| 814 | - } | ||
| 815 | - | ||
| 816 | - // The floor is calibrated on the synthetic clip; a clip of the user's is a | ||
| 817 | - // measurement, not a gate, because its content is not pinned. | ||
| 818 | - if std::env::var_os("EC_H265_CLIP").is_none() { | ||
| 819 | - assert!( | ||
| 820 | - bd > BD_PSNR_VS_X265_FLOOR, | ||
| 821 | - "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ | ||
| 822 | - {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" | ||
| 823 | - ); | ||
| 824 | - } | ||
| 825 | -} | ||
| 826 | - | ||
| 827 | -/// Decode `want` pictures from a media file as tightly packed I420 triples. | ||
| 828 | -/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film | ||
| 829 | -/// heads are titles and fades). | ||
| 830 | -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec<Planes>) { | ||
| 831 | - let dims = ec_testkit::ffprobe() | ||
| 832 | - .args([ | ||
| 833 | - "-v", | ||
| 834 | - "error", | ||
| 835 | - "-select_streams", | ||
| 836 | - "v:0", | ||
| 837 | - "-show_entries", | ||
| 838 | - "stream=width,height", | ||
| 839 | - "-of", | ||
| 840 | - "csv=p=0", | ||
| 841 | - ]) | ||
| 842 | - .arg(path) | ||
| 843 | - .output() | ||
| 844 | - .expect("ffprobe"); | ||
| 845 | - assert!( | ||
| 846 | - dims.status.success(), | ||
| 847 | - "ffprobe failed: {}", | ||
| 848 | - String::from_utf8_lossy(&dims.stderr) | ||
| 849 | - ); | ||
| 850 | - let csv = String::from_utf8_lossy(&dims.stdout); | ||
| 851 | - // ffprobe prints one comma-separated line per stream, and recent builds | ||
| 852 | - // end it with a trailing separator, so the fields are taken by position | ||
| 853 | - // rather than by splitting the line in two. | ||
| 854 | - let mut fields = csv.lines().next().unwrap_or_default().split(','); | ||
| 855 | - let (w, h) = (|| { | ||
| 856 | - Some(( | ||
| 857 | - fields.next()?.trim().parse::<usize>().ok()?, | ||
| 858 | - fields.next()?.trim().parse::<usize>().ok()?, | ||
| 859 | - )) | ||
| 860 | - })() | ||
| 861 | - .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}")); | ||
| 862 | - // Pictures to pass over before sampling: the head of a film is titles and | ||
| 863 | - // fades, which are not what a codec is measured on. | ||
| 864 | - let skip: usize = std::env::var("EC_H265_CLIP_SKIP") | ||
| 865 | - .ok() | ||
| 866 | - .and_then(|v| v.parse().ok()) | ||
| 867 | - .unwrap_or(0); | ||
| 868 | - // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing | ||
| 869 | - // afterwards buffers the entire decoded clip in memory: a 1080p feature is | ||
| 870 | - // hundreds of gigabytes of raw I420, which the kernel answers with the OOM | ||
| 871 | - // killer. `select` drops the skipped pictures inside ffmpeg and | ||
| 872 | - // `-frames:v` stops the decode once `want` have come out, so what reaches | ||
| 873 | - // this process is exactly `want` frames. | ||
| 874 | - let raw = ec_testkit::ffmpeg() | ||
| 875 | - .args(["-v", "error", "-i"]) | ||
| 876 | - .arg(path) | ||
| 877 | - .args([ | ||
| 878 | - "-vf", | ||
| 879 | - &format!("select=gte(n\\,{skip})"), | ||
| 880 | - "-fps_mode", | ||
| 881 | - "passthrough", | ||
| 882 | - "-frames:v", | ||
| 883 | - &want.to_string(), | ||
| 884 | - "-f", | ||
| 885 | - "rawvideo", | ||
| 886 | - "-pix_fmt", | ||
| 887 | - "yuv420p", | ||
| 888 | - "pipe:1", | ||
| 889 | - ]) | ||
| 890 | - .output() | ||
| 891 | - .expect("ffmpeg raw extract"); | ||
| 892 | - assert!( | ||
| 893 | - raw.status.success(), | ||
| 894 | - "ffmpeg failed: {}", | ||
| 895 | - String::from_utf8_lossy(&raw.stderr) | ||
| 896 | - ); | ||
| 897 | - let frame = w * h * 3 / 2; | ||
| 898 | - assert!( | ||
| 899 | - raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, | ||
| 900 | - "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", | ||
| 901 | - path.to_string_lossy(), | ||
| 902 | - raw.stdout.len() | ||
| 903 | - ); | ||
| 904 | - let sources: Vec<Planes> = raw | ||
| 905 | - .stdout | ||
| 906 | - .chunks(frame) | ||
| 907 | - .take(want) | ||
| 908 | - .map(|f| { | ||
| 909 | - let (y, rest) = f.split_at(w * h); | ||
| 910 | - let (u, v) = rest.split_at(w / 2 * h / 2); | ||
| 911 | - (y.to_vec(), u.to_vec(), v.to_vec()) | ||
| 912 | - }) | ||
| 913 | - .collect(); | ||
| 914 | - eprintln!( | ||
| 915 | - "{}: {}x{}, {} pictures (skipped {skip})", | ||
| 916 | - path.to_string_lossy(), | ||
| 917 | - w, | ||
| 918 | - h, | ||
| 919 | - sources.len() | ||
| 920 | - ); | ||
| 921 | - (w, h, sources) | ||
| 922 | -} | ||
crates/ec-h265/tests/it/encode_threads.rsmodified+6 -2
| @@ -183,7 +183,8 @@ fn end_picture_outputs_each_access_unit_cropped() { | |||
| 183 | cfg.keyint = 4; | 183 | cfg.keyint = 4; |
| 184 | cfg.keep_recon = true; | 184 | cfg.keep_recon = true; |
| 185 | cfg.threads = 1; | 185 | cfg.threads = 1; |
| 186 | - let mut seq = ec_h265::SequenceEncoder::new(Encoder::new(cfg).expect("encoder")).expect("sequence"); | 186 | + let mut seq = |
| 187 | + ec_h265::SequenceEncoder::new(Encoder::new(cfg).expect("encoder")).expect("sequence"); | ||
| 187 | let mut dec = Decoder::new(); | 188 | let mut dec = Decoder::new(); |
| 188 | for f in &frames { | 189 | for f in &frames { |
| 189 | let pic = seq.encode(f, false).expect("encode"); | 190 | let pic = seq.encode(f, false).expect("encode"); |
| @@ -193,6 +194,9 @@ fn end_picture_outputs_each_access_unit_cropped() { | |||
| 193 | assert_eq!((out.width, out.height), (200, 120)); | 194 | assert_eq!((out.width, out.height), (200, 120)); |
| 194 | let recon = pic.recon.expect("recon"); | 195 | let recon = pic.recon.expect("recon"); |
| 195 | let y: Vec<u8> = out.y.iter().map(|&v| v as u8).collect(); | 196 | let y: Vec<u8> = out.y.iter().map(|&v| v as u8).collect(); |
| 196 | - assert!(*y == *recon.planes[0].data, "cropped luma differs from the reconstruction"); | 197 | + assert!( |
| 198 | + *y == *recon.planes[0].data, | ||
| 199 | + "cropped luma differs from the reconstruction" | ||
| 200 | + ); | ||
| 197 | } | 201 | } |
| 198 | } | 202 | } |
crates/ec-h265/tests/it/main.rsmodified+0 -13
| @@ -5,23 +5,10 @@ | |||
| 5 | #![forbid(unsafe_code)] | 5 | #![forbid(unsafe_code)] |
| 6 | 6 | ||
| 7 | mod common; | 7 | mod common; |
| 8 | -mod conformance; | ||
| 9 | -mod conformance_intra; | ||
| 10 | -mod conformance_rext; | ||
| 11 | -mod conformance_rext422; | ||
| 12 | -mod cu_syntax; | ||
| 13 | -mod dec_meta; | ||
| 14 | -mod dec_shell; | ||
| 15 | mod decode; | 8 | mod decode; |
| 16 | -mod dolby_vision_p8; | ||
| 17 | mod enc8_bitstream_hash; | 9 | mod enc8_bitstream_hash; |
| 18 | -mod encode; | ||
| 19 | mod encode_threads; | 10 | mod encode_threads; |
| 20 | mod fuzz_regressions; | 11 | mod fuzz_regressions; |
| 21 | mod main10; | 12 | mod main10; |
| 22 | -mod rate_control; | ||
| 23 | -mod rdoq_cache_hash; | ||
| 24 | -mod real_library; | ||
| 25 | mod refusals; | 13 | mod refusals; |
| 26 | mod rext_generated; | 14 | mod rext_generated; |
| 27 | -mod scaling_lists; | ||
crates/ec-h265/tests/it/rate_control.rsdeleted+0 -207
| @@ -1,207 +0,0 @@ | |||
| 1 | -//! Bitrate control of the sequence encoder: a clip coded at a target lands within | ||
| 2 | -//! 5% of that target, and the output does not depend on the worker count. | ||
| 3 | -//! | ||
| 4 | -//! The clip is a textured pattern that moves a few samples per picture, so the | ||
| 5 | -//! pictures differ in cost and the model has to follow them. The 5% bound is the | ||
| 6 | -//! same one the 60 s measurement is held to (`scripts/hevc-rc.sh`). | ||
| 7 | - | ||
| 8 | -use ec_core::frame::{PixelFormat, Plane, VideoFrame}; | ||
| 9 | -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; | ||
| 10 | - | ||
| 11 | -const W: usize = 320; | ||
| 12 | -const H: usize = 240; | ||
| 13 | -const FPS: f64 = 30.0; | ||
| 14 | -const FRAMES: usize = 150; | ||
| 15 | -const KEYINT: usize = 30; | ||
| 16 | - | ||
| 17 | -fn moving_clip(frames: usize) -> Vec<VideoFrame> { | ||
| 18 | - let (cw, ch) = (W / 2, H / 2); | ||
| 19 | - (0..frames) | ||
| 20 | - .map(|t| { | ||
| 21 | - let mut y = vec![0u8; W * H]; | ||
| 22 | - for r in 0..H { | ||
| 23 | - for c in 0..W { | ||
| 24 | - let (x, yy) = (c + 3 * t, r + t); | ||
| 25 | - let mut v = (x * 7 + yy * 5) as u32; | ||
| 26 | - v ^= (x as u32).wrapping_mul(0x9e37) ^ (yy as u32).wrapping_mul(0x85eb); | ||
| 27 | - y[r * W + c] = (v.wrapping_mul(2_654_435_761) >> 24) as u8; | ||
| 28 | - } | ||
| 29 | - } | ||
| 30 | - let chroma = |scale: usize| -> Vec<u8> { | ||
| 31 | - (0..cw * ch) | ||
| 32 | - .map(|i| { | ||
| 33 | - let (c, r) = (i % cw, i / cw); | ||
| 34 | - ((c * scale + r * 3 + t * 2) % 251) as u8 | ||
| 35 | - }) | ||
| 36 | - .collect() | ||
| 37 | - }; | ||
| 38 | - VideoFrame::try_new( | ||
| 39 | - PixelFormat::I420, | ||
| 40 | - W as u32, | ||
| 41 | - H as u32, | ||
| 42 | - vec![ | ||
| 43 | - Plane::new(y, W), | ||
| 44 | - Plane::new(chroma(5), cw), | ||
| 45 | - Plane::new(chroma(9), cw), | ||
| 46 | - ], | ||
| 47 | - ) | ||
| 48 | - .expect("I420 planes at the stated size") | ||
| 49 | - }) | ||
| 50 | - .collect() | ||
| 51 | -} | ||
| 52 | - | ||
| 53 | -/// Encode the clip at `kbps` with `threads` workers; returns the stream bytes. | ||
| 54 | -fn encode_at(frames: &[VideoFrame], kbps: u32, threads: usize) -> Vec<u8> { | ||
| 55 | - let mut cfg = EncoderConfig::new(W as u32, H as u32); | ||
| 56 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 57 | - cfg.keyint = KEYINT; | ||
| 58 | - cfg.threads = threads; | ||
| 59 | - let enc = Encoder::new(cfg).expect("encoder"); | ||
| 60 | - let coded = enc.encode_sequence(frames).expect("encode"); | ||
| 61 | - coded.iter().flat_map(|p| p.au.iter().copied()).collect() | ||
| 62 | -} | ||
| 63 | - | ||
| 64 | -#[test] | ||
| 65 | -fn bitrate_lands_within_five_percent_of_each_target() { | ||
| 66 | - let frames = moving_clip(FRAMES); | ||
| 67 | - for kbps in [1000u32, 2500, 5000] { | ||
| 68 | - let stream = encode_at(&frames, kbps, 1); | ||
| 69 | - let seconds = FRAMES as f64 / FPS; | ||
| 70 | - let achieved = stream.len() as f64 * 8.0 / seconds / 1000.0; | ||
| 71 | - let error = (achieved - f64::from(kbps)) / f64::from(kbps); | ||
| 72 | - eprintln!( | ||
| 73 | - "target {kbps} kbps: achieved {achieved:.1} kbps ({:+.2}%)", | ||
| 74 | - error * 100.0 | ||
| 75 | - ); | ||
| 76 | - assert!( | ||
| 77 | - error.abs() <= 0.05, | ||
| 78 | - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", | ||
| 79 | - error * 100.0 | ||
| 80 | - ); | ||
| 81 | - } | ||
| 82 | -} | ||
| 83 | - | ||
| 84 | -/// A flat picture at `luma` (chroma at 128): nothing in it costs more than a skipped block | ||
| 85 | -/// at any QP, so it is the case where the rate cannot be spent. | ||
| 86 | -fn flat_clip(frames: usize, luma: u8) -> Vec<VideoFrame> { | ||
| 87 | - let (cw, ch) = (W / 2, H / 2); | ||
| 88 | - (0..frames) | ||
| 89 | - .map(|_| { | ||
| 90 | - VideoFrame::try_new( | ||
| 91 | - PixelFormat::I420, | ||
| 92 | - W as u32, | ||
| 93 | - H as u32, | ||
| 94 | - vec![ | ||
| 95 | - Plane::new(vec![luma; W * H], W), | ||
| 96 | - Plane::new(vec![128; cw * ch], cw), | ||
| 97 | - Plane::new(vec![128; cw * ch], cw), | ||
| 98 | - ], | ||
| 99 | - ) | ||
| 100 | - .expect("I420 planes at the stated size") | ||
| 101 | - }) | ||
| 102 | - .collect() | ||
| 103 | -} | ||
| 104 | - | ||
| 105 | -/// A flat clip at 2000 kbps cannot spend its budget even at QP 0, so the rate model must | ||
| 106 | -/// walk the quantiser down to the HEVC floor and hold it there, rather than stall high. | ||
| 107 | -/// The floor is the codec's, not a rate floor of this encoder: whatever bits remain are the | ||
| 108 | -/// content's own cost at QP 0. | ||
| 109 | -#[test] | ||
| 110 | -fn flat_near_black_descends_to_the_qp_floor() { | ||
| 111 | - let frames = flat_clip(60, 16); | ||
| 112 | - let pics: Vec<EncodedPicture> = encode_pictures(&frames, 2000); | ||
| 113 | - // The first predicted pictures walk the quantiser down from the IDR's QP (at most four | ||
| 114 | - // steps each); from picture 10 on, every predicted picture must sit at QP 0. | ||
| 115 | - let tail: Vec<(usize, i32)> = pics | ||
| 116 | - .iter() | ||
| 117 | - .enumerate() | ||
| 118 | - .filter(|(i, _)| i % KEYINT != 0 && *i >= 10) | ||
| 119 | - .map(|(i, p)| (i, p.qp)) | ||
| 120 | - .collect(); | ||
| 121 | - assert!(!tail.is_empty()); | ||
| 122 | - let stalled: Vec<&(usize, i32)> = tail.iter().filter(|(_, qp)| *qp != 0).collect(); | ||
| 123 | - assert!( | ||
| 124 | - stalled.is_empty(), | ||
| 125 | - "QP did not reach the floor: {stalled:?}" | ||
| 126 | - ); | ||
| 127 | -} | ||
| 128 | - | ||
| 129 | -/// Encode `frames` at `kbps` and return the coded pictures, so the test can see each QP. | ||
| 130 | -fn encode_pictures(frames: &[VideoFrame], kbps: u32) -> Vec<EncodedPicture> { | ||
| 131 | - let mut cfg = EncoderConfig::new(W as u32, H as u32); | ||
| 132 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 133 | - cfg.keyint = KEYINT; | ||
| 134 | - cfg.threads = 1; | ||
| 135 | - Encoder::new(cfg) | ||
| 136 | - .expect("encoder") | ||
| 137 | - .encode_sequence(frames) | ||
| 138 | - .expect("encode") | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -#[test] | ||
| 142 | -fn bitrate_output_is_identical_at_any_thread_count() { | ||
| 143 | - let frames = moving_clip(FRAMES); | ||
| 144 | - let one = encode_at(&frames, 2500, 1); | ||
| 145 | - for threads in [2usize, 4] { | ||
| 146 | - assert!( | ||
| 147 | - encode_at(&frames, 2500, threads) == one, | ||
| 148 | - "stream differs at {threads} threads" | ||
| 149 | - ); | ||
| 150 | - } | ||
| 151 | -} | ||
| 152 | - | ||
| 153 | -/// Near-black with temporal noise at 720p: luma 16 plus a deterministic PRNG offset of -2..=2 | ||
| 154 | -/// that differs every picture. Cost against QP is a cliff here (a few hundred bytes per | ||
| 155 | -/// picture above QP ~17, tens of kilobytes a few steps below), so the `2^(QP/6)` model alone | ||
| 156 | -/// dives into the cliff after a run of cheap pictures and the stream overshoots. The cliff | ||
| 157 | -/// only shows at this size, which is why this clip is not 320x240. | ||
| 158 | -fn noisy_black_clip(frames: usize, w: usize, h: usize) -> Vec<VideoFrame> { | ||
| 159 | - let (cw, ch) = (w / 2, h / 2); | ||
| 160 | - let mut state = 0x2545_f491_4f6c_dd1du64; | ||
| 161 | - let mut next = move || { | ||
| 162 | - state ^= state << 13; | ||
| 163 | - state ^= state >> 7; | ||
| 164 | - state ^= state << 17; | ||
| 165 | - (state >> 33) as u32 | ||
| 166 | - }; | ||
| 167 | - (0..frames) | ||
| 168 | - .map(|_| { | ||
| 169 | - let y: Vec<u8> = (0..w * h).map(|_| (14 + next() % 5) as u8).collect(); | ||
| 170 | - VideoFrame::try_new( | ||
| 171 | - PixelFormat::I420, | ||
| 172 | - w as u32, | ||
| 173 | - h as u32, | ||
| 174 | - vec![ | ||
| 175 | - Plane::new(y, w), | ||
| 176 | - Plane::new(vec![128; cw * ch], cw), | ||
| 177 | - Plane::new(vec![128; cw * ch], cw), | ||
| 178 | - ], | ||
| 179 | - ) | ||
| 180 | - .expect("I420 planes at the stated size") | ||
| 181 | - }) | ||
| 182 | - .collect() | ||
| 183 | -} | ||
| 184 | - | ||
| 185 | -#[test] | ||
| 186 | -fn noisy_near_black_lands_within_five_percent() { | ||
| 187 | - let (w, h, frames) = (1280usize, 720usize, noisy_black_clip(90, 1280, 720)); | ||
| 188 | - for kbps in [500u32, 2000] { | ||
| 189 | - let mut cfg = EncoderConfig::new(w as u32, h as u32); | ||
| 190 | - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; | ||
| 191 | - cfg.keyint = KEYINT; | ||
| 192 | - cfg.threads = 1; | ||
| 193 | - let pics = Encoder::new(cfg) | ||
| 194 | - .expect("encoder") | ||
| 195 | - .encode_sequence(&frames) | ||
| 196 | - .expect("encode"); | ||
| 197 | - let bytes: usize = pics.iter().map(|p| p.au.len()).sum(); | ||
| 198 | - let achieved = bytes as f64 * 8.0 / (frames.len() as f64 / FPS) / 1000.0; | ||
| 199 | - let error = (achieved - f64::from(kbps)) / f64::from(kbps); | ||
| 200 | - eprintln!("target {kbps}: {achieved:.1} kbps ({:+.2}%)", error * 100.0); | ||
| 201 | - assert!( | ||
| 202 | - error.abs() <= 0.05, | ||
| 203 | - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", | ||
| 204 | - error * 100.0 | ||
| 205 | - ); | ||
| 206 | - } | ||
| 207 | -} | ||
crates/ec-h265/tests/it/rdoq_cache_hash.rsdeleted+0 -70
| @@ -1,70 +0,0 @@ | |||
| 1 | -//! lane-h265rdoq r3: the sub-block frozen-prefix cursor must not change a | ||
| 2 | -//! single output byte. Hashes two natural-content encodes (1920x1080 and | ||
| 3 | -//! 416x240) with FNV-1a; the number itself means nothing, only that it is the | ||
| 4 | -//! same before and after this round's change to `rdoq()` (checked by hand: | ||
| 5 | -//! stash `residual.rs`, rerun, compare). | ||
| 6 | - | ||
| 7 | -use crate::common::{fnv1a, natural_frame}; | ||
| 8 | -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; | ||
| 9 | - | ||
| 10 | -fn encode_hash(width: u32, height: u32) -> u64 { | ||
| 11 | - let mut cfg = EncoderConfig::new(width, height); | ||
| 12 | - cfg.rate_control = RateControl::ConstantQp(24); | ||
| 13 | - cfg.threads = 1; | ||
| 14 | - let encoder = Encoder::new(cfg).expect("encoder"); | ||
| 15 | - let mut all = Vec::new(); | ||
| 16 | - for i in 0..3u32 { | ||
| 17 | - let frame = natural_frame(width, height, i * 5); | ||
| 18 | - all.extend(encoder.encode_idr(&frame).expect("encode").au); | ||
| 19 | - } | ||
| 20 | - fnv1a(&all) | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -#[test] | ||
| 24 | -fn rdoq_cache_hash_1920x1080() { | ||
| 25 | - println!("hash 1920x1080 = {:016x}", encode_hash(1920, 1080)); | ||
| 26 | -} | ||
| 27 | - | ||
| 28 | -#[test] | ||
| 29 | -fn rdoq_cache_hash_416x240() { | ||
| 30 | - println!("hash 416x240 = {:016x}", encode_hash(416, 240)); | ||
| 31 | -} | ||
| 32 | - | ||
| 33 | -/// lane-h265simd: pinned bit-identity gate for the transform's hot path. The | ||
| 34 | -/// value is the same hash the two tests above print, verified by hand | ||
| 35 | -/// (`git stash` the transform.rs change, rerun, compare) to be identical | ||
| 36 | -/// before and after replacing `m32()`'s per-element branch with a | ||
| 37 | -/// compile-time-mirrored flat table in `forward_1d`/`inverse_1d` — this pins | ||
| 38 | -/// that equality so a future change to the hot path is caught if it ever | ||
| 39 | -/// produces a different byte. | ||
| 40 | -/// | ||
| 41 | -/// lane-h265prune: re-pinned after the RQT split trial gained an all-zero-CBF | ||
| 42 | -/// early out (mirrors the CU-quadtree's existing `last_cu_empty` skip one | ||
| 43 | -/// level down at the transform tree): a coding unit whose luma+chroma already | ||
| 44 | -/// quantised to nothing is committed as one leaf transform unit without | ||
| 45 | -/// trying the four-child split first, since splitting a zero-SSD block can | ||
| 46 | -/// only add split_transform_flag and mode-signalling bits. This changes the | ||
| 47 | -/// bitstream on any content where that trial used to flip a leaf to split | ||
| 48 | -/// (BD-gated, not bit-identical — see `EncoderConfig::rqt` and this crate's | ||
| 49 | -/// `bd_psnr_vs_x265`). | ||
| 50 | -/// | ||
| 51 | -/// lane-h265rdoq: re-pinned after RDOQ's trial costing switched from exact | ||
| 52 | -/// per-trial CABAC replay to an estimated per-context fracbits table | ||
| 53 | -/// (`EncoderConfig::rdoq_estimate`, now on by default) — deliberately | ||
| 54 | -/// bit-different, not exact-mode-preserving; see that field's doc comment | ||
| 55 | -/// for the BD/speed numbers that justified flipping the default. | ||
| 56 | -/// | ||
| 57 | -/// lane-h265screen: re-pinned after every committed 4x4 luma block gained a | ||
| 58 | -/// rate-distortion decision on `transform_skip_flag` (`TransformSkip::Rd`, now | ||
| 59 | -/// the default) — deliberately bit-different; see that field's doc comment for | ||
| 60 | -/// the BD numbers per clip. | ||
| 61 | -/// | ||
| 62 | -/// lane-hevcenctools: re-pinned after the sequence parameter set's | ||
| 63 | -/// `sps_temporal_mvp_enabled_flag` went on, which the P pictures' slice headers | ||
| 64 | -/// need. That is one SPS bit; the intra slices are otherwise unchanged, and the | ||
| 65 | -/// 9203-picture conformance check still matches. | ||
| 66 | -#[test] | ||
| 67 | -fn rdoq_cache_hash_is_pinned() { | ||
| 68 | - assert_eq!(encode_hash(416, 240), 0xd501713b57091906); | ||
| 69 | - assert_eq!(encode_hash(1920, 1080), 0x5eb50f5a747ca1c2); | ||
| 70 | -} | ||
crates/ec-h265/tests/it/real_library.rsdeleted+0 -367
| @@ -1,367 +0,0 @@ | |||
| 1 | -//! Every file either decodes bit-exactly, is refused by name (a pixel format or | ||
| 2 | -//! a bit depth outside 4:2:0 8/10-bit, or a decoder refusal that says | ||
| 3 | -//! "unsupported"), or fails. A refusal is reported, not counted as a failure. | ||
| 4 | - | ||
| 5 | -use std::io::Read; | ||
| 6 | -use std::path::{Path, PathBuf}; | ||
| 7 | -use std::process::Stdio; | ||
| 8 | - | ||
| 9 | -use ec_h265::dec::Decoder; | ||
| 10 | -use ec_h265::decode::DecodedPicture; | ||
| 11 | -use ec_h265_syntax::{ConformanceWindow, split_annex_b}; | ||
| 12 | - | ||
| 13 | -/// Pictures compared per file. | ||
| 14 | -const FRAMES: usize = 300; | ||
| 15 | - | ||
| 16 | -/// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits. | ||
| 17 | -const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"]; | ||
| 18 | - | ||
| 19 | -fn scratch(tag: &str) -> PathBuf { | ||
| 20 | - let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); | ||
| 21 | - let dir = base.join(format!("ec-h265-{tag}-{}", std::process::id())); | ||
| 22 | - std::fs::create_dir_all(&dir).expect("scratch dir"); | ||
| 23 | - dir | ||
| 24 | -} | ||
| 25 | - | ||
| 26 | -/// One manifest row: the columns the sweep reads. | ||
| 27 | -struct Entry { | ||
| 28 | - path: PathBuf, | ||
| 29 | - container: String, | ||
| 30 | - width: String, | ||
| 31 | - height: String, | ||
| 32 | - pix_fmt: String, | ||
| 33 | -} | ||
| 34 | - | ||
| 35 | -fn hevc_entries() -> Vec<Entry> { | ||
| 36 | - [ | ||
| 37 | - ( | ||
| 38 | - "derived/sintel720-x265-main10.mp4", | ||
| 39 | - "yuv420p10le", | ||
| 40 | - "1280", | ||
| 41 | - "720", | ||
| 42 | - ), | ||
| 43 | - ("open/sintel_trailer-1080p.mp4", "yuv420p", "1920", "1080"), | ||
| 44 | - ] | ||
| 45 | - .into_iter() | ||
| 46 | - .map(|(rel, pix_fmt, width, height)| Entry { | ||
| 47 | - path: ec_testkit::fixture(rel), | ||
| 48 | - container: "mp4".to_string(), | ||
| 49 | - width: width.to_string(), | ||
| 50 | - height: height.to_string(), | ||
| 51 | - pix_fmt: pix_fmt.to_string(), | ||
| 52 | - }) | ||
| 53 | - .collect() | ||
| 54 | -} | ||
| 55 | - | ||
| 56 | -/// The samples of a picture cropped to its conformance window, as the bytes of a | ||
| 57 | -/// planar rawvideo frame: one byte per sample at 8 bits, little-endian u16 above. | ||
| 58 | -fn cropped(pic: &DecodedPicture, win: &ConformanceWindow, bps: usize) -> Vec<u8> { | ||
| 59 | - let (l, r, t, b) = ( | ||
| 60 | - win.left as usize, | ||
| 61 | - win.right as usize, | ||
| 62 | - win.top as usize, | ||
| 63 | - win.bottom as usize, | ||
| 64 | - ); | ||
| 65 | - let (w, h) = (pic.width, pic.height); | ||
| 66 | - // Conformance offsets are in chroma units for 4:2:0: luma is twice as large. | ||
| 67 | - let planes = [ | ||
| 68 | - ( | ||
| 69 | - &pic.y, | ||
| 70 | - w, | ||
| 71 | - h, | ||
| 72 | - 2 * l, | ||
| 73 | - w.saturating_sub(2 * r), | ||
| 74 | - 2 * t, | ||
| 75 | - h.saturating_sub(2 * b), | ||
| 76 | - ), | ||
| 77 | - ( | ||
| 78 | - &pic.cb, | ||
| 79 | - w / 2, | ||
| 80 | - h / 2, | ||
| 81 | - l, | ||
| 82 | - (w / 2).saturating_sub(r), | ||
| 83 | - t, | ||
| 84 | - (h / 2).saturating_sub(b), | ||
| 85 | - ), | ||
| 86 | - ( | ||
| 87 | - &pic.cr, | ||
| 88 | - w / 2, | ||
| 89 | - h / 2, | ||
| 90 | - l, | ||
| 91 | - (w / 2).saturating_sub(r), | ||
| 92 | - t, | ||
| 93 | - (h / 2).saturating_sub(b), | ||
| 94 | - ), | ||
| 95 | - ]; | ||
| 96 | - let mut out = Vec::new(); | ||
| 97 | - for (samples, pw, ph, x0, x1, y0, y1) in planes { | ||
| 98 | - for y in y0..y1.min(ph) { | ||
| 99 | - for x in x0..x1.min(pw) { | ||
| 100 | - let s = samples.get(y * pw + x).copied().unwrap_or(0); | ||
| 101 | - if bps == 1 { | ||
| 102 | - out.push(s as u8); | ||
| 103 | - } else { | ||
| 104 | - out.extend_from_slice(&s.to_le_bytes()); | ||
| 105 | - } | ||
| 106 | - } | ||
| 107 | - } | ||
| 108 | - } | ||
| 109 | - out | ||
| 110 | -} | ||
| 111 | - | ||
| 112 | -/// Where byte `offset` of a cropped frame lies: plane name, x and y in that plane. | ||
| 113 | -fn locate(offset: usize, bps: usize, lw: usize, lh: usize) -> (&'static str, usize, usize) { | ||
| 114 | - let s = offset / bps; | ||
| 115 | - let (cw, ch) = (lw / 2, lh / 2); | ||
| 116 | - if s < lw * lh { | ||
| 117 | - ("Y", s % lw, s / lw) | ||
| 118 | - } else if s < lw * lh + cw * ch { | ||
| 119 | - let c = s - lw * lh; | ||
| 120 | - ("Cb", c % cw, c / cw) | ||
| 121 | - } else { | ||
| 122 | - let c = s - lw * lh - cw * ch; | ||
| 123 | - ("Cr", c % cw, c / cw) | ||
| 124 | - } | ||
| 125 | -} | ||
| 126 | - | ||
| 127 | -/// Running comparison of decoded frames against the oracle's rawvideo stream. | ||
| 128 | -#[derive(Default)] | ||
| 129 | -struct Compare { | ||
| 130 | - compared: usize, | ||
| 131 | - /// First mismatch: "frame N plane P x= y= (poc)". | ||
| 132 | - first_diff: Option<String>, | ||
| 133 | - differing_frames: usize, | ||
| 134 | - oracle_short: bool, | ||
| 135 | -} | ||
| 136 | - | ||
| 137 | -/// The oracle's stream and the decoder's frames, compared frame by frame. | ||
| 138 | -struct Sweep { | ||
| 139 | - out: std::process::ChildStdout, | ||
| 140 | - child: std::process::Child, | ||
| 141 | - open: bool, | ||
| 142 | - cmp: Compare, | ||
| 143 | - index: usize, | ||
| 144 | - frame_len: usize, | ||
| 145 | - bps: usize, | ||
| 146 | -} | ||
| 147 | - | ||
| 148 | -impl Sweep { | ||
| 149 | - fn take(&mut self, pic: &DecodedPicture, win: &ConformanceWindow, poc: i32) { | ||
| 150 | - let want = cropped(pic, win, self.bps); | ||
| 151 | - let index = self.index; | ||
| 152 | - self.index += 1; | ||
| 153 | - if !self.open { | ||
| 154 | - return; | ||
| 155 | - } | ||
| 156 | - let mut oracle = vec![0u8; want.len()]; | ||
| 157 | - if self.out.read_exact(&mut oracle).is_err() { | ||
| 158 | - self.open = false; | ||
| 159 | - self.cmp.oracle_short = true; | ||
| 160 | - return; | ||
| 161 | - } | ||
| 162 | - self.frame_len = want.len(); | ||
| 163 | - self.cmp.compared += 1; | ||
| 164 | - if want != oracle { | ||
| 165 | - self.cmp.differing_frames += 1; | ||
| 166 | - if self.cmp.first_diff.is_none() { | ||
| 167 | - let lw = pic.width - 2 * (win.left as usize + win.right as usize); | ||
| 168 | - let lh = pic.height - 2 * (win.top as usize + win.bottom as usize); | ||
| 169 | - let at = want | ||
| 170 | - .iter() | ||
| 171 | - .zip(&oracle) | ||
| 172 | - .position(|(a, b)| a != b) | ||
| 173 | - .unwrap_or(0); | ||
| 174 | - let (plane, x, y) = locate(at, self.bps, lw, lh); | ||
| 175 | - self.cmp.first_diff = Some(format!( | ||
| 176 | - "frame {index} plane {plane} x={x} y={y} (poc {poc})" | ||
| 177 | - )); | ||
| 178 | - } | ||
| 179 | - } | ||
| 180 | - } | ||
| 181 | - | ||
| 182 | - /// End of the decoder's output: any frame still in the oracle is missing here. | ||
| 183 | - fn finish(mut self) -> Compare { | ||
| 184 | - if self.open { | ||
| 185 | - let mut probe = vec![0u8; self.frame_len.max(1)]; | ||
| 186 | - if self.frame_len > 0 && self.out.read_exact(&mut probe).is_ok() { | ||
| 187 | - self.cmp.first_diff.get_or_insert(format!( | ||
| 188 | - "decoder produced {} frames, ffmpeg produced more", | ||
| 189 | - self.index | ||
| 190 | - )); | ||
| 191 | - self.cmp.oracle_short = false; | ||
| 192 | - self.cmp.differing_frames += 1; | ||
| 193 | - } | ||
| 194 | - } | ||
| 195 | - let _ = self.child.kill(); | ||
| 196 | - let _ = self.child.wait(); | ||
| 197 | - self.cmp | ||
| 198 | - } | ||
| 199 | -} | ||
| 200 | - | ||
| 201 | -fn short_name(path: &Path) -> String { | ||
| 202 | - path.file_name() | ||
| 203 | - .map(|n| n.to_string_lossy().chars().take(38).collect()) | ||
| 204 | - .unwrap_or_default() | ||
| 205 | -} | ||
| 206 | - | ||
| 207 | -/// Decodes one file and compares it with ffmpeg. `Err` is a refusal or an error, | ||
| 208 | -/// with the text the table prints. | ||
| 209 | -fn sweep_file(entry: &Entry, es: &Path, bit_depth: u32) -> Result<Compare, String> { | ||
| 210 | - let bps = if bit_depth > 8 { 2 } else { 1 }; | ||
| 211 | - let mut child = ec_testkit::ffmpeg() | ||
| 212 | - .args(["-v", "error", "-c:v", "hevc", "-i"]) | ||
| 213 | - .arg(es) | ||
| 214 | - .args([ | ||
| 215 | - "-frames:v", | ||
| 216 | - &FRAMES.to_string(), | ||
| 217 | - "-f", | ||
| 218 | - "rawvideo", | ||
| 219 | - "-pix_fmt", | ||
| 220 | - ]) | ||
| 221 | - .arg(&entry.pix_fmt) | ||
| 222 | - .arg("-") | ||
| 223 | - .stdout(Stdio::piped()) | ||
| 224 | - .stderr(Stdio::null()) | ||
| 225 | - .spawn() | ||
| 226 | - .map_err(|e| e.to_string())?; | ||
| 227 | - let out = child.stdout.take().expect("piped stdout"); | ||
| 228 | - let mut sweep = Sweep { | ||
| 229 | - out, | ||
| 230 | - child, | ||
| 231 | - open: true, | ||
| 232 | - cmp: Compare::default(), | ||
| 233 | - index: 0, | ||
| 234 | - frame_len: 0, | ||
| 235 | - bps, | ||
| 236 | - }; | ||
| 237 | - | ||
| 238 | - let data = std::fs::read(es).map_err(|e| e.to_string())?; | ||
| 239 | - let mut dec = Decoder::new(); | ||
| 240 | - let drain = |dec: &mut Decoder, sweep: &mut Sweep| { | ||
| 241 | - while let Some(frame) = dec.next_frame() { | ||
| 242 | - sweep.take(&frame.picture, &frame.window, frame.poc); | ||
| 243 | - } | ||
| 244 | - }; | ||
| 245 | - let result = (|| -> Result<(), String> { | ||
| 246 | - for nal in split_annex_b(&data) { | ||
| 247 | - let mut bytes = nal.header.to_bytes().to_vec(); | ||
| 248 | - bytes.extend_from_slice(nal.payload); | ||
| 249 | - if let Err(e) = dec.push_nal(&bytes) { | ||
| 250 | - return Err(format!("{e}")); | ||
| 251 | - } | ||
| 252 | - drain(&mut dec, &mut sweep); | ||
| 253 | - } | ||
| 254 | - dec.flush().map_err(|e| format!("{e}"))?; | ||
| 255 | - drain(&mut dec, &mut sweep); | ||
| 256 | - Ok(()) | ||
| 257 | - })(); | ||
| 258 | - let cmp = sweep.finish(); | ||
| 259 | - result?; | ||
| 260 | - Ok(cmp) | ||
| 261 | -} | ||
| 262 | - | ||
| 263 | -/// Extracts the first `FRAMES` pictures of the video as Annex B. | ||
| 264 | -fn extract(src: &Path, dst: &Path) -> bool { | ||
| 265 | - ec_testkit::ffmpeg() | ||
| 266 | - .args(["-v", "error", "-y", "-i"]) | ||
| 267 | - .arg(src) | ||
| 268 | - .args([ | ||
| 269 | - "-map", | ||
| 270 | - "0:v:0", | ||
| 271 | - "-c", | ||
| 272 | - "copy", | ||
| 273 | - "-bsf:v", | ||
| 274 | - "hevc_mp4toannexb", | ||
| 275 | - "-frames:v", | ||
| 276 | - &FRAMES.to_string(), | ||
| 277 | - "-f", | ||
| 278 | - "hevc", | ||
| 279 | - ]) | ||
| 280 | - .arg(dst) | ||
| 281 | - .status() | ||
| 282 | - .is_ok_and(|s| s.success()) | ||
| 283 | -} | ||
| 284 | - | ||
| 285 | -#[test] | ||
| 286 | -#[ignore = "slow: decodes and compares two open clips with ffmpeg; run with --ignored."] | ||
| 287 | -fn real_library_hevc_streams_match_ffmpeg() { | ||
| 288 | - let entries = hevc_entries(); | ||
| 289 | - let dir = scratch("real-library-hevc"); | ||
| 290 | - let mut table = String::new(); | ||
| 291 | - let mut decoded = 0usize; | ||
| 292 | - let mut refused = 0usize; | ||
| 293 | - let mut failures = Vec::new(); | ||
| 294 | - | ||
| 295 | - for entry in &entries { | ||
| 296 | - let name = short_name(&entry.path); | ||
| 297 | - let res = format!("{}x{}", entry.width, entry.height); | ||
| 298 | - let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" { | ||
| 299 | - 10 | ||
| 300 | - } else { | ||
| 301 | - 8 | ||
| 302 | - }; | ||
| 303 | - if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) { | ||
| 304 | - refused += 1; | ||
| 305 | - table.push_str(&format!( | ||
| 306 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n", | ||
| 307 | - entry.container, "-", entry.pix_fmt | ||
| 308 | - )); | ||
| 309 | - continue; | ||
| 310 | - } | ||
| 311 | - let es = dir.join("stream.265"); | ||
| 312 | - if !extract(&entry.path, &es) { | ||
| 313 | - failures.push(format!("{name}: extraction failed")); | ||
| 314 | - table.push_str(&format!( | ||
| 315 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n", | ||
| 316 | - entry.container, "-" | ||
| 317 | - )); | ||
| 318 | - continue; | ||
| 319 | - } | ||
| 320 | - match sweep_file(entry, &es, bit_depth) { | ||
| 321 | - Ok(c) if c.differing_frames > 0 => { | ||
| 322 | - failures.push(format!("{name}: {} frames differ", c.differing_frames)); | ||
| 323 | - table.push_str(&format!( | ||
| 324 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n", | ||
| 325 | - entry.container, c.compared, c.differing_frames, c.compared, | ||
| 326 | - c.first_diff.clone().unwrap_or_default() | ||
| 327 | - )); | ||
| 328 | - } | ||
| 329 | - Ok(c) => { | ||
| 330 | - decoded += 1; | ||
| 331 | - table.push_str(&format!( | ||
| 332 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n", | ||
| 333 | - entry.container, | ||
| 334 | - c.compared, | ||
| 335 | - if c.oracle_short { | ||
| 336 | - " (ffmpeg stopped early)" | ||
| 337 | - } else { | ||
| 338 | - "" | ||
| 339 | - } | ||
| 340 | - )); | ||
| 341 | - } | ||
| 342 | - Err(e) if e.contains("unsupported") => { | ||
| 343 | - refused += 1; | ||
| 344 | - table.push_str(&format!( | ||
| 345 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n", | ||
| 346 | - entry.container, "-" | ||
| 347 | - )); | ||
| 348 | - } | ||
| 349 | - Err(e) => { | ||
| 350 | - failures.push(format!("{name}: {e}")); | ||
| 351 | - table.push_str(&format!( | ||
| 352 | - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n", | ||
| 353 | - entry.container, "-" | ||
| 354 | - )); | ||
| 355 | - } | ||
| 356 | - } | ||
| 357 | - let _ = std::fs::remove_file(&es); | ||
| 358 | - } | ||
| 359 | - let _ = std::fs::remove_dir_all(&dir); | ||
| 360 | - eprintln!("{table}"); | ||
| 361 | - eprintln!( | ||
| 362 | - "real library hevc: {decoded} bit-exact, {refused} refused by name, {} failed", | ||
| 363 | - failures.len() | ||
| 364 | - ); | ||
| 365 | - assert!(failures.is_empty(), "{failures:#?}"); | ||
| 366 | - assert!(decoded >= 1, "no real HEVC file was swept end to end"); | ||
| 367 | -} | ||
crates/ec-h265/tests/it/rext_generated.rsmodified+3 -1
| @@ -7,6 +7,8 @@ use std::path::Path; | |||
| 7 | use ec_h265::Decoder; | 7 | use ec_h265::Decoder; |
| 8 | use ec_h265_syntax::md5::Md5; | 8 | use ec_h265_syntax::md5::Md5; |
| 9 | 9 | ||
| 10 | +use crate::common::bit_depth_of; | ||
| 11 | + | ||
| 10 | fn hex(d: [u8; 16]) -> String { | 12 | fn hex(d: [u8; 16]) -> String { |
| 11 | d.iter().map(|b| format!("{b:02x}")).collect() | 13 | d.iter().map(|b| format!("{b:02x}")).collect() |
| 12 | } | 14 | } |
| @@ -67,7 +69,7 @@ fn output_md5(data: &[u8]) -> Result<(String, usize), String> { | |||
| 67 | if plane.is_empty() { | 69 | if plane.is_empty() { |
| 68 | continue; | 70 | continue; |
| 69 | } | 71 | } |
| 70 | - let wide = p.bit_depth_of(c) > 8; | 72 | + let wide = bit_depth_of(p, c) > 8; |
| 71 | let mut bytes = Vec::new(); | 73 | let mut bytes = Vec::new(); |
| 72 | for y in y0..y1 { | 74 | for y in y0..y1 { |
| 73 | for x in x0..x1 { | 75 | for x in x0..x1 { |
crates/ec-h265/tests/it/scaling_lists.rsdeleted+0 -111
| @@ -1,111 +0,0 @@ | |||
| 1 | -//! Scaling-list streams, checked against ffmpeg. | ||
| 2 | -//! | ||
| 3 | -//! The SLIST conformance streams code their own lists in the SPS and PPS. Most of | ||
| 4 | -//! their pictures are B slices, which this decoder does not pixel-decode yet, so the | ||
| 5 | -//! check is on the first picture in output order: an IDR, intra only, decoded with | ||
| 6 | -//! the stream's lists. It must match ffmpeg sample for sample after cropping. | ||
| 7 | - | ||
| 8 | -use ec_h265::Decoder; | ||
| 9 | -use ec_h265::dec::Frame; | ||
| 10 | -use std::path::{Path, PathBuf}; | ||
| 11 | - | ||
| 12 | -/// The four scaling-list streams the picture-management sweep covers; `str` is | ||
| 13 | -/// the SLIST_D stream. | ||
| 14 | -const STREAMS: [&str; 4] = [ | ||
| 15 | - "SLIST_A_Sony_5/SLIST_A_Sony_5/SLIST_A_Sony_5.bin", | ||
| 16 | - "SLIST_B_Sony_9/SLIST_B_Sony_9/SLIST_B_Sony_9.bin", | ||
| 17 | - "SLIST_C_Sony_4/SLIST_C_Sony_4/SLIST_C_Sony_4.bin", | ||
| 18 | - "SLIST_D_Sony_9/SLIST_D_Sony_9/str.bin", | ||
| 19 | -]; | ||
| 20 | - | ||
| 21 | -fn vectors_dir() -> PathBuf { | ||
| 22 | - ec_testkit::fixture("vectors/hevc-jctvc") | ||
| 23 | -} | ||
| 24 | - | ||
| 25 | -/// The first output picture as 4:2:0 bytes cropped to the conformance window. | ||
| 26 | -fn cropped_yuv(frame: &Frame) -> Vec<u8> { | ||
| 27 | - let pic = &frame.picture; | ||
| 28 | - let win = &frame.window; | ||
| 29 | - // Conformance window offsets are in chroma samples for 4:2:0. | ||
| 30 | - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); | ||
| 31 | - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); | ||
| 32 | - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); | ||
| 33 | - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); | ||
| 34 | - let mut out = Vec::new(); | ||
| 35 | - for row in ly0..ly1 { | ||
| 36 | - out.extend( | ||
| 37 | - pic.y[row * pic.width + lx0..row * pic.width + lx1] | ||
| 38 | - .iter() | ||
| 39 | - .map(|&v| v as u8), | ||
| 40 | - ); | ||
| 41 | - } | ||
| 42 | - let cw = pic.width / 2; | ||
| 43 | - for plane in [&pic.cb, &pic.cr] { | ||
| 44 | - for row in cy0..cy1 { | ||
| 45 | - out.extend( | ||
| 46 | - plane[row * cw + cx0..row * cw + cx1] | ||
| 47 | - .iter() | ||
| 48 | - .map(|&v| v as u8), | ||
| 49 | - ); | ||
| 50 | - } | ||
| 51 | - } | ||
| 52 | - out | ||
| 53 | -} | ||
| 54 | - | ||
| 55 | -/// The first frame of `path` as ffmpeg decodes it, in yuv420p. | ||
| 56 | -fn ffmpeg_first_frame(path: &Path, tag: &str) -> Result<Vec<u8>, String> { | ||
| 57 | - let out = std::env::temp_dir().join(format!("ec-h265-scaling-{tag}.yuv")); | ||
| 58 | - let status = ec_testkit::ffmpeg() | ||
| 59 | - .args(["-v", "error", "-y", "-i"]) | ||
| 60 | - .arg(path) | ||
| 61 | - .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) | ||
| 62 | - .arg(&out) | ||
| 63 | - .output() | ||
| 64 | - .map_err(|e| e.to_string())?; | ||
| 65 | - if !status.status.success() { | ||
| 66 | - return Err(String::from_utf8_lossy(&status.stderr).to_string()); | ||
| 67 | - } | ||
| 68 | - std::fs::read(&out).map_err(|e| e.to_string()) | ||
| 69 | -} | ||
| 70 | - | ||
| 71 | -// Ignored until the intra path decodes the syntax these streams use: the decode | ||
| 72 | -// desyncs at the last CTB of the IDR, and the intra CTU loop has no SAO or | ||
| 73 | -// cu_qp_delta parsing. Run with `--ignored` to see the failure. | ||
| 74 | -#[ignore = "intra path lacks the syntax these streams use (desync at the IDR's last CTB)"] | ||
| 75 | -#[test] | ||
| 76 | -fn first_picture_of_each_scaling_list_stream_matches_ffmpeg() { | ||
| 77 | - let dir = vectors_dir(); | ||
| 78 | - let mut checked = 0usize; | ||
| 79 | - for rel in STREAMS { | ||
| 80 | - let path = dir.join(rel); | ||
| 81 | - let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{rel}: {e}")); | ||
| 82 | - let mut decoder = Decoder::new(); | ||
| 83 | - decoder | ||
| 84 | - .decode_annex_b(&data) | ||
| 85 | - .unwrap_or_else(|e| panic!("{rel}: decode failed: {e}")); | ||
| 86 | - decoder | ||
| 87 | - .flush() | ||
| 88 | - .unwrap_or_else(|e| panic!("{rel}: flush failed: {e}")); | ||
| 89 | - let frame = decoder | ||
| 90 | - .next_frame() | ||
| 91 | - .unwrap_or_else(|| panic!("{rel}: no picture out")); | ||
| 92 | - let ours = cropped_yuv(&frame); | ||
| 93 | - let tag = rel.replace('/', "_"); | ||
| 94 | - let theirs = | ||
| 95 | - ffmpeg_first_frame(&path, &tag).unwrap_or_else(|e| panic!("{rel}: ffmpeg failed: {e}")); | ||
| 96 | - assert_eq!( | ||
| 97 | - ours.len(), | ||
| 98 | - theirs.len(), | ||
| 99 | - "{rel}: picture is {} bytes, ffmpeg's is {}", | ||
| 100 | - ours.len(), | ||
| 101 | - theirs.len() | ||
| 102 | - ); | ||
| 103 | - let differing = ours.iter().zip(&theirs).filter(|(a, b)| a != b).count(); | ||
| 104 | - assert_eq!( | ||
| 105 | - differing, 0, | ||
| 106 | - "{rel}: {differing} samples differ from ffmpeg in the first picture" | ||
| 107 | - ); | ||
| 108 | - checked += 1; | ||
| 109 | - } | ||
| 110 | - eprintln!("scaling-list check: {checked} first pictures bit-exact against ffmpeg"); | ||
| 111 | -} | ||