forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

dec_shell.rs476 lines, 15.7 KiBHistoryRawDownload
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//! output. The sweep is skipped when the vectors are absent.
8
9use std::collections::VecDeque;
10use std::path::{Path, PathBuf};
11use std::process::Command;
12
13use ec_h265::dec::dpb::{Dpb, DpbLimits, Marking, PendingFrame};
14use ec_h265::dec::poc::derive_poc;
15use ec_h265::dec::rps::{RpsInput, build_ref_lists};
16use ec_h265::dec::shared::SharedPic;
17use ec_h265::dec::{Decoder, NalOutcome};
18use ec_h265::decode::DecodedPicture;
19use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType};
20use ec_h265_syntax::{ConformanceWindow, Pps, ShortTermRefPicSet};
21
22fn picture(w: usize, h: usize) -> DecodedPicture {
23 DecodedPicture {
24 width: w,
25 height: h,
26 bit_depth: 8,
27 bit_depth_c: 8,
28 chroma_format_idc: 1,
29 y: Vec::new(),
30 cb: Vec::new(),
31 cr: Vec::new(),
32 }
33}
34
35fn st_set(before: &[i32], after: &[i32]) -> ShortTermRefPicSet {
36 let mut st = ShortTermRefPicSet {
37 num_negative: before.len() as u32,
38 num_positive: after.len() as u32,
39 ..ShortTermRefPicSet::default()
40 };
41 for (i, &d) in before.iter().enumerate() {
42 st.delta_poc_s0[i] = d;
43 st.used_s0[i] = true;
44 }
45 for (i, &d) in after.iter().enumerate() {
46 st.delta_poc_s1[i] = d;
47 st.used_s1[i] = true;
48 }
49 st
50}
51
52fn rps_input<'a>(
53 poc: i32,
54 st: &'a ShortTermRefPicSet,
55 lt: &'a [LongTermRef],
56 fill: Option<(u32, u32)>,
57) -> RpsInput<'a> {
58 RpsInput {
59 poc,
60 log2_max_poc_lsb: 4,
61 st,
62 lt,
63 irap_no_rasl: false,
64 width: 16,
65 height: 16,
66 chroma_format_idc: 1,
67 fill,
68 }
69}
70
71fn add(dpb: &mut Dpb, poc: i32, marking: Marking, output: bool) -> u32 {
72 dpb.insert(
73 poc,
74 marking,
75 output,
76 std::sync::Arc::new(SharedPic::from_planes(poc, picture(16, 16))),
77 ConformanceWindow::default(),
78 poc as u32,
79 )
80}
81
82#[test]
83fn poc_follows_the_lsb_without_wrapping() {
84 assert_eq!(derive_poc(5, 4, 7, false), 7);
85 assert_eq!(derive_poc(0, 4, 0, false), 0);
86}
87
88#[test]
89fn poc_msb_wraps_forward_at_the_half_window() {
90 // prevTid0 = 0, lsb 14 of 16: 14 - 0 > 8, so the MSB is -16 and POC is -2.
91 assert_eq!(derive_poc(0, 4, 14, false), -2);
92}
93
94#[test]
95fn poc_msb_wraps_backward_past_the_maximum() {
96 // prevTid0 = 14 (lsb 14), lsb 2: 14 - 2 >= 8, so the MSB advances to 16.
97 assert_eq!(derive_poc(14, 4, 2, false), 18);
98}
99
100#[test]
101fn poc_of_an_irap_with_no_rasl_output_has_no_msb() {
102 assert_eq!(derive_poc(37, 4, 5, true), 5);
103}
104
105#[test]
106fn rps_marks_what_it_names_and_drops_the_rest() {
107 let mut dpb = Dpb::new();
108 let ids: Vec<u32> = [0, 1, 2, 3, 4, 5, 6, 7]
109 .iter()
110 .map(|&p| add(&mut dpb, p, Marking::ShortTerm, false))
111 .collect();
112 // Current POC 8 names 7, 5 and 4 (deltas -1, -3, -4). 0..3 and 6 drop out.
113 let st = st_set(&[-1, -3, -4], &[]);
114 let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8))));
115 let before: Vec<i32> = set.st_curr_before.iter().map(|e| e.poc).collect();
116 assert_eq!(before, vec![7, 5, 4]);
117 assert!(set.st_curr_after.is_empty());
118 assert!(set.lt_curr.is_empty());
119 assert_eq!(set.st_curr_before[0].id, ids[7]);
120 for &p in &[0usize, 1, 2, 3, 6] {
121 assert_eq!(dpb.get(ids[p]).unwrap().marking, Marking::Unused, "POC {p}");
122 }
123 assert_eq!(dpb.get(ids[5]).unwrap().marking, Marking::ShortTerm);
124 dpb.remove_unneeded();
125 assert_eq!(dpb.len(), 3);
126}
127
128#[test]
129fn rps_generates_a_missing_reference_as_grey() {
130 let mut dpb = Dpb::new();
131 add(&mut dpb, 4, Marking::ShortTerm, false);
132 // Current POC 8 names POC 6 (absent) and POC 4.
133 let st = st_set(&[-2, -4], &[]);
134 let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8))));
135 assert_eq!(set.st_curr_before.len(), 2);
136 let generated = dpb
137 .get(set.st_curr_before[0].id)
138 .expect("generated picture");
139 assert_eq!(generated.poc, 6);
140 assert!(!generated.needed_for_output);
141 let planes = generated.picture.read_planes();
142 assert_eq!(planes.y.len(), 16 * 16);
143 assert!(planes.y.iter().all(|&v| v == 128));
144}
145
146#[test]
147fn rps_long_term_entry_matches_by_lsb_and_converts_marking() {
148 let mut dpb = Dpb::new();
149 let lt_id = add(&mut dpb, 16, Marking::ShortTerm, false);
150 // PocLsbLt 0 with no MSB: the picture with POC & 15 == 0 is POC 16.
151 let lt = [LongTermRef {
152 poc_lsb_lt: 0,
153 used_by_curr: true,
154 delta_poc_msb_present: false,
155 delta_poc_msb_cycle: 0,
156 }];
157 let st = ShortTermRefPicSet::default();
158 let set = dpb.apply_rps(&rps_input(20, &st, &lt, Some((8, 8))));
159 assert_eq!(set.lt_curr.len(), 1);
160 assert_eq!(set.lt_curr[0].id, lt_id);
161 assert!(set.lt_curr[0].long_term);
162 assert_eq!(dpb.get(lt_id).unwrap().marking, Marking::LongTerm);
163}
164
165#[test]
166fn bumping_outputs_in_poc_order_under_the_reorder_limit() {
167 let limits = DpbLimits {
168 max_dec_pic_buffering: 6,
169 max_num_reorder: 2,
170 max_latency_plus1: 0,
171 };
172 let mut dpb = Dpb::new();
173 let mut out: VecDeque<PendingFrame> = VecDeque::new();
174 // Decode order 0, 8, 4, 2: a reorder limit of 2 forces output as it goes.
175 for poc in [0, 8, 4, 2] {
176 add(&mut dpb, poc, Marking::Unused, true);
177 while dpb.needs_bumping(&limits, false) && dpb.bump(&mut out) {}
178 }
179 let early: Vec<i32> = out.iter().map(|f| f.poc).collect();
180 assert_eq!(early, vec![0, 2]);
181 dpb.drain(&mut out);
182 let all: Vec<i32> = out.iter().map(|f| f.poc).collect();
183 assert_eq!(all, vec![0, 2, 4, 8]);
184 assert!(dpb.is_empty());
185}
186
187#[test]
188fn bumping_honours_the_latency_limit() {
189 let limits = DpbLimits {
190 max_dec_pic_buffering: 6,
191 max_num_reorder: 4,
192 max_latency_plus1: 1,
193 };
194 let mut dpb = Dpb::new();
195 let mut out = VecDeque::new();
196 add(&mut dpb, 0, Marking::Unused, true);
197 assert!(!dpb.needs_bumping(&limits, false));
198 // SpsMaxLatencyPictures = 4 + 1 - 1 = 4: a picture that waited 4 times goes out.
199 dpb.pictures_mut()[0].latency = 4;
200 assert!(dpb.needs_bumping(&limits, false));
201 assert!(dpb.bump(&mut out));
202 assert_eq!(out.len(), 1);
203}
204
205#[test]
206fn bumping_drops_a_full_buffer_only_when_asked() {
207 let limits = DpbLimits {
208 max_dec_pic_buffering: 2,
209 max_num_reorder: 8,
210 max_latency_plus1: 0,
211 };
212 let mut dpb = Dpb::new();
213 add(&mut dpb, 0, Marking::ShortTerm, false);
214 add(&mut dpb, 2, Marking::ShortTerm, false);
215 assert!(dpb.needs_bumping(&limits, true));
216 assert!(!dpb.needs_bumping(&limits, false));
217}
218
219#[test]
220fn reference_lists_cycle_and_follow_the_modification() {
221 let mut dpb = Dpb::new();
222 let a = add(&mut dpb, 4, Marking::ShortTerm, false);
223 let b = add(&mut dpb, 6, Marking::ShortTerm, false);
224 let c = add(&mut dpb, 10, Marking::ShortTerm, false);
225 let st = st_set(&[-4, -2], &[2]);
226 let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8))));
227 assert_eq!(
228 set.st_curr_before.iter().map(|e| e.id).collect::<Vec<_>>(),
229 vec![a, b]
230 );
231 assert_eq!(
232 set.st_curr_after.iter().map(|e| e.id).collect::<Vec<_>>(),
233 vec![c]
234 );
235
236 let pps = Pps::default();
237 let mut header = SliceHeader::intra(&pps, 0);
238 header.slice_type = SliceType::B;
239 header.num_ref_idx_l0_active_minus1 = 3;
240 header.num_ref_idx_l1_active_minus1 = 1;
241 let lists = build_ref_lists(&set, &header).expect("lists");
242 let l0: Vec<u32> = lists.l0.iter().map(|e| e.id).collect();
243 assert_eq!(l0, vec![a, b, c, a]);
244 let l1: Vec<u32> = lists.l1.iter().map(|e| e.id).collect();
245 assert_eq!(l1, vec![c, a]);
246
247 header.list_entry = [vec![2, 2, 0, 1], vec![1, 0]];
248 let lists = build_ref_lists(&set, &header).expect("modified lists");
249 assert_eq!(
250 lists.l0.iter().map(|e| e.id).collect::<Vec<_>>(),
251 vec![c, c, a, b]
252 );
253 assert_eq!(
254 lists.l1.iter().map(|e| e.id).collect::<Vec<_>>(),
255 vec![a, c]
256 );
257}
258
259#[test]
260fn decoder_refuses_out_of_scope_parameter_sets_and_skips_layers() {
261 let mut dec = Decoder::new();
262 // A VPS-typed NAL on layer 1 is skipped whatever its payload.
263 let layer1 = [32u8 << 1, 0b0000_1001, 0xff];
264 assert_eq!(dec.push_nal(&layer1).unwrap(), NalOutcome::Skipped);
265 // SEI and filler are ignored.
266 assert_eq!(
267 dec.push_nal(&[39 << 1, 1, 0x80]).unwrap(),
268 NalOutcome::Skipped
269 );
270 assert_eq!(
271 dec.push_nal(&[62 << 1, 1, 0x80]).unwrap(),
272 NalOutcome::Skipped
273 );
274 assert!(dec.next_frame().is_none());
275}
276
277fn have_tool(tool: &str) -> bool {
278 Command::new(tool)
279 .arg("-version")
280 .output()
281 .map(|o| o.status.success())
282 .unwrap_or(false)
283}
284
285fn run(tool: &str, args: &[&str], file: &Path) -> Result<Vec<u8>, String> {
286 let out = Command::new(tool)
287 .args(["-v", "error"])
288 .args(args)
289 .arg(file)
290 .output()
291 .map_err(|e| e.to_string())?;
292 if !out.status.success() {
293 return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
294 }
295 Ok(out.stdout)
296}
297
298fn numbers(text: &[u8]) -> Vec<u64> {
299 String::from_utf8_lossy(text)
300 .lines()
301 .filter_map(|l| l.trim().trim_end_matches(',').parse().ok())
302 .collect()
303}
304
305/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's
306/// directory under `fixtures/vectors/hevc-jctvc` (or `EC_H265_JCTVC_DIR`), sorted
307/// by name. Some zips extract one directory deeper, so two levels are searched.
308fn streams() -> Vec<PathBuf> {
309 // EC_H265_JCTVC_DIR overrides the default, for hosts whose fixtures link is dangling.
310 let root = match std::env::var("EC_H265_JCTVC_DIR") {
311 Ok(dir) => PathBuf::from(dir),
312 Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/hevc-jctvc"),
313 };
314 fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec<PathBuf>) {
315 let Ok(entries) = std::fs::read_dir(dir) else {
316 return;
317 };
318 let mut paths: Vec<PathBuf> = entries.filter_map(|e| e.ok().map(|e| e.path())).collect();
319 paths.sort();
320 for p in paths {
321 if p.is_dir() && depth > 0 {
322 bitstreams_in(&p, depth - 1, out);
323 } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) {
324 out.push(p);
325 }
326 }
327 }
328 let Ok(dirs) = std::fs::read_dir(&root) else {
329 return Vec::new();
330 };
331 let mut dirs: Vec<PathBuf> = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect();
332 dirs.sort();
333 dirs.into_iter()
334 .filter(|d| d.is_dir())
335 .filter_map(|d| {
336 let mut found = Vec::new();
337 bitstreams_in(&d, 2, &mut found);
338 found.into_iter().next()
339 })
340 .collect()
341}
342
343/// Output order from our decoder, picture management only: (POC, AU index).
344fn our_order(data: &[u8]) -> Result<Vec<(i32, u32)>, String> {
345 let mut dec = Decoder::new();
346 dec.set_pixel_decode(false);
347 dec.decode_annex_b(data).map_err(|e| e.to_string())?;
348 dec.flush().map_err(|e| e.to_string())?;
349 let mut order = Vec::new();
350 while let Some(f) = dec.next_frame() {
351 order.push((f.poc, f.au_index));
352 }
353 Ok(order)
354}
355
356/// Output order from ffprobe: the access-unit index (by packet position in
357/// decode order) of each frame, in display order.
358fn ffprobe_order(path: &Path) -> Result<Vec<u32>, String> {
359 let packets = numbers(&run(
360 "ffprobe",
361 &[
362 "-select_streams",
363 "v:0",
364 "-show_entries",
365 "packet=pos",
366 "-of",
367 "csv=p=0",
368 ],
369 path,
370 )?);
371 let frames = numbers(&run(
372 "ffprobe",
373 &[
374 "-select_streams",
375 "v:0",
376 "-show_entries",
377 "frame=pkt_pos",
378 "-of",
379 "csv=p=0",
380 ],
381 path,
382 )?);
383 frames
384 .iter()
385 .map(|pos| {
386 packets
387 .iter()
388 .position(|p| p == pos)
389 .map(|i| i as u32)
390 .ok_or_else(|| format!("frame position {pos} is no packet position"))
391 })
392 .collect()
393}
394
395/// Streams where ffprobe is not the reference: the spec's frame count (from the
396/// conformance description) and why ffprobe differs. Our count must equal the spec's.
397fn spec_expectation(name: &str) -> Option<(usize, &'static str)> {
398 match name {
399 // Unequal luma (10) and chroma (9) bit depth: ffmpeg decodes nothing.
400 "TSUNEQBD_A_MAIN10_Technicolor_2" => Some((8, "ffmpeg unsupported (unequal bit depths)")),
401 // Six IDR pictures, each with its own VPS/SPS/PPS and resolution: ffmpeg outputs 2.
402 "VPSSPSPPS_A_MainConcept_1" => Some((6, "ffmpeg outputs 2")),
403 _ => None,
404 }
405}
406
407#[test]
408fn conformance_output_order_matches_ffprobe() {
409 let streams = streams();
410 if streams.is_empty() || !have_tool("ffprobe") {
411 eprintln!("conformance sweep skipped: vectors or ffprobe absent");
412 return;
413 }
414 let mut table = String::from("stream\tpictures_out\tffprobe_out\tresult\tdetail\n");
415 let mut pass = 0usize;
416 let mut spec_ok = 0usize;
417 for path in &streams {
418 let name = path
419 .file_stem()
420 .unwrap_or_default()
421 .to_string_lossy()
422 .to_string();
423 let data = match std::fs::read(path) {
424 Ok(d) => d,
425 Err(e) => {
426 table.push_str(&format!("{name}\t-\t-\tFAIL\tread: {e}\n"));
427 continue;
428 }
429 };
430 let ours = our_order(&data);
431 let theirs = ffprobe_order(path);
432 let row = match (ours, theirs) {
433 (Ok(ours), Ok(theirs)) => {
434 let our_aus: Vec<u32> = ours.iter().map(|(_, au)| *au).collect();
435 let pocs: Vec<String> = ours.iter().take(8).map(|(p, _)| p.to_string()).collect();
436 let detail = format!("first POCs {}", pocs.join(","));
437 match spec_expectation(&name) {
438 // The spec's own count is the reference where ffprobe is wrong.
439 Some((frames, why)) => {
440 let verdict = if ours.len() == frames { "SPEC" } else { "FAIL" };
441 if verdict == "SPEC" {
442 spec_ok += 1;
443 }
444 format!(
445 "{name}\t{}\t{}\t{verdict}\tspec: {frames} frames, {why}; {detail}\n",
446 ours.len(),
447 theirs.len(),
448 )
449 }
450 None => {
451 let verdict = if our_aus == theirs { "PASS" } else { "FAIL" };
452 if verdict == "PASS" {
453 pass += 1;
454 }
455 format!(
456 "{name}\t{}\t{}\t{verdict}\t{detail}\n",
457 ours.len(),
458 theirs.len(),
459 )
460 }
461 }
462 }
463 (Err(e), _) => format!("{name}\t-\t-\tREFUSED\t{e}\n"),
464 (_, Err(e)) => format!("{name}\t-\t-\tSKIP\tffprobe: {e}\n"),
465 };
466 table.push_str(&row);
467 }
468 match std::env::var("EC_H265_POC_TABLE") {
469 Ok(path) => std::fs::write(&path, &table).expect("write POC table"),
470 Err(_) => print!("{table}"),
471 }
472 eprintln!(
473 "POC/output order: {pass}/{} streams PASS, {spec_ok} SPEC (spec frame count, ffprobe differs)",
474 streams.len()
475 );
476}