forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

parity.rs229 lines, 8.9 KiBHistoryRawDownload
1//! Parity of the decoding path against a snapshot. Every fixture in
2//! `tests/data` and the Matroska files in `assets/` is read through
3//! [`super::parse_file`] and [`super::cues_of`], and each cue, each picture and
4//! each decoded canvas is written out and compared with the checked-in
5//! `tests/data/subtitle_parity.txt`.
6//!
7//! That snapshot was taken from the oxideav path this module used to run beside
8//! the `ec-*` one, before the oxideav crates were removed, so the snapshot is
9//! the old behaviour and any drift from it is a failure. Regenerate it only with
10//! `EC_WRITE_PARITY_SNAPSHOT=1` and `--nocapture`, and only when a difference
11//! is intended.
12
13use std::path::{Path, PathBuf};
14
15use super::{Cue, CueImage, parse_file};
16use crate::scratch::Scratch;
17
18/// 64-bit FNV-1a: a hash the snapshot can carry, stable across toolchains.
19/// The bytes a picture was made from, whatever its format: the display set or the unit.
20fn source_bytes(source: &super::Source) -> &[u8] {
21 match source {
22 super::Source::Pgs(set) | super::Source::Dvb(set) => set,
23 super::Source::Dvd { unit, .. } => unit,
24 }
25}
26
27fn fnv(bytes: &[u8]) -> u64 {
28 bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
29 (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
30 })
31}
32
33/// One fixture's result as the snapshot writes it: every cue's times and text,
34/// and for a picture the hash of its display set and of its canvas, with the
35/// number of pixels the canvas paints.
36fn describe(
37 label: &str,
38 cues: &Result<Vec<Cue>, String>,
39 rgba: &dyn Fn(&CueImage) -> Option<Vec<u8>>,
40) -> String {
41 let cues = match cues {
42 Ok(cues) => cues,
43 Err(why) => return format!("{label}: error {why:?}\n"),
44 };
45 let mut out = format!("{label}: {} cues\n", cues.len());
46 for cue in cues {
47 out += &format!(" {} {} {:?}\n", cue.start_us, cue.end_us, cue.text);
48 if let Some(image) = &cue.image {
49 let canvas = match rgba(image) {
50 Some(px) => format!(
51 "fnv {:016x} lit {}",
52 fnv(&px),
53 px.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count()
54 ),
55 None => "none".to_owned(),
56 };
57 out += &format!(
58 " image {}x{} set {:016x} canvas {canvas}\n",
59 image.width,
60 image.height,
61 fnv(source_bytes(&image.set))
62 );
63 }
64 }
65 out
66}
67
68/// A Matroska case: every track of `path`, its cues read off the file and each
69/// picture decoded to its canvas.
70fn mkv_case(path: &Path, label: &str, out: &mut Vec<String>) {
71 let tracks = crate::demux::matroska_subtitles(path).expect("the walk does not fail");
72 for mut track in tracks {
73 let name = format!("{label} track {} {}", track.number, track.codec);
74 let cues = super::cues_of(&mut track);
75 out.push(describe(&name, &cues, &|i| i.rgba()));
76 }
77}
78
79/// The synthetic PGS fixture from `tests/subtitles.rs`: a 2x2 picture on an 8x4
80/// canvas, one display set that paints and one that erases it.
81fn pgs_segment(kind: u8, body: &[u8]) -> Vec<u8> {
82 let mut out = vec![kind];
83 out.extend_from_slice(&(body.len() as u16).to_be_bytes());
84 out.extend_from_slice(body);
85 out
86}
87
88fn pgs_display_set() -> Vec<u8> {
89 #[rustfmt::skip]
90 let pcs = [
91 0, 8, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1,
92 0, 0, 0, 0, 0, 1, 0, 1,
93 ];
94 let pds = [0, 0, 1, 235, 128, 128, 255];
95 let rle = [0x00, 0x82, 0x01, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00];
96 let mut ods = vec![0, 0, 0, 0xC0];
97 ods.extend_from_slice(&[0, 0, (4 + rle.len()) as u8, 0, 2, 0, 2]);
98 ods.extend_from_slice(&rle);
99 let mut set = pgs_segment(0x16, &pcs);
100 set.extend(pgs_segment(0x14, &pds));
101 set.extend(pgs_segment(0x15, &ods));
102 set.extend(pgs_segment(0x80, &[]));
103 set
104}
105
106fn pgs_erase() -> Vec<u8> {
107 let mut set = pgs_segment(0x16, &[0, 8, 0, 4, 0x10, 0, 1, 0, 0, 0, 0]);
108 set.extend(pgs_segment(0x80, &[]));
109 set
110}
111
112fn element(id: &[u8], body: &[u8]) -> Vec<u8> {
113 let mut out = id.to_vec();
114 let mut len = (body.len() as u64).to_be_bytes();
115 len[0] |= 0x01;
116 out.extend_from_slice(&len);
117 out.extend_from_slice(body);
118 out
119}
120
121/// A Matroska file with one PGS track: `first` at 500 ms, the erase at 2 s.
122fn pgs_matroska(first: Vec<u8>) -> Vec<u8> {
123 let mut entry = Vec::new();
124 entry.extend(element(&[0xD7], &[1])); // TrackNumber
125 entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle
126 entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID
127 entry.extend(element(&[0x22, 0xB5, 0x9C], b"eng"));
128 let tracks = element(&[0xAE], &entry);
129 let block = |at: i16, data: Vec<u8>| {
130 let mut body = vec![0x81, (at >> 8) as u8, at as u8, 0x00];
131 body.extend(data);
132 element(&[0xA3], &body)
133 };
134 let mut cluster = element(&[0xE7], &[0x00]);
135 cluster.extend(block(500, first));
136 cluster.extend(block(2000, pgs_erase()));
137 let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks);
138 segment.extend(element(&[0x1F, 0x43, 0xB6, 0x75], &cluster));
139 element(&[0x18, 0x53, 0x80, 0x67], &segment)
140}
141
142/// Every fixture rendered through the decoding path: the checked-in fixtures
143/// and inline ones that reach the markup they do not (a VTT, an ASS with
144/// override tags, an SRT with markup and a line break), then the Matroska files.
145fn render() -> String {
146 let dir = Scratch::dir("ve_subs_parity");
147 let data = |name: &str| -> PathBuf {
148 Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data").join(name)
149 };
150 let asset = |name: &str| -> PathBuf {
151 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
152 };
153 let mut out = Vec::new();
154
155 let mut file_case = |name: &str, path: PathBuf| {
156 let got = parse_file(&path).map_err(|e| e.to_string());
157 out.push(describe(name, &got, &|i| i.rgba()));
158 };
159 file_case("test_subs.srt", data("test_subs.srt"));
160 file_case("test_subs.ass", data("test_subs.ass"));
161 let inline: [(&str, &str); 3] = [
162 (
163 "inline.vtt",
164 "WEBVTT\n\n00:00:01.000 --> 00:00:02.500 line:10%\n<v Ann>Hello <i>there</i>\n\n\
165 00:00:03.000 --> 00:00:04.000\nsecond\nline\n",
166 ),
167 (
168 "inline.ass",
169 "[Script Info]\nScriptType: v4.00+\nPlayResX: 1280\nPlayResY: 720\n\n\
170 [V4+ Styles]\nFormat: Name, Fontname, Fontsize\nStyle: Default,Arial,40\n\n\
171 [Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
172 Dialogue: 0,0:00:01.00,0:00:02.00,Default,,0,0,0,,{\\an8}top {\\i1}slant{\\i0}\\Nnext\n\
173 Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,plain {\\b1}bold{\\b0}\n",
174 ),
175 (
176 "inline.srt",
177 "1\n00:00:01,000 --> 00:00:02,000\n<i>tilted</i> and <font color=\"#ff0000\">red</font>\nsecond\n",
178 ),
179 ];
180 for (name, body) in inline {
181 let path = dir.join(name);
182 std::fs::write(&path, body).expect("write the fixture");
183 file_case(name, path);
184 }
185
186 for name in ["test_subs.mkv", "test_subs.mks", "test_subs_bcp47.mkv"] {
187 mkv_case(&asset(name), name, &mut out);
188 }
189 let pgs = dir.join("pgs.mkv");
190 std::fs::write(&pgs, pgs_matroska([pgs_display_set(), pgs_erase()].concat()))
191 .expect("write the pgs fixture");
192 mkv_case(&pgs, "pgs.mkv", &mut out);
193
194 out.concat()
195}
196
197/// The one difference found between the two paths, pinned on its own so the
198/// parity test above stays exact: an ASS drawing (`{\p1}` ... `{\p0}`) is
199/// shapes, not words. The oxideav path read the drawing commands out as text;
200/// `ec-ass` keeps them as `Segment::Raw`, which [`ec_subs::plain_text`] drops.
201#[test]
202fn an_ass_drawing_is_shapes_and_not_words() {
203 let dir = Scratch::dir("ve_subs_parity_drawing");
204 let path = dir.join("drawing.ass");
205 std::fs::write(
206 &path,
207 "[Script Info]\nScriptType: v4.00+\n\n[Events]\n\
208 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
209 Dialogue: 0,0:00:03.00,0:00:04.00,Default,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n",
210 )
211 .expect("write the fixture");
212 let cues = parse_file(&path).expect("the ass parses");
213 assert_eq!(cues.len(), 1);
214 assert_eq!(cues[0].text, "words");
215}
216
217/// The decoding path matches the checked-in snapshot on every fixture. The
218/// snapshot was written by the oxideav path before it was removed, so this is
219/// still the old behaviour, to the byte, held in place.
220#[test]
221fn the_decoding_path_matches_the_snapshot_taken_from_the_oxideav_path() {
222 let got = render();
223 if std::env::var_os("EC_WRITE_PARITY_SNAPSHOT").is_some() {
224 // The VPS keeps the tree it ran in, so the snapshot comes back on
225 // stdout, between markers, and is checked in by hand.
226 println!("SNAPSHOT-BEGIN\n{got}SNAPSHOT-END");
227 }
228 assert_eq!(got, include_str!("../../tests/data/subtitle_parity.txt"));
229}