forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ffmpeg_parity.rs347 lines, 12.3 KiBHistoryRawDownload
1//! ASS parity with ffmpeg, and with the Matroska rebuild edith runs, on the synthetic scripts in
2//! `tests/data/`.
3//!
4//! ffmpeg is the reference. `ffprobe -show_packets` gives every event's start and duration, and
5//! `-c:s text -f srt` gives its words with every override tag stripped. ffmpeg emits events in
6//! start-time order, ties kept in file order, so ec-ass's cues are sorted the same way (stably)
7//! before comparing. Each cue must match on start and end in milliseconds, on order, and on text.
8//!
9//! `reordered_format.ass` is not compared with ffmpeg. Its demuxer produces no packets at all for a
10//! script whose Events `Format:` line puts Start before Layer, so there is nothing to compare. Its
11//! expectations are written out by hand instead.
12//!
13//! The ffmpeg tests skip loudly when `ffmpeg` or `ffprobe` is not on PATH.
14
15use std::path::{Path, PathBuf};
16use std::process::Command;
17
18use ec_ass::parse;
19use ec_subs::{Segment, SubtitleCue, TextAlign, plain_text};
20
21/// Fixtures ffmpeg can demux, all compared end to end.
22const FFMPEG_FIXTURES: &[&str] = &[
23 "styles_tags.ass",
24 "layers_overlap.ass",
25 "multiline_wrap0.ass",
26 "multiline_wrap2.ass",
27 "timing_edges.ass",
28 "unicode_sections.ass",
29 "karaoke_colours.ass",
30];
31
32fn data_path(name: &str) -> PathBuf {
33 Path::new(env!("CARGO_MANIFEST_DIR"))
34 .join("tests/data")
35 .join(name)
36}
37
38fn fixture(name: &str) -> Vec<u8> {
39 let path = data_path(name);
40 std::fs::read(&path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))
41}
42
43fn tool_present(tool: &str) -> bool {
44 Command::new(tool)
45 .arg("-version")
46 .output()
47 .map(|o| o.status.success())
48 .unwrap_or(false)
49}
50
51/// Both reference tools, or `None` (with a loud note) when either is missing.
52fn ffmpeg_available() -> bool {
53 if tool_present("ffmpeg") && tool_present("ffprobe") {
54 return true;
55 }
56 eprintln!("SKIP: ffmpeg/ffprobe not on PATH; ASS parity with ffmpeg not checked");
57 false
58}
59
60/// Seconds in ffprobe's decimal form to whole milliseconds.
61fn ms(seconds: &str) -> i64 {
62 (seconds.trim().parse::<f64>().expect("seconds") * 1000.0).round() as i64
63}
64
65/// `(start_ms, end_ms)` per packet, in the order ffprobe lists them.
66fn ffprobe_spans(path: &Path) -> Vec<(i64, i64)> {
67 let out = Command::new("ffprobe")
68 .args([
69 "-v",
70 "error",
71 "-select_streams",
72 "s:0",
73 "-show_entries",
74 "packet=pts_time,duration_time",
75 "-of",
76 "csv=p=0",
77 ])
78 .arg(path)
79 .output()
80 .expect("ffprobe runs");
81 assert!(
82 out.status.success(),
83 "ffprobe failed on {}: {}",
84 path.display(),
85 String::from_utf8_lossy(&out.stderr)
86 );
87 String::from_utf8_lossy(&out.stdout)
88 .lines()
89 .map(|line| {
90 let mut fields = line.split(',');
91 let start = ms(fields.next().expect("pts_time"));
92 // A zero-length event reports no duration (`N/A`).
93 let duration = fields
94 .next()
95 .and_then(|d| d.trim().parse::<f64>().ok())
96 .map_or(0, |d| (d * 1000.0).round() as i64);
97 (start, start + duration)
98 })
99 .collect()
100}
101
102/// ffmpeg's SRT rendering of the script's cues, words only.
103fn ffmpeg_srt(path: &Path) -> String {
104 let out = Command::new("ffmpeg")
105 .args(["-v", "error", "-nostdin", "-i"])
106 .arg(path)
107 .args(["-map", "0:s:0", "-c:s", "text", "-f", "srt", "-"])
108 .output()
109 .expect("ffmpeg runs");
110 assert!(
111 out.status.success(),
112 "ffmpeg failed on {}: {}",
113 path.display(),
114 String::from_utf8_lossy(&out.stderr)
115 );
116 String::from_utf8(out.stdout).expect("srt is utf-8")
117}
118
119/// `HH:MM:SS,mmm` to milliseconds.
120fn srt_ms(field: &str) -> i64 {
121 let (clock, millis) = field.trim().split_once(',').expect("srt comma");
122 let mut parts = clock
123 .split(':')
124 .map(|p| p.parse::<i64>().expect("srt digits"));
125 let (h, m, s) = (
126 parts.next().unwrap(),
127 parts.next().unwrap(),
128 parts.next().unwrap(),
129 );
130 ((h * 60 + m) * 60 + s) * 1000 + millis.parse::<i64>().expect("srt millis")
131}
132
133/// `(start_ms, end_ms, text)` per cue of an SRT document. Each block is an index line, a timing
134/// line, its text lines, then one blank separator before the next index line. A text that ends
135/// in a line break keeps that blank line, so the separator is cut by position, not by content.
136fn srt_cues(srt: &str) -> Vec<(i64, i64, String)> {
137 let lines: Vec<&str> = srt.lines().collect();
138 let timings: Vec<usize> = lines
139 .iter()
140 .enumerate()
141 .filter(|(_, l)| l.contains(" --> "))
142 .map(|(i, _)| i)
143 .collect();
144 timings
145 .iter()
146 .enumerate()
147 .map(|(k, &t)| {
148 let (start, end) = lines[t].split_once(" --> ").expect("timing line");
149 let text_end = match timings.get(k + 1) {
150 // Next timing is at `next`: `next - 1` is its index line, `next - 2` the separator.
151 Some(&next) => next - 2,
152 None => lines.len() - 1,
153 };
154 let text = lines[t + 1..text_end.max(t + 1)].join("\n");
155 (srt_ms(start), srt_ms(end), text)
156 })
157 .collect()
158}
159
160/// ec-ass's cues as `(start_ms, end_ms, text)`, in ffmpeg's order.
161fn ours_in_ffmpeg_order(cues: &[SubtitleCue]) -> Vec<(i64, i64, String)> {
162 let mut sorted: Vec<&SubtitleCue> = cues.iter().collect();
163 sorted.sort_by_key(|c| c.start_us);
164 sorted
165 .iter()
166 .map(|c| (c.start_us / 1000, c.end_us / 1000, plain_text(&c.segments)))
167 .collect()
168}
169
170#[test]
171fn cues_match_ffmpeg_timing_order_and_text() {
172 if !ffmpeg_available() {
173 return;
174 }
175 for name in FFMPEG_FIXTURES {
176 let path = data_path(name);
177 let track = parse(&fixture(name)).unwrap_or_else(|e| panic!("{name}: {e}"));
178 let ours = ours_in_ffmpeg_order(&track.cues);
179
180 let packets = ffprobe_spans(&path);
181 assert_eq!(packets.len(), ours.len(), "{name}: event count");
182 for (i, (packet, ours)) in packets.iter().zip(&ours).enumerate() {
183 assert_eq!(
184 *packet,
185 (ours.0, ours.1),
186 "{name}: event {i} start/end (ms)"
187 );
188 }
189
190 let reference = srt_cues(&ffmpeg_srt(&path));
191 assert_eq!(reference.len(), ours.len(), "{name}: srt cue count");
192 for (i, (theirs, mine)) in reference.iter().zip(&ours).enumerate() {
193 assert_eq!(theirs, mine, "{name}: event {i} (start, end, text)");
194 }
195 }
196}
197
198/// Edith rebuilds a Matroska ASS track as a plain script: the `CodecPrivate` header, then one
199/// `Dialogue:` row per block, with the block's timing and its `ReadOrder` dropped. The same
200/// rebuild must parse to the same cues as the script itself.
201#[test]
202fn matroska_style_blocks_rebuild_to_the_same_cues() {
203 for name in FFMPEG_FIXTURES {
204 let bytes = fixture(name);
205 let direct = parse(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
206
207 // Matroska form: header as CodecPrivate, then `ReadOrder,Layer,...` blocks.
208 let text = String::from_utf8_lossy(&bytes);
209 let mut rebuilt = direct.extradata.clone();
210 let mut read_order = 0;
211 for line in text.lines() {
212 let Some(body) = line.trim().strip_prefix("Dialogue:") else {
213 continue;
214 };
215 let mut fields = body.trim_start().splitn(4, ',');
216 let (layer, start, end, rest) = (
217 fields.next().unwrap(),
218 fields.next().unwrap(),
219 fields.next().unwrap(),
220 fields.next().unwrap(),
221 );
222 let block = format!("{read_order},{layer},{rest}");
223 read_order += 1;
224
225 // Edith's side: the block is split back into timing and the rest of the row.
226 let mut block_fields = block.splitn(3, ',');
227 let _read_order = block_fields.next().unwrap();
228 let layer = block_fields.next().unwrap();
229 let rest = block_fields.next().unwrap();
230 rebuilt
231 .extend_from_slice(format!("Dialogue: {layer},{start},{end},{rest}\n").as_bytes());
232 }
233
234 let again = parse(&rebuilt).unwrap_or_else(|e| panic!("{name}: rebuilt: {e}"));
235 assert_eq!(again.cues.len(), direct.cues.len(), "{name}: cue count");
236 for (i, (a, b)) in direct.cues.iter().zip(&again.cues).enumerate() {
237 assert_eq!(
238 (a.start_us, a.end_us, &a.segments, a.positioning),
239 (b.start_us, b.end_us, &b.segments, b.positioning),
240 "{name}: cue {i}"
241 );
242 }
243 }
244}
245
246/// A Format line that reorders the columns is read by name, not by position.
247#[test]
248fn reordered_format_is_read_by_column_name() {
249 let track = parse(&fixture("reordered_format.ass")).unwrap();
250
251 let top = track.style("Reordered Top").expect("style by name");
252 assert_eq!(top.font_size, Some(44.0));
253 assert_eq!(top.font_family.as_deref(), Some("Verdana"));
254 assert!(top.bold && !top.italic);
255 assert_eq!(top.align, TextAlign::Center);
256 let bottom = track.style("Reordered Bottom").expect("style by name");
257 assert!(bottom.italic && !bottom.bold);
258 assert_eq!(bottom.primary_color, Some((255, 255, 0, 255)));
259
260 let texts: Vec<String> = track.cues.iter().map(|c| plain_text(&c.segments)).collect();
261 assert_eq!(
262 texts,
263 [
264 "first row in reordered columns",
265 "second row, comma kept in text",
266 "overlapping third row",
267 "bold last",
268 ]
269 );
270 let starts: Vec<(i64, i64)> = track.cues.iter().map(|c| (c.start_us, c.end_us)).collect();
271 assert_eq!(
272 starts,
273 [
274 (1_000_000, 2_500_000),
275 (2_500_000, 4_000_000),
276 (3_000_000, 5_000_000),
277 (5_000_000, 6_000_000),
278 ]
279 );
280 assert_eq!(track.cues[0].style_ref.as_deref(), Some("Reordered Top"));
281 assert_eq!(track.cues[1].style_ref.as_deref(), Some("Reordered Bottom"));
282 assert_eq!(track.cues[2].positioning.unwrap().align, TextAlign::Center);
283 let last = track.cues[3].positioning.unwrap();
284 assert_eq!((last.x, last.y), (Some(10.0), Some(20.0)));
285 assert_eq!(
286 track.cues[3].segments,
287 vec![Segment::Bold(vec![Segment::Text("bold last".into())])]
288 );
289}
290
291/// Override tags this parser does not model reach the caller verbatim as `Raw`, with each
292/// unmodelled tag's own text, including tags nested in `\t(...)`. A `\fs` inside `\t(...)` must
293/// not be read as a font size.
294#[test]
295fn unmodelled_override_tags_survive_as_verbatim_raw() {
296 let doc = "[Events]\n\
297 Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
298 Dialogue: 0,0:00:00.00,0:00:01.00,,,0,0,0,,{\\t(0,500,\\fs20)}grow\n\
299 Dialogue: 0,0:00:01.00,0:00:02.00,,,0,0,0,,{\\blur3\\bord2\\frz30\\fscx120}wide\n\
300 Dialogue: 0,0:00:02.00,0:00:03.00,,,0,0,0,,{\\move(10,10,200,200,0,500)}moving\n\
301 Dialogue: 0,0:00:03.00,0:00:04.00,,,0,0,0,,{\\clip(0,0,100,100)\\org(5,5)}clipped\n\
302 Dialogue: 0,0:00:04.00,0:00:05.00,,,0,0,0,,{\\p1}m 0 0 l 10 10{\\p0}words\n";
303 let track = parse(doc.as_bytes()).unwrap();
304 let segments: Vec<&Vec<Segment>> = track.cues.iter().map(|c| &c.segments).collect();
305
306 assert_eq!(
307 *segments[0],
308 vec![
309 Segment::Raw("{\\t(0,500,\\fs20)}".into()),
310 Segment::Text("grow".into()),
311 ]
312 );
313 assert_eq!(
314 *segments[1],
315 vec![
316 Segment::Raw("{\\blur3\\bord2\\frz30\\fscx120}".into()),
317 Segment::Text("wide".into()),
318 ]
319 );
320 assert_eq!(
321 *segments[2],
322 vec![
323 Segment::Raw("{\\move(10,10,200,200,0,500)}".into()),
324 Segment::Text("moving".into()),
325 ]
326 );
327 assert_eq!(
328 *segments[3],
329 vec![
330 Segment::Raw("{\\clip(0,0,100,100)\\org(5,5)}".into()),
331 Segment::Text("clipped".into()),
332 ]
333 );
334 // Drawing commands are kept whole as Raw, and are not words.
335 assert_eq!(
336 *segments[4],
337 vec![
338 Segment::Raw("m 0 0 l 10 10".into()),
339 Segment::Text("words".into()),
340 ]
341 );
342 assert_eq!(
343 track.cues[2].positioning.unwrap().x,
344 Some(10.0),
345 "\\move starts where \\pos would put it"
346 );
347}