Unavailable neighbours carry reference index -1, not 0
Browse files at this commit276058ca79228133ba96a3e0bba5225a1f9f82f1Parent: 4a55700- fix
- unavailable neighbours carry reference index -1, not 0
4 changed files +399 -5
- crates/ec-h264/src/cabac.rs +5 -3
- crates/ec-h264/src/decoder.rs +50 -0
- crates/ec-h264/src/mv.rs +14 -1
- crates/ec-h264/tests/conformance.rs +330 -1
crates/ec-h264/src/cabac.rsmodified+5 -3
| @@ -639,11 +639,13 @@ impl<'a> Cabac<'a> { | |||
| 639 | } | 639 | } |
| 640 | 640 | ||
| 641 | /// condTermFlagN for a DC block: bit `which` of the neighbour's DC | 641 | /// condTermFlagN for a DC block: bit `which` of the neighbour's DC |
| 642 | - /// coded_block_flags, with I_PCM counting as coded and an unavailable | 642 | + /// coded_block_flags, with I_PCM counting as coded. An unavailable |
| 643 | - /// neighbour as set (the current macroblock is always intra here). | 643 | + /// neighbour counts as set only for an intra macroblock (9.3.3.1.1.9) — |
| 644 | + /// the chroma DC block of an inter macroblock at the picture edge reads | ||
| 645 | + /// the opposite value. | ||
| 644 | fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize { | 646 | fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize { |
| 645 | match n { | 647 | match n { |
| 646 | - None => 1, | 648 | + None => usize::from(self.cur_intra), |
| 647 | Some(i) if i.flags & FLAG_PCM != 0 => 1, | 649 | Some(i) if i.flags & FLAG_PCM != 0 => 1, |
| 648 | Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), | 650 | Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), |
| 649 | } | 651 | } |
crates/ec-h264/src/decoder.rsmodified+50 -0
| @@ -52,6 +52,18 @@ use crate::transform::{ | |||
| 52 | unzigzag, unzigzag_ac15, | 52 | unzigzag, unzigzag_ac15, |
| 53 | }; | 53 | }; |
| 54 | 54 | ||
| 55 | +/// Debug tracing gates, resolved once: reading the environment per macroblock | ||
| 56 | +/// would allocate, which the zero-allocation test would (rightly) catch. | ||
| 57 | +fn trace_enabled() -> bool { | ||
| 58 | + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
| 59 | + *ON.get_or_init(|| std::env::var_os("EC_H264_TRACE").is_some()) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +fn no_deblock() -> bool { | ||
| 63 | + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); | ||
| 64 | + *ON.get_or_init(|| std::env::var_os("EC_H264_NO_DEBLOCK").is_some()) | ||
| 65 | +} | ||
| 66 | + | ||
| 55 | /// Where a 4x4 block's top-right neighbour samples come from, per | 67 | /// Where a 4x4 block's top-right neighbour samples come from, per |
| 56 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). | 68 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). |
| 57 | #[derive(Clone, Copy, PartialEq)] | 69 | #[derive(Clone, Copy, PartialEq)] |
| @@ -492,6 +504,14 @@ impl Decoder { | |||
| 492 | weights: sh.pred_weight_table.clone(), | 504 | weights: sh.pred_weight_table.clone(), |
| 493 | poc: self.cur.poc, | 505 | poc: self.cur.poc, |
| 494 | }; | 506 | }; |
| 507 | + if trace_enabled() { | ||
| 508 | + eprintln!( | ||
| 509 | + "SLICE type {:?} qp {} cabac_init_idc {} l0 {} l1 {} first_mb {first_mb} \ | ||
| 510 | + header_bits {} bytes {:02x?}", | ||
| 511 | + sh.slice_type, sh.slice_qp, sh.cabac_init_idc, sh.num_ref_idx_l0_active, | ||
| 512 | + sh.num_ref_idx_l1_active, sh.header_bits, &rbsp[..rbsp.len().min(6)] | ||
| 513 | + ); | ||
| 514 | + } | ||
| 495 | let intra_slice = sh.slice_type.is_intra(); | 515 | let intra_slice = sh.slice_type.is_intra(); |
| 496 | let b_slice = sh.slice_type == SliceType::B; | 516 | let b_slice = sh.slice_type == SliceType::B; |
| 497 | if !intra_slice && ctx.lists[0].len() == 0 { | 517 | if !intra_slice && ctx.lists[0].len() == 0 { |
| @@ -1014,6 +1034,12 @@ fn decode_macroblock( | |||
| 1014 | (None, Some(mb_type)) | 1034 | (None, Some(mb_type)) |
| 1015 | }; | 1035 | }; |
| 1016 | r.set_intra(intra_type.is_some()); | 1036 | r.set_intra(intra_type.is_some()); |
| 1037 | + if trace_enabled() { | ||
| 1038 | + eprintln!( | ||
| 1039 | + "MB {mb_addr} ({mb_x},{mb_y}) type {} skipped {skipped} qp {}", | ||
| 1040 | + mb_type as i64, ctx.qp | ||
| 1041 | + ); | ||
| 1042 | + } | ||
| 1017 | 1043 | ||
| 1018 | if let Some(shape) = shape { | 1044 | if let Some(shape) = shape { |
| 1019 | return decode_inter_mb( | 1045 | return decode_inter_mb( |
| @@ -1413,6 +1439,9 @@ fn decode_inter_mb( | |||
| 1413 | if shape.sub && !skipped { | 1439 | if shape.sub && !skipped { |
| 1414 | for part in 0..4 { | 1440 | for part in 0..4 { |
| 1415 | let t = r.sub_mb_type(b)? as usize; | 1441 | let t = r.sub_mb_type(b)? as usize; |
| 1442 | + if trace_enabled() { | ||
| 1443 | + eprintln!(" sub_mb_type[{part}] = {t}"); | ||
| 1444 | + } | ||
| 1416 | motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; | 1445 | motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; |
| 1417 | if motion.sub[part].pred == Pred::Direct { | 1446 | if motion.sub[part].pred == Pred::Direct { |
| 1418 | for k in 0..4 { | 1447 | for k in 0..4 { |
| @@ -1498,6 +1527,9 @@ fn decode_inter_mb( | |||
| 1498 | 0 | 1527 | 0 |
| 1499 | }; | 1528 | }; |
| 1500 | let v = r.mvd(comp, inc)?; | 1529 | let v = r.mvd(comp, inc)?; |
| 1530 | + if trace_enabled() { | ||
| 1531 | + eprintln!(" mvd part {part} sp {sp} list {list} comp {comp} inc {inc} = {v}"); | ||
| 1532 | + } | ||
| 1501 | mvd[comp] = i16::try_from(v) | 1533 | mvd[comp] = i16::try_from(v) |
| 1502 | .map_err(|_| Error::corrupt("mvd outside the level limits"))?; | 1534 | .map_err(|_| Error::corrupt("mvd outside the level limits"))?; |
| 1503 | } | 1535 | } |
| @@ -1547,6 +1579,12 @@ fn decode_inter_mb( | |||
| 1547 | // partition width inside an 8x8. | 1579 | // partition width inside an 8x8. |
| 1548 | let n = mvc.neighbours(pic, px, py, pw, list); | 1580 | let n = mvc.neighbours(pic, px, py, pw, list); |
| 1549 | let mvp = predict_mv(&n, idx, shape.w, shape.h, part); | 1581 | let mvp = predict_mv(&n, idx, shape.w, shape.h, part); |
| 1582 | + if trace_enabled() { | ||
| 1583 | + eprintln!( | ||
| 1584 | + " nb A {:?} B {:?} C {:?} shape {}x{} part {part} mvp {mvp:?} written {:#06x}", | ||
| 1585 | + n[0], n[1], n[2], shape.w, shape.h, mvc.written | ||
| 1586 | + ); | ||
| 1587 | + } | ||
| 1550 | let d = motion.mvd[list][py * 4 + px]; | 1588 | let d = motion.mvd[list][py * 4 + px]; |
| 1551 | mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; | 1589 | mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; |
| 1552 | ref_idx[list] = idx; | 1590 | ref_idx[list] = idx; |
| @@ -1555,6 +1593,12 @@ fn decode_inter_mb( | |||
| 1555 | .map(|p| p.id) | 1593 | .map(|p| p.id) |
| 1556 | .unwrap_or(-1); | 1594 | .unwrap_or(-1); |
| 1557 | } | 1595 | } |
| 1596 | + if trace_enabled() { | ||
| 1597 | + eprintln!( | ||
| 1598 | + " MV part {part} sp {sp} at ({px},{py}) {pw}x{ph} mv {:?} ref {:?}", | ||
| 1599 | + mv[0], ref_idx | ||
| 1600 | + ); | ||
| 1601 | + } | ||
| 1558 | for dy in 0..ph { | 1602 | for dy in 0..ph { |
| 1559 | for dx in 0..pw { | 1603 | for dx in 0..pw { |
| 1560 | write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0); | 1604 | write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0); |
| @@ -1597,6 +1641,9 @@ fn decode_inter_mb( | |||
| 1597 | pic.i4_modes[base..base + 4].fill(2); | 1641 | pic.i4_modes[base..base + 4].fill(2); |
| 1598 | } | 1642 | } |
| 1599 | let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; | 1643 | let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; |
| 1644 | + if trace_enabled() { | ||
| 1645 | + eprintln!(" cbp {cbp_luma:#x}/{cbp_chroma}"); | ||
| 1646 | + } | ||
| 1600 | // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. | 1647 | // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. |
| 1601 | finish_macroblock( | 1648 | finish_macroblock( |
| 1602 | pic, | 1649 | pic, |
| @@ -2019,6 +2066,9 @@ fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) | |||
| 2019 | /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all | 2066 | /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all |
| 2020 | /// vertical edges then all horizontal edges per macroblock, then chroma. | 2067 | /// vertical edges then all horizontal edges per macroblock, then chroma. |
| 2021 | fn deblock_picture(pic: &mut Picture) { | 2068 | fn deblock_picture(pic: &mut Picture) { |
| 2069 | + if no_deblock() { | ||
| 2070 | + return; | ||
| 2071 | + } | ||
| 2022 | let mb_w = pic.mb_w; | 2072 | let mb_w = pic.mb_w; |
| 2023 | for mb_y in 0..pic.mb_h { | 2073 | for mb_y in 0..pic.mb_h { |
| 2024 | for mb_x in 0..mb_w { | 2074 | for mb_x in 0..mb_w { |
crates/ec-h264/src/mv.rsmodified+14 -1
| @@ -146,7 +146,7 @@ pub(crate) const B_SUB: [SubShape; 13] = [ | |||
| 146 | ]; | 146 | ]; |
| 147 | 147 | ||
| 148 | /// Motion data of one neighbouring partition (8.4.1.3.2). | 148 | /// Motion data of one neighbouring partition (8.4.1.3.2). |
| 149 | -#[derive(Clone, Copy, Debug, Default)] | 149 | +#[derive(Clone, Copy, Debug)] |
| 150 | pub(crate) struct Nb { | 150 | pub(crate) struct Nb { |
| 151 | /// The partition exists and has been decoded (clause 6.4.11.7). | 151 | /// The partition exists and has been decoded (clause 6.4.11.7). |
| 152 | pub avail: bool, | 152 | pub avail: bool, |
| @@ -155,6 +155,19 @@ pub(crate) struct Nb { | |||
| 155 | pub ref_idx: i8, | 155 | pub ref_idx: i8, |
| 156 | } | 156 | } |
| 157 | 157 | ||
| 158 | +impl Default for Nb { | ||
| 159 | + /// An unavailable partition, which 8.4.1.3.2 gives reference index -1 — | ||
| 160 | + /// *not* 0. A derived `Default` would make it look like a neighbour on | ||
| 161 | + /// reference picture 0 and hand the median rules a phantom match. | ||
| 162 | + fn default() -> Nb { | ||
| 163 | + Nb { | ||
| 164 | + avail: false, | ||
| 165 | + mv: [0; 2], | ||
| 166 | + ref_idx: -1, | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | +} | ||
| 170 | + | ||
| 158 | /// Where the current macroblock's motion data is being written, and which of | 171 | /// Where the current macroblock's motion data is being written, and which of |
| 159 | /// its 4x4 blocks already carry it. | 172 | /// its 4x4 blocks already carry it. |
| 160 | pub(crate) struct MvCtx { | 173 | pub(crate) struct MvCtx { |
crates/ec-h264/tests/conformance.rsmodified+330 -1
| @@ -20,7 +20,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; | |||
| 20 | 20 | ||
| 21 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; | 21 | use ec_core::registry::{CodecId, CodecParameters, Decoder as _}; |
| 22 | use ec_core::{Buf, Frame, Packet, TimeBase}; | 22 | use ec_core::{Buf, Frame, Packet, TimeBase}; |
| 23 | -use ec_h264::{Decoder, Error, H264Decoder}; | 23 | +use ec_h264::{Decoder, Error, H264Decoder, NalOutcome}; |
| 24 | 24 | ||
| 25 | // --------------------------------------------------------------------------- | 25 | // --------------------------------------------------------------------------- |
| 26 | // Counting allocator: proves the steady-state decode loop allocates nothing. | 26 | // Counting allocator: proves the steady-state decode loop allocates nothing. |
| @@ -157,6 +157,137 @@ fn first_diff(a: &[u8], b: &[u8]) -> Option<usize> { | |||
| 157 | a.iter().zip(b).position(|(x, y)| x != y) | 157 | a.iter().zip(b).position(|(x, y)| x != y) |
| 158 | } | 158 | } |
| 159 | 159 | ||
| 160 | +/// Pack a decoded frame as contiguous I420 bytes. | ||
| 161 | +fn frame_bytes(frame: &ec_core::frame::VideoFrame) -> Vec<u8> { | ||
| 162 | + let (w, h) = (frame.width as usize, frame.height as usize); | ||
| 163 | + let mut out = Vec::with_capacity(w * h * 3 / 2); | ||
| 164 | + let dims = [ | ||
| 165 | + (w, h), | ||
| 166 | + (w.div_ceil(2), h.div_ceil(2)), | ||
| 167 | + (w.div_ceil(2), h.div_ceil(2)), | ||
| 168 | + ]; | ||
| 169 | + for (plane, (pw, ph)) in frame.planes.iter().zip(dims) { | ||
| 170 | + for y in 0..ph { | ||
| 171 | + out.extend_from_slice(plane.row(y, pw).expect("plane row")); | ||
| 172 | + } | ||
| 173 | + } | ||
| 174 | + out | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +/// Decode a whole Annex B stream, returning every frame in display order. | ||
| 178 | +fn decode_all(bytes: &[u8]) -> Result<Vec<Vec<u8>>, Error> { | ||
| 179 | + let mut dec = Decoder::new(); | ||
| 180 | + let mut frames = Vec::new(); | ||
| 181 | + for nal in ec_h264_syntax::AnnexBIter::new(bytes) { | ||
| 182 | + match dec.push_nal(nal)? { | ||
| 183 | + NalOutcome::PictureBoundary => { | ||
| 184 | + dec.end_picture()?; | ||
| 185 | + dec.push_nal(nal)?; | ||
| 186 | + } | ||
| 187 | + _ => {} | ||
| 188 | + } | ||
| 189 | + while let Some(f) = dec.next_frame() { | ||
| 190 | + frames.push(frame_bytes(&f)); | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + dec.flush()?; | ||
| 194 | + while let Some(f) = dec.next_frame() { | ||
| 195 | + frames.push(frame_bytes(&f)); | ||
| 196 | + } | ||
| 197 | + Ok(frames) | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Every frame ffmpeg decodes from `stream`, as raw I420. | ||
| 201 | +fn ffmpeg_all_frames(stream: &Path, frame_len: usize) -> Option<Vec<Vec<u8>>> { | ||
| 202 | + let mut cmd = Command::new("ffmpeg"); | ||
| 203 | + cmd.args(["-v", "error"]); | ||
| 204 | + if std::env::var_os("EC_H264_NO_DEBLOCK").is_some() { | ||
| 205 | + cmd.args(["-skip_loop_filter", "all"]); | ||
| 206 | + } | ||
| 207 | + let out = cmd | ||
| 208 | + .arg("-i") | ||
| 209 | + .arg(stream) | ||
| 210 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 211 | + .output() | ||
| 212 | + .ok()?; | ||
| 213 | + if !out.status.success() || out.stdout.is_empty() { | ||
| 214 | + return None; | ||
| 215 | + } | ||
| 216 | + Some( | ||
| 217 | + out.stdout | ||
| 218 | + .chunks_exact(frame_len) | ||
| 219 | + .map(<[u8]>::to_vec) | ||
| 220 | + .collect(), | ||
| 221 | + ) | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// Encode a multi-frame clip with x264 and return the Annex B file. | ||
| 225 | +fn x264_encode_gop( | ||
| 226 | + dir: &Path, | ||
| 227 | + tag: &str, | ||
| 228 | + size: &str, | ||
| 229 | + frames: u32, | ||
| 230 | + extra: &[&str], | ||
| 231 | +) -> Option<PathBuf> { | ||
| 232 | + let stream = dir.join(format!("{tag}.264")); | ||
| 233 | + let source = format!("testsrc=size={size}:rate=25:duration=4"); | ||
| 234 | + let mut args: Vec<String> = [ | ||
| 235 | + "-hide_banner", | ||
| 236 | + "-loglevel", | ||
| 237 | + "error", | ||
| 238 | + "-y", | ||
| 239 | + "-f", | ||
| 240 | + "lavfi", | ||
| 241 | + "-i", | ||
| 242 | + ] | ||
| 243 | + .iter() | ||
| 244 | + .map(|s| s.to_string()) | ||
| 245 | + .collect(); | ||
| 246 | + args.push(source); | ||
| 247 | + if !extra.contains(&"-pix_fmt") { | ||
| 248 | + args.extend(["-pix_fmt".into(), "yuv420p".into()]); | ||
| 249 | + } | ||
| 250 | + args.extend([ | ||
| 251 | + "-c:v".into(), | ||
| 252 | + "libx264".into(), | ||
| 253 | + "-frames:v".into(), | ||
| 254 | + frames.to_string(), | ||
| 255 | + ]); | ||
| 256 | + args.extend(extra.iter().map(|s| s.to_string())); | ||
| 257 | + args.extend([ | ||
| 258 | + "-f".into(), | ||
| 259 | + "h264".into(), | ||
| 260 | + stream.to_string_lossy().into_owned(), | ||
| 261 | + ]); | ||
| 262 | + let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); | ||
| 263 | + run("ffmpeg", &refs).then_some(stream) | ||
| 264 | +} | ||
| 265 | + | ||
| 266 | +/// Decode `stream` both ways and report the first frame that differs. | ||
| 267 | +fn compare_sequence(stream: &Path) -> Result<usize, String> { | ||
| 268 | + let bytes = std::fs::read(stream).map_err(|e| e.to_string())?; | ||
| 269 | + let ours = decode_all(&bytes).map_err(|e| format!("{e}"))?; | ||
| 270 | + let first = ours.first().ok_or("no frames decoded")?; | ||
| 271 | + let theirs = | ||
| 272 | + ffmpeg_all_frames(stream, first.len()).ok_or("ffmpeg cannot decode the stream")?; | ||
| 273 | + if ours.len() != theirs.len() { | ||
| 274 | + return Err(format!( | ||
| 275 | + "{} frames decoded, ffmpeg gave {}", | ||
| 276 | + ours.len(), | ||
| 277 | + theirs.len() | ||
| 278 | + )); | ||
| 279 | + } | ||
| 280 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 281 | + if let Some(pos) = first_diff(a, b) { | ||
| 282 | + return Err(format!( | ||
| 283 | + "frame {i} differs at byte {pos}: ours {} ffmpeg {}", | ||
| 284 | + a[pos], b[pos] | ||
| 285 | + )); | ||
| 286 | + } | ||
| 287 | + } | ||
| 288 | + Ok(ours.len()) | ||
| 289 | +} | ||
| 290 | + | ||
| 160 | #[test] | 291 | #[test] |
| 161 | fn jvt_cavlc_first_idr_bit_exact() { | 292 | fn jvt_cavlc_first_idr_bit_exact() { |
| 162 | let base = vectors_dir(); | 293 | let base = vectors_dir(); |
| @@ -907,3 +1038,201 @@ fn avcc_extradata_and_length_prefixed_packets() { | |||
| 907 | assert_eq!(avcc_frame, annex_b_frame); | 1038 | assert_eq!(avcc_frame, annex_b_frame); |
| 908 | let _ = std::fs::remove_dir_all(&dir); | 1039 | let _ = std::fs::remove_dir_all(&dir); |
| 909 | } | 1040 | } |
| 1041 | + | ||
| 1042 | +// --------------------------------------------------------------------------- | ||
| 1043 | +// Inter prediction, the decoded picture buffer and display order. | ||
| 1044 | +// --------------------------------------------------------------------------- | ||
| 1045 | + | ||
| 1046 | +/// A P-only GOP, every frame bit-exact against ffmpeg, under both entropy | ||
| 1047 | +/// coders. This is the narrowest thing that exercises motion compensation, the | ||
| 1048 | +/// reference list, sliding-window marking and the inter boundary strengths at | ||
| 1049 | +/// once, so it is the first test to look at when any of them regress. | ||
| 1050 | +#[test] | ||
| 1051 | +fn p_only_gop_matches_ffmpeg_every_frame() { | ||
| 1052 | + if !have_ffmpeg() { | ||
| 1053 | + eprintln!("SKIP: ffmpeg not on PATH"); | ||
| 1054 | + return; | ||
| 1055 | + } | ||
| 1056 | + let dir = scratch("p-gop"); | ||
| 1057 | + let mut failures = Vec::new(); | ||
| 1058 | + for (mode, profile) in ENTROPY_MODES { | ||
| 1059 | + let mut extra = profile.to_vec(); | ||
| 1060 | + extra.extend(["-qp", "26", "-x264-params", "bframes=0:weightp=0:ref=1"]); | ||
| 1061 | + let tag = format!("{mode}-p"); | ||
| 1062 | + match x264_encode_gop(&dir, &tag, "176x144", 12, &extra) { | ||
| 1063 | + Some(stream) => match compare_sequence(&stream) { | ||
| 1064 | + Ok(n) => eprintln!("{tag}: {n} frames bit-exact"), | ||
| 1065 | + Err(e) => failures.push(format!("{tag}: {e}")), | ||
| 1066 | + }, | ||
| 1067 | + None => failures.push(format!("{tag}: ffmpeg cannot encode")), | ||
| 1068 | + } | ||
| 1069 | + } | ||
| 1070 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 1071 | + assert!(failures.is_empty(), "{failures:#?}"); | ||
| 1072 | +} | ||
| 1073 | + | ||
| 1074 | +/// Scratch driver kept out of the default run: decode a stream named by | ||
| 1075 | +/// `EC_H264_DEBUG_STREAM` frame by frame and report the first mismatch. | ||
| 1076 | +#[test] | ||
| 1077 | +#[ignore] | ||
| 1078 | +fn debug_named_stream() { | ||
| 1079 | + let Ok(path) = std::env::var("EC_H264_DEBUG_STREAM") else { | ||
| 1080 | + return; | ||
| 1081 | + }; | ||
| 1082 | + let stream = PathBuf::from(path); | ||
| 1083 | + let bytes = std::fs::read(&stream).unwrap(); | ||
| 1084 | + let mut dec = Decoder::new(); | ||
| 1085 | + let mut pictures = 0usize; | ||
| 1086 | + for (i, nal) in ec_h264_syntax::AnnexBIter::new(&bytes).enumerate() { | ||
| 1087 | + let kind = nal[0] & 0x1F; | ||
| 1088 | + match dec.push_nal(nal) { | ||
| 1089 | + Ok(NalOutcome::PictureBoundary) => { | ||
| 1090 | + dec.end_picture().unwrap(); | ||
| 1091 | + pictures += 1; | ||
| 1092 | + if let Err(e) = dec.push_nal(nal) { | ||
| 1093 | + panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"); | ||
| 1094 | + } | ||
| 1095 | + } | ||
| 1096 | + Ok(_) => {} | ||
| 1097 | + Err(e) => panic!("nal {i} (type {kind}) after {pictures} pictures: {e}"), | ||
| 1098 | + } | ||
| 1099 | + while dec.next_frame().is_some() {} | ||
| 1100 | + } | ||
| 1101 | + dec.flush().unwrap(); | ||
| 1102 | + eprintln!("decoded {pictures} pictures"); | ||
| 1103 | + let ours = decode_all(&bytes).unwrap(); | ||
| 1104 | + let theirs = match std::env::var("EC_H264_DEBUG_REF") { | ||
| 1105 | + Ok(p) => { | ||
| 1106 | + let raw = std::fs::read(p).unwrap(); | ||
| 1107 | + raw.chunks_exact(ours[0].len()).map(<[u8]>::to_vec).collect() | ||
| 1108 | + } | ||
| 1109 | + Err(_) => ffmpeg_all_frames(&stream, ours[0].len()).unwrap(), | ||
| 1110 | + }; | ||
| 1111 | + if std::env::var_os("EC_H264_DUMP").is_some() { | ||
| 1112 | + let w = 176usize; | ||
| 1113 | + for (label, f) in [("ref0", &ours[0]), ("ours1", &ours[1]), ("ff1", &theirs[1])] { | ||
| 1114 | + eprintln!("--- {label} MB(0,0) rows 0..4 ---"); | ||
| 1115 | + for y in 0..4 { | ||
| 1116 | + let row: Vec<u8> = (0..16).map(|x| f[y * w + x]).collect(); | ||
| 1117 | + eprintln!("{row:?}"); | ||
| 1118 | + } | ||
| 1119 | + } | ||
| 1120 | + } | ||
| 1121 | + for (i, a) in ours.iter().enumerate().take(4) { | ||
| 1122 | + let best = theirs | ||
| 1123 | + .iter() | ||
| 1124 | + .enumerate() | ||
| 1125 | + .map(|(j, b)| (a.iter().zip(b).filter(|(x, y)| x != y).count(), j)) | ||
| 1126 | + .min(); | ||
| 1127 | + eprintln!("our frame {i} best matches reference {best:?}"); | ||
| 1128 | + } | ||
| 1129 | + let w = 176usize; | ||
| 1130 | + let h = 144usize; | ||
| 1131 | + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { | ||
| 1132 | + let diff = a.iter().zip(b).filter(|(x, y)| x != y).count(); | ||
| 1133 | + if diff == 0 { | ||
| 1134 | + eprintln!("frame {i}: exact"); | ||
| 1135 | + continue; | ||
| 1136 | + } | ||
| 1137 | + let mut mbs = std::collections::BTreeSet::new(); | ||
| 1138 | + for (k, (x, y)) in a.iter().zip(b).enumerate().take(w * h) { | ||
| 1139 | + if x != y { | ||
| 1140 | + mbs.insert(((k / w) / 16 * (w / 16) + (k % w) / 16, ((k % w) / 16, (k / w) / 16))); | ||
| 1141 | + } | ||
| 1142 | + } | ||
| 1143 | + eprintln!(" first differing MBs: {:?}", mbs.iter().take(6).map(|m| m.1).collect::<Vec<_>>()); | ||
| 1144 | + let max = a | ||
| 1145 | + .iter() | ||
| 1146 | + .zip(b) | ||
| 1147 | + .map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs()) | ||
| 1148 | + .max() | ||
| 1149 | + .unwrap_or(0); | ||
| 1150 | + eprintln!( | ||
| 1151 | + "frame {i}: {diff} bytes differ, max delta {max}, {} luma MBs", | ||
| 1152 | + mbs.len() | ||
| 1153 | + ); | ||
| 1154 | + } | ||
| 1155 | +} | ||
| 1156 | + | ||
| 1157 | +/// JVT conformance, every frame of every vector: our display-order output | ||
| 1158 | +/// against the reference decoder YUV that ships with the vector. | ||
| 1159 | +/// | ||
| 1160 | +/// The first-IDR test above proves intra reconstruction; this one is what | ||
| 1161 | +/// proves inter prediction, the decoded picture buffer and output order, | ||
| 1162 | +/// because a single wrong motion vector or a reference marked at the wrong | ||
| 1163 | +/// moment shows up as a mismatch in some later frame, not the first. | ||
| 1164 | +#[test] | ||
| 1165 | +fn jvt_full_sequence_bit_exact() { | ||
| 1166 | + let base = vectors_dir(); | ||
| 1167 | + if !base.is_dir() { | ||
| 1168 | + eprintln!("SKIP: {} missing", base.display()); | ||
| 1169 | + return; | ||
| 1170 | + } | ||
| 1171 | + let mut table = String::new(); | ||
| 1172 | + let mut passed = 0usize; | ||
| 1173 | + let mut refused = Vec::new(); | ||
| 1174 | + let mut failed = Vec::new(); | ||
| 1175 | + for name in all_vectors(&base) { | ||
| 1176 | + let dir = base.join(&name); | ||
| 1177 | + let Some(stream) = find_stream(&dir) else { | ||
| 1178 | + continue; | ||
| 1179 | + }; | ||
| 1180 | + let bytes = std::fs::read(&stream).unwrap(); | ||
| 1181 | + match decode_all(&bytes) { | ||
| 1182 | + Ok(frames) if frames.is_empty() => { | ||
| 1183 | + failed.push(format!("{name}: decoded no frames")); | ||
| 1184 | + } | ||
| 1185 | + Ok(frames) => { | ||
| 1186 | + let len = frames[0].len(); | ||
| 1187 | + let Some(ref_path) = find_ref_yuv(&dir) else { | ||
| 1188 | + table.push_str(&format!("{name:<16} {:>3} frames, no reference YUV\n", frames.len())); | ||
| 1189 | + continue; | ||
| 1190 | + }; | ||
| 1191 | + let reference = std::fs::read(&ref_path).unwrap(); | ||
| 1192 | + let want = reference.len() / len; | ||
| 1193 | + let mut bad = None; | ||
| 1194 | + for (i, f) in frames.iter().enumerate() { | ||
| 1195 | + let Some(chunk) = reference.get(i * len..(i + 1) * len) else { | ||
| 1196 | + break; | ||
| 1197 | + }; | ||
| 1198 | + if let Some(pos) = first_diff(f, chunk) { | ||
| 1199 | + bad = Some((i, pos)); | ||
| 1200 | + break; | ||
| 1201 | + } | ||
| 1202 | + } | ||
| 1203 | + match bad { | ||
| 1204 | + None if frames.len() == want => { | ||
| 1205 | + passed += 1; | ||
| 1206 | + table.push_str(&format!("{name:<16} {:>3}/{want:<3} frames bit-exact\n", frames.len())); | ||
| 1207 | + } | ||
| 1208 | + None => { | ||
| 1209 | + failed.push(format!( | ||
| 1210 | + "{name}: {} frames decoded, reference has {want}", | ||
| 1211 | + frames.len() | ||
| 1212 | + )); | ||
| 1213 | + table.push_str(&format!("{name:<16} {:>3}/{want:<3} FRAME COUNT\n", frames.len())); | ||
| 1214 | + } | ||
| 1215 | + Some((i, pos)) => { | ||
| 1216 | + failed.push(format!("{name}: frame {i} differs at byte {pos}")); | ||
| 1217 | + table.push_str(&format!("{name:<16} {:>3}/{want:<3} MISMATCH frame {i}\n", frames.len())); | ||
| 1218 | + } | ||
| 1219 | + } | ||
| 1220 | + } | ||
| 1221 | + Err(e @ Error::Unsupported { .. }) => { | ||
| 1222 | + refused.push(name.clone()); | ||
| 1223 | + table.push_str(&format!("{name:<16} refused: {e}\n")); | ||
| 1224 | + } | ||
| 1225 | + Err(e) => { | ||
| 1226 | + failed.push(format!("{name}: {e}")); | ||
| 1227 | + table.push_str(&format!("{name:<16} ERROR {e}\n")); | ||
| 1228 | + } | ||
| 1229 | + } | ||
| 1230 | + } | ||
| 1231 | + eprintln!("{table}"); | ||
| 1232 | + eprintln!( | ||
| 1233 | + "full-sequence: {passed} bit-exact, {} refused by name, {} failed", | ||
| 1234 | + refused.len(), | ||
| 1235 | + failed.len() | ||
| 1236 | + ); | ||
| 1237 | + assert!(failed.is_empty(), "{failed:#?}"); | ||
| 1238 | +} | ||