forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

real_library_zlib.rs505 lines, 17.4 KiBHistoryRawDownload
1//! The zlib-compressed (`ContentCompAlgo` 0) Matroska subtitle tracks of the
2//! owner's own films, against ffprobe.
3//!
4//! Two keys, both named by `real_library.toml` (gitignored):
5//!
6//! - `mkv_zlib_pgs`: the `S_HDMV/PGS` tracks. Edith's own Matroska subtitle walk
7//! ([`engine::demux::matroska_subtitles`]) reads these, so every payload comes
8//! out of `ec_inflate` through the same path the app uses.
9//! - `mkv_zlib_vobsub`: the `S_VOBSUB` tracks. Edith's subtitle walk declares
10//! them but reads no VobSub payload (see `matroska_subtitles`), so there is no
11//! app path for those bytes to take. Their blocks are read here straight out
12//! of the file and handed to `ec_inflate` directly, which is the same decoder
13//! the app's Matroska demuxer calls.
14//!
15//! Both sides assert that the track really is zlib-compressed, from a walk of the
16//! file's own `ContentEncodings` (never from what edith reports), so the witness
17//! cannot pass silently on an uncompressed track. Each packet is compared with
18//! `ffprobe -show_packets -show_data_hash MD5` for that stream: packet count,
19//! pts in microseconds, duration where edith states one, size, and the MD5 of
20//! the decompressed bytes.
21//!
22//! A key the manifest does not name, or a path not on this machine, skips.
23//! Needs ffprobe.
24//!
25//! ```text
26//! cargo test -p engine --test real_library_zlib -- --nocapture
27//! ```
28
29use crate::reallib;
30
31use std::io::Read as _;
32use std::path::Path;
33use std::process::Command;
34use std::time::Instant;
35
36use engine::demux::{matroska_subtitles, PGS};
37use reallib::{ffprobe_streams, have, md5_hex, FfPacket, FfStream};
38
39// The element ids a walk of the file reads, as they are written in it.
40const SEGMENT: u32 = 0x1853_8067;
41const INFO: u32 = 0x1549_A966;
42const TIMESTAMP_SCALE: u32 = 0x2A_D7B1;
43const CLUSTER: u32 = 0x1F43_B675;
44const CLUSTER_TIMESTAMP: u32 = 0xE7;
45const TRACKS: u32 = 0x1654_AE6B;
46const TRACK_ENTRY: u32 = 0xAE;
47const TRACK_NUMBER: u32 = 0xD7;
48const TRACK_TYPE: u32 = 0x83;
49const CODEC_ID: u32 = 0x86;
50const CONTENT_ENCODINGS: u32 = 0x6D80;
51const CONTENT_ENCODING: u32 = 0x6240;
52const CONTENT_ENCODING_TYPE: u32 = 0x5033;
53const CONTENT_COMPRESSION: u32 = 0x5034;
54const CONTENT_COMP_ALGO: u32 = 0x4254;
55const BLOCK_GROUP: u32 = 0xA0;
56const BLOCK: u32 = 0xA1;
57const SIMPLE_BLOCK: u32 = 0xA3;
58
59/// `TrackType` of a subtitle track.
60const SUBTITLE: u64 = 0x11;
61/// The Matroska codec id of VobSub bitmaps.
62const VOBSUB: &str = "S_VOBSUB";
63/// The same ceiling the app's Matroska demuxer puts on one inflated block.
64const LIMIT: usize = 64 << 20;
65/// How much of the file the header walk reads. Tracks come before the first
66/// cluster, so this is more than enough for the header of any file written here.
67const HEAD: usize = 8 << 20;
68
69/// One `TrackEntry` as the file declares it.
70#[derive(Debug, Default, Clone)]
71struct Track {
72 number: u64,
73 kind: u64,
74 codec: String,
75 /// A `ContentEncoding` element was present.
76 encoded: bool,
77 /// `ContentEncodingType`; the default 0 is compression.
78 enc_kind: Option<u64>,
79 /// `ContentCompAlgo`; the default 0 is zlib.
80 algo: Option<u64>,
81}
82
83impl Track {
84 /// Whether the file compresses every block of this track with zlib alone.
85 fn zlib(&self) -> bool {
86 self.encoded && self.enc_kind.unwrap_or(0) == 0 && self.algo.unwrap_or(0) == 0
87 }
88}
89
90/// One block as the file stores it: its track, its absolute timestamp in
91/// ticks, its lacing bits and the byte range of its payload in the file.
92#[derive(Debug)]
93struct Block {
94 track: u64,
95 ticks: i64,
96 lacing: u8,
97 range: std::ops::Range<usize>,
98}
99
100/// What a walk of the file's header and, when asked, its blocks found.
101#[derive(Debug, Default)]
102struct Walk {
103 tracks: Vec<Track>,
104 blocks: Vec<Block>,
105 timestamp_scale: u64,
106}
107
108/// An EBML variable-length integer at `at`: its value with the length marker
109/// dropped (kept for an element id), its length in bytes, and where it ends.
110fn vint(buf: &[u8], at: usize, keep_marker: bool) -> Option<(u64, usize, usize)> {
111 let first = *buf.get(at)?;
112 let len = first.leading_zeros() as usize + 1;
113 if len > 8 {
114 return None;
115 }
116 let mut raw = 0u64;
117 for &b in buf.get(at..at + len)? {
118 raw = (raw << 8) | u64::from(b);
119 }
120 let value = if keep_marker {
121 raw
122 } else {
123 raw & ((1u64 << (7 * len)) - 1)
124 };
125 Some((value, len, at + len))
126}
127
128/// An element header at `at`: its id, its size (`None` for the unknown size a
129/// live muxer writes) and where its body starts.
130fn header(buf: &[u8], at: usize) -> Option<(u32, Option<u64>, usize)> {
131 let (id, _, next) = vint(buf, at, true)?;
132 let (size, len, body) = vint(buf, next, false)?;
133 let unknown = size == (1u64 << (7 * len)) - 1;
134 Some((id as u32, (!unknown).then_some(size), body))
135}
136
137fn uint(data: &[u8]) -> u64 {
138 data.iter().fold(0, |acc, &b| (acc << 8) | u64::from(b))
139}
140
141fn text(data: &[u8]) -> String {
142 String::from_utf8_lossy(data)
143 .trim_end_matches('\0')
144 .to_string()
145}
146
147/// Every header element of `buf`, in file order, descending into the masters
148/// this reads and skipping every other body by its size. With `blocks` false the
149/// walk stops at the first cluster, which is what a header-only read wants.
150///
151/// A block's lacing is recorded, not undone: a laced block is one this witness
152/// refuses, so the caller can say so.
153fn walk(buf: &[u8], blocks: bool) -> Walk {
154 let mut w = Walk {
155 timestamp_scale: 1_000_000,
156 ..Walk::default()
157 };
158 let mut cluster_ticks = 0i64;
159 let mut at = 0usize;
160 while let Some((id, size, body)) = header(buf, at) {
161 match id {
162 SEGMENT | INFO | TRACKS | CONTENT_ENCODINGS | CONTENT_COMPRESSION | BLOCK_GROUP => {
163 at = body;
164 continue;
165 }
166 CLUSTER => {
167 if !blocks {
168 break;
169 }
170 at = body;
171 continue;
172 }
173 TRACK_ENTRY => {
174 w.tracks.push(Track::default());
175 at = body;
176 continue;
177 }
178 CONTENT_ENCODING => {
179 if let Some(t) = w.tracks.last_mut() {
180 t.encoded = true;
181 }
182 at = body;
183 continue;
184 }
185 _ => {}
186 }
187 // A leaf: its body must be present and sized.
188 let Some(size) = size else { break };
189 let Some(end) = body.checked_add(size as usize).filter(|&e| e <= buf.len()) else {
190 break;
191 };
192 let data = &buf[body..end];
193 let last = w.tracks.last_mut();
194 match id {
195 TRACK_NUMBER => {
196 if let Some(t) = last {
197 t.number = uint(data);
198 }
199 }
200 TRACK_TYPE => {
201 if let Some(t) = last {
202 t.kind = uint(data);
203 }
204 }
205 CODEC_ID => {
206 if let Some(t) = last {
207 t.codec = text(data);
208 }
209 }
210 CONTENT_ENCODING_TYPE => {
211 if let Some(t) = last {
212 t.enc_kind = Some(uint(data));
213 }
214 }
215 CONTENT_COMP_ALGO => {
216 if let Some(t) = last {
217 t.algo = Some(uint(data));
218 }
219 }
220 TIMESTAMP_SCALE => w.timestamp_scale = uint(data).max(1),
221 CLUSTER_TIMESTAMP => cluster_ticks = uint(data) as i64,
222 SIMPLE_BLOCK | BLOCK if blocks => {
223 let Some((track, _, after)) = vint(data, 0, false) else {
224 break;
225 };
226 let (Some(rel), Some(&flags)) = (data.get(after..after + 2), data.get(after + 2))
227 else {
228 break;
229 };
230 let rel = i16::from_be_bytes([rel[0], rel[1]]);
231 w.blocks.push(Block {
232 track,
233 ticks: cluster_ticks + i64::from(rel),
234 lacing: flags & 0x06,
235 range: body + after + 3..end,
236 });
237 }
238 _ => {}
239 }
240 at = end;
241 }
242 w
243}
244
245/// One packet as edith states it, in microseconds from the start of the file.
246struct Got {
247 start_us: i128,
248 duration_us: Option<i128>,
249 len: usize,
250 md5: String,
251}
252
253/// ffprobe's packets of one stream: `-show_packets -show_data_hash MD5`.
254fn ffprobe_packets_of(path: &Path, stream: u32) -> Vec<FfPacket> {
255 let out = Command::new("ffprobe")
256 .args(["-v", "error", "-select_streams"])
257 .arg(stream.to_string())
258 .args(["-show_packets", "-show_data_hash", "MD5"])
259 .args(["-show_entries"])
260 .arg("packet=stream_index,pts,dts,duration,size,flags,data_hash")
261 .args(["-of", "csv=p=0"])
262 .arg(path)
263 .output()
264 .expect("run ffprobe");
265 assert!(out.status.success(), "ffprobe failed on stream {stream}");
266 let opt = |f: &str| f.trim().parse::<i64>().ok();
267 String::from_utf8_lossy(&out.stdout)
268 .lines()
269 .map(|line| {
270 let f: Vec<&str> = line.split(',').collect();
271 FfPacket {
272 stream: f[0].trim().parse().expect("stream index"),
273 pts: opt(f[1]),
274 dts: opt(f[2]),
275 duration: opt(f[3]),
276 size: f[4].trim().parse().expect("size"),
277 key: f[5].starts_with('K'),
278 md5: f[6].trim().trim_start_matches("MD5:").to_string(),
279 }
280 })
281 .collect()
282}
283
284/// The `time_base` ffprobe states for a stream, as (numerator, denominator).
285fn time_base(streams: &[FfStream], index: u32) -> (i128, i128) {
286 let s = streams
287 .iter()
288 .find(|s| s.index == index)
289 .expect("ffprobe names the stream");
290 let (num, den) = s.time_base.split_once('/').expect("time_base is a ratio");
291 (
292 num.parse().expect("time_base numerator"),
293 den.parse().expect("time_base denominator"),
294 )
295}
296
297/// Ticks of a stream's time base as microseconds, exactly.
298fn ticks_us(ticks: i64, (num, den): (i128, i128)) -> i128 {
299 i128::from(ticks) * num * 1_000_000 / den
300}
301
302/// Compares edith's packets with ffprobe's, packet for packet. Returns the
303/// number of disagreements, each named on stderr with the first few.
304fn compare(key: &str, label: &str, ours: &[Got], ff: &[FfPacket], tb: (i128, i128)) -> usize {
305 let mut bad = 0;
306 if ours.len() != ff.len() {
307 eprintln!(
308 "{key} {label}: edith has {} packets, ffprobe {}",
309 ours.len(),
310 ff.len()
311 );
312 bad += 1;
313 }
314 for (i, (o, f)) in ours.iter().zip(ff).enumerate() {
315 let start = f.pts.map(|p| ticks_us(p, tb));
316 let dur = f.duration.map(|d| ticks_us(d, tb));
317 let ok = start == Some(o.start_us)
318 && o.duration_us.is_none_or(|d| dur == Some(d))
319 && f.size == o.len
320 && f.md5 == o.md5;
321 if !ok {
322 bad += 1;
323 if bad <= 5 {
324 eprintln!(
325 "{key} {label}: packet {i}: edith start {} dur {:?} len {} md5 {} | ffprobe pts {:?} dur {:?} size {} md5 {}",
326 o.start_us, o.duration_us, o.len, o.md5, start, dur, f.size, f.md5
327 );
328 }
329 }
330 }
331 bad
332}
333
334/// `mkv_zlib_pgs`: every zlib PGS track, its packets read through edith's own
335/// Matroska subtitle walk and compared with ffprobe.
336fn check_pgs(key: &str) {
337 let Some(path) = engine::real_library::film(key) else {
338 return;
339 };
340 if !have("ffprobe") {
341 eprintln!("skipped: no ffprobe to state the reference packets");
342 return;
343 }
344 let started = Instant::now();
345 let mut head = Vec::new();
346 std::fs::File::open(&path)
347 .expect("open the file")
348 .take(HEAD as u64)
349 .read_to_end(&mut head)
350 .expect("read the file's head");
351 let header = walk(&head, false);
352 let ff_streams = ffprobe_streams(&path);
353 let subs = matroska_subtitles(&path).expect("edith reads the subtitle tracks");
354
355 let mut tracks = 0;
356 let mut packets = 0;
357 let mut bad = 0;
358 // The index of a track among all the file's tracks is its ffprobe stream
359 // index: both count the TrackEntry elements in file order.
360 for (pos, t) in header.tracks.iter().enumerate() {
361 if t.kind != SUBTITLE || t.codec != PGS || !t.zlib() {
362 continue;
363 }
364 tracks += 1;
365 let sub = subs
366 .iter()
367 .find(|s| s.number == t.number)
368 .unwrap_or_else(|| panic!("{key}: edith lists no subtitle track {}", t.number));
369 assert!(
370 sub.unsupported.is_none(),
371 "{key}: edith refuses the zlib track: {:?}",
372 sub.unsupported
373 );
374 let index = pos as u32;
375 assert_eq!(
376 ff_streams[pos].kind, "subtitle",
377 "{key}: ffprobe stream {index} is not a subtitle stream"
378 );
379 let tb = time_base(&ff_streams, index);
380 let ours: Vec<Got> = sub
381 .cues
382 .iter()
383 .map(|c| Got {
384 start_us: i128::from(c.start_us),
385 duration_us: c.duration_us.map(i128::from),
386 len: c.payload.len(),
387 md5: md5_hex(&c.payload),
388 })
389 .collect();
390 let ff = ffprobe_packets_of(&path, index);
391 assert!(
392 !ours.is_empty(),
393 "{key}: edith read no cues for track {index}"
394 );
395 packets += ours.len();
396 bad += compare(key, &format!("track {index}"), &ours, &ff, tb);
397 eprintln!(
398 "{key}: track {index} (PGS, zlib): {} packets compared with ffprobe",
399 ours.len()
400 );
401 }
402 assert!(
403 tracks > 0,
404 "{key}: no zlib-compressed PGS track in the file"
405 );
406 eprintln!(
407 "{key}: {packets} packets over {tracks} zlib PGS track(s), {bad} mismatches, {:.1} s",
408 started.elapsed().as_secs_f64()
409 );
410 assert_eq!(bad, 0, "{key}: edith and ffprobe disagree");
411}
412
413/// `mkv_zlib_vobsub`: every zlib VobSub track. Blocks are read straight out of
414/// the file (the whole file is read: the VobSub titles are tens of megabytes)
415/// and inflated with `ec_inflate`, the decoder the Matroska demuxer calls.
416fn check_vobsub(key: &str) {
417 let Some(path) = engine::real_library::film(key) else {
418 return;
419 };
420 if !have("ffprobe") {
421 eprintln!("skipped: no ffprobe to state the reference packets");
422 return;
423 }
424 let started = Instant::now();
425 let buf = std::fs::read(&path).expect("read the file");
426 let file = walk(&buf, true);
427 let ff_streams = ffprobe_streams(&path);
428 let subs = matroska_subtitles(&path).expect("edith reads the subtitle tracks");
429
430 let mut tracks = 0;
431 let mut packets = 0;
432 let mut bad = 0;
433 for (pos, t) in file.tracks.iter().enumerate() {
434 if t.kind != SUBTITLE || t.codec != VOBSUB || !t.zlib() {
435 continue;
436 }
437 tracks += 1;
438 // Edith declares the track and accepts its encoding. It reads no VobSub
439 // payload, so nothing about the blocks is asked of edith here.
440 let sub = subs
441 .iter()
442 .find(|s| s.number == t.number)
443 .unwrap_or_else(|| panic!("{key}: edith lists no subtitle track {}", t.number));
444 assert_eq!(
445 sub.codec, VOBSUB,
446 "{key}: edith's codec for track {}",
447 t.number
448 );
449 assert!(
450 sub.unsupported.is_none(),
451 "{key}: edith refuses the zlib track: {:?}",
452 sub.unsupported
453 );
454
455 let index = pos as u32;
456 assert_eq!(
457 ff_streams[pos].kind, "subtitle",
458 "{key}: ffprobe stream {index} is not a subtitle stream"
459 );
460 let tb = time_base(&ff_streams, index);
461 let mut ours = Vec::new();
462 for b in file.blocks.iter().filter(|b| b.track == t.number) {
463 assert_eq!(b.lacing, 0, "{key}: a laced VobSub block is not expected");
464 let inflated = ec_inflate::inflate_zlib(&buf[b.range.clone()], LIMIT)
465 .unwrap_or_else(|e| panic!("{key}: a block did not inflate: {e}"));
466 ours.push(Got {
467 // Block ticks are in the segment's TimestampScale (nanoseconds
468 // a tick), so microseconds are ticks * scale / 1000.
469 start_us: i128::from(b.ticks) * i128::from(file.timestamp_scale) / 1000,
470 // A SimpleBlock states no duration; BlockDuration is not read
471 // here, so the duration is left for ffprobe to state alone.
472 duration_us: None,
473 len: inflated.len(),
474 md5: md5_hex(&inflated),
475 });
476 }
477 assert!(!ours.is_empty(), "{key}: no blocks for track {index}");
478 let ff = ffprobe_packets_of(&path, index);
479 packets += ours.len();
480 bad += compare(key, &format!("track {index}"), &ours, &ff, tb);
481 eprintln!(
482 "{key}: track {index} (VobSub, zlib): {} packets compared with ffprobe",
483 ours.len()
484 );
485 }
486 assert!(
487 tracks > 0,
488 "{key}: no zlib-compressed VobSub track in the file"
489 );
490 eprintln!(
491 "{key}: {packets} packets over {tracks} zlib VobSub track(s), {bad} mismatches, {:.1} s",
492 started.elapsed().as_secs_f64()
493 );
494 assert_eq!(bad, 0, "{key}: ec_inflate and ffprobe disagree");
495}
496
497#[test]
498fn zlib_pgs_tracks_match_ffprobe() {
499 check_pgs("mkv_zlib_pgs");
500}
501
502#[test]
503fn zlib_vobsub_tracks_match_ffprobe() {
504 check_vobsub("mkv_zlib_vobsub");
505}