forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

sw_backends.rs223 lines, 8.3 KiBHistoryRawDownload
1//! The H.264 software decode seat's witnesses, after the swap that made
2//! `ec-h264` -- the in-project decoder -- the seat. The independent one is
3//! ffmpeg: 8-bit H.264 decode is bit-exact by conformance, so a correct decoder
4//! handed a file must return the pictures the outside decoder returns, byte for
5//! byte. (The witness these tests were first written against, `rusty_h264`,
6//! retired with the crate on 2026-09-12 when the encode seat moved too; ffmpeg
7//! took the outside role.) The seat's own two output orders must also agree:
8//! display order is a reordering, not a rewrite.
9//!
10//! ```text
11//! cargo test -p engine --test sw_backends -- --test-threads=1
12//! ```
13
14use std::collections::hash_map::DefaultHasher;
15use std::hash::{Hash, Hasher};
16use std::path::{Path, PathBuf};
17
18use ec_core::registry::{CodecId, CodecParameters, Decoder as _};
19use ec_core::{Packet, TimeBase};
20use ec_h264::H264Decoder;
21
22fn asset(name: &str) -> PathBuf {
23 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
24 .join("../../assets")
25 .join(name)
26}
27
28/// Every access unit of the file, in container (decode) order.
29fn access_units(path: &Path) -> Vec<Vec<u8>> {
30 let (_, mut demuxer) = engine::demux::Demuxer::open(path).expect("open");
31 let mut aus = Vec::new();
32 while let Ok(Some(au)) = demuxer.next_access_unit() {
33 aus.push(au);
34 }
35 assert!(!aus.is_empty(), "{}: no access units", path.display());
36 aus
37}
38
39/// One decoded picture as plain planes, whatever the decoder calls them.
40struct Picture {
41 width: usize,
42 y: Vec<u8>,
43 u: Vec<u8>,
44 v: Vec<u8>,
45}
46
47impl Picture {
48 fn hash(&self) -> u64 {
49 let mut hasher = DefaultHasher::new();
50 self.width.hash(&mut hasher);
51 self.y.hash(&mut hasher);
52 self.u.hash(&mut hasher);
53 self.v.hash(&mut hasher);
54 hasher.finish()
55 }
56}
57
58/// `ec-h264` in the requested output order, drained to end of stream.
59fn decode_ec(aus: &[Vec<u8>], order: ec_h264::OutputOrder) -> Vec<Picture> {
60 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)).expect("ec decoder");
61 decoder.set_output_order(order);
62 let mut pictures = Vec::new();
63 for au in aus {
64 decoder
65 .send_packet(&Packet::new(0, TimeBase::new(1, 1), au.as_slice()))
66 .expect("ec decode");
67 while let Ok(frame) = decoder.receive_frame() {
68 let ec_core::frame::Frame::Video(pic) = frame else {
69 continue;
70 };
71 let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]];
72 pictures.push(Picture {
73 width: pic.width as usize,
74 y: y.data[..].to_vec(),
75 u: u.data[..].to_vec(),
76 v: v.data[..].to_vec(),
77 });
78 }
79 }
80 decoder.flush().expect("ec flush");
81 while let Ok(frame) = decoder.receive_frame() {
82 let ec_core::frame::Frame::Video(pic) = frame else {
83 continue;
84 };
85 let [y, u, v] = [&pic.planes[0], &pic.planes[1], &pic.planes[2]];
86 pictures.push(Picture {
87 width: pic.width as usize,
88 y: y.data[..].to_vec(),
89 u: u.data[..].to_vec(),
90 v: v.data[..].to_vec(),
91 });
92 }
93 pictures
94}
95
96/// Every picture ffmpeg releases for the file, in display order, as I420
97/// planes. `None` where ffmpeg is not installed -- the same skip the export
98/// suite's `ffmpeg_complaints` takes.
99fn decode_ffmpeg(path: &Path) -> Option<Vec<Picture>> {
100 let installed = std::process::Command::new("ffmpeg")
101 .arg("-version")
102 .output()
103 .map(|out| out.status.success())
104 .unwrap_or(false);
105 if !installed {
106 return None;
107 }
108 let (meta, _) = engine::demux::Demuxer::open(path).expect("open");
109 let (w, h) = (meta.width as usize, meta.height as usize);
110 let frame = w * h + 2 * (w / 2) * (h / 2);
111 let out = std::process::Command::new("ffmpeg")
112 .args(["-v", "error", "-i"])
113 .arg(path)
114 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
115 .output()
116 .expect("run ffmpeg");
117 assert!(
118 out.status.success(),
119 "ffmpeg read {} and failed: {}",
120 path.display(),
121 String::from_utf8_lossy(&out.stderr)
122 );
123 let raw = out.stdout;
124 assert_eq!(raw.len() % frame, 0, "ffmpeg handed back a partial frame");
125 Some(
126 raw.chunks_exact(frame)
127 .map(|data| {
128 let (luma, rest) = data.split_at(w * h);
129 let (cb, cr) = rest.split_at((w / 2) * (h / 2));
130 Picture {
131 width: w,
132 y: luma.to_vec(),
133 u: cb.to_vec(),
134 v: cr.to_vec(),
135 }
136 })
137 .collect(),
138 )
139}
140
141fn assert_same_pictures(a: &Picture, b: &Picture, what: &str, index: usize) {
142 assert_eq!(a.width, b.width, "{what}: picture {index} width");
143 assert_eq!(a.y, b.y, "{what}: picture {index} luma");
144 assert_eq!(a.u, b.u, "{what}: picture {index} cb");
145 assert_eq!(a.v, b.v, "{what}: picture {index} cr");
146}
147
148/// The seat against the outside decoder, byte for byte, on both a CAVLC
149/// Baseline and a CABAC High stream with B pictures. Display order on both
150/// sides: ffmpeg releases pictures as they play, and so does the seat.
151#[test]
152fn sw_decode_matches_ffmpeg_byte_for_byte() {
153 for name in ["test_baseline.mp4", "test_high.mp4"] {
154 let path = asset(name);
155 let Some(want) = decode_ffmpeg(&path) else {
156 eprintln!("no ffmpeg: skipping the outside decoder's word on {name}");
157 continue;
158 };
159 let got = decode_ec(&access_units(&path), ec_h264::OutputOrder::Display);
160 assert_eq!(got.len(), want.len(), "{name}: picture count");
161 for (i, (a, b)) in got.iter().zip(&want).enumerate() {
162 assert_same_pictures(a, b, name, i);
163 }
164 eprintln!("{name}: {} pictures agree byte for byte with ffmpeg", got.len());
165 }
166}
167
168/// Display order is a reordering, not a rewrite: the same multiset of
169/// pictures the decode-order run releases, possibly in a different sequence.
170/// On the B-picture fixture the sequences genuinely differ -- the reordering
171/// is the point of the DPB -- and on the Baseline fixture they cannot (no
172/// B pictures, nothing to reorder).
173#[test]
174fn display_order_releases_the_same_pictures() {
175 for name in ["test_baseline.mp4", "test_high.mp4"] {
176 let aus = access_units(&asset(name));
177 let decode_order = decode_ec(&aus, ec_h264::OutputOrder::Decode);
178 let display_order = decode_ec(&aus, ec_h264::OutputOrder::Display);
179 assert_eq!(decode_order.len(), display_order.len(), "{name}: count");
180 let mut want: Vec<u64> = decode_order.iter().map(Picture::hash).collect();
181 let mut got: Vec<u64> = display_order.iter().map(Picture::hash).collect();
182 want.sort_unstable();
183 got.sort_unstable();
184 assert_eq!(want, got, "{name}: the released pictures differ");
185
186 let reordered = decode_order
187 .iter()
188 .zip(&display_order)
189 .any(|(a, b)| a.hash() != b.hash());
190 if name == "test_high.mp4" {
191 assert!(
192 reordered,
193 "test_high.mp4 has B pictures: display order must differ \
194 from decode order somewhere, or the reorder is not engaged"
195 );
196 } else {
197 assert!(
198 !reordered,
199 "a Baseline stream has nothing to reorder: the sequences \
200 must be identical"
201 );
202 }
203 eprintln!(
204 "{name}: display order releases the same {} pictures",
205 got.len()
206 );
207 }
208}
209
210/// The seat, wired through `DecodeSession`, labels every picture with its
211/// timeline position: a full run to EOF delivers `0..frame_count` in order on
212/// a B-picture stream -- the contract the transport reads (`frame.index` is a
213/// timeline index) and the one the hardware backend already kept.
214#[test]
215fn the_software_seat_labels_the_timeline_in_display_order() {
216 engine::envcfg::set("VE_SW", "1");
217
218 let path = asset("test_high.mp4");
219 let (meta, rx) = engine::DecodeSession::open(&path).expect("open");
220 let indices: Vec<u32> = rx.into_iter().map(|f| f.index).collect();
221 let want: Vec<u32> = (0..meta.frame_count).collect();
222 assert_eq!(indices, want, "frames must arrive 0..n in display order");
223}