forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

bitmap_subs.rs153 lines, 6.6 KiBHistoryRawDownload
1//! DVD (VobSub) and DVB bitmap subtitles imported the way PGS is: the tracks come out of
2//! a Matroska file, a transport stream and an `.idx`/`.sub` pair as picture cues with
3//! the container's timing, and a cue draws the pixels the encoder was given.
4//!
5//! The fixtures are generated here, at test time, from the synthetic source of
6//! `edith_codecs/scripts/gen-bitmap-sub-fixtures.py` (four cues, 0.5-1.5, 2.0-3.2,
7//! 3.5-4.5 and 5.0-6.0 s on 720x576) through ffmpeg's `dvdsub` and `dvbsub` encoders; no
8//! media is checked in. Without ffmpeg, python3 with PIL, or the codec checkout, a test
9//! prints a `SKIP` line and passes -- unless `EC_REQUIRE_FIXTURES=1`, which fails it.
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13use std::sync::OnceLock;
14
15use engine::PlaybackSession;
16use engine::subtitle::SubtitleTrack;
17
18const STARTS_MS: [i64; 4] = [500, 2000, 3500, 5000];
19const ENDS_MS: [i64; 4] = [1500, 3200, 4500, 6000];
20
21fn skip(why: &str) -> Option<PathBuf> {
22 if std::env::var("EC_REQUIRE_FIXTURES").is_ok_and(|v| v == "1") {
23 panic!("EC_REQUIRE_FIXTURES=1 but the bitmap subtitle fixtures cannot be made: {why}");
24 }
25 eprintln!("SKIP bitmap_subs: {why}; this test did not run");
26 None
27}
28
29/// The directory of generated fixtures: `dvd.mkv`, `dvd.idx`, `dvd.sub`, `dvb.ts`, `dvb.mkv`.
30fn fixtures() -> Option<PathBuf> {
31 static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
32 DIR.get_or_init(make).clone()
33}
34
35fn make() -> Option<PathBuf> {
36 let codecs = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../edith_codecs");
37 let script = codecs.join("scripts/gen-bitmap-sub-fixtures.py");
38 if !script.exists() {
39 return skip("edith_codecs/scripts/gen-bitmap-sub-fixtures.py is not there");
40 }
41 let dir = std::env::temp_dir().join(format!("edith-bitmap-subs-{}", std::process::id()));
42 std::fs::create_dir_all(&dir).ok()?;
43 let sup = dir.join("src.sup");
44 let ok = |c: &mut Command| c.status().is_ok_and(|s| s.success());
45 // `EC_PYTHON` names an interpreter with PIL when the system python3 has none.
46 let python = std::env::var("EC_PYTHON").unwrap_or_else(|_| "python3".into());
47 if !ok(Command::new(python).arg(&script).arg(&sup)) {
48 return skip("python3 with PIL could not run the source generator");
49 }
50 let ff = |args: &[&str], out: &Path| {
51 ok(Command::new("ffmpeg")
52 .args(["-v", "error", "-y", "-fix_sub_duration", "-f", "sup", "-i"])
53 .arg(&sup)
54 .args(args)
55 .arg(out))
56 };
57 let (dvd_mkv, dvd_sub, dvb_mkv, dvb_ts) = (
58 dir.join("dvd.mkv"),
59 dir.join("dvd.sub"),
60 dir.join("dvb.mkv"),
61 dir.join("dvb.ts"),
62 );
63 let made = ff(&["-c:s", "dvdsub", "-map", "0"], &dvd_mkv)
64 && ff(&["-c:s", "dvdsub", "-map", "0", "-target", "pal-dvd"], &dvd_sub)
65 && ff(&["-c:s", "dvbsub", "-map", "0"], &dvb_mkv)
66 && ok(Command::new("ffmpeg")
67 .args(["-v", "error", "-y", "-fix_sub_duration", "-f", "sup", "-i"])
68 .arg(&sup)
69 .args(["-f", "lavfi", "-i", "color=c=black:s=64x64:r=5:d=7"])
70 .args(["-c:v", "mpeg2video", "-b:v", "50k", "-c:s", "dvbsub", "-map", "0", "-map", "1"])
71 .arg(&dvb_ts));
72 if !made {
73 return skip("ffmpeg could not encode the dvdsub/dvbsub fixtures");
74 }
75 // The palette of ffmpeg's dvdsub encoder is the DVD default table, which a missing
76 // `palette:` line selects; the idx only has to name the canvas.
77 std::fs::write(dir.join("dvd.idx"), "size: 720x576\nid: en, index: 0\n").ok()?;
78 Some(dir)
79}
80
81fn within(got_us: i64, want_ms: i64, tol_ms: i64, what: &str) {
82 let d = (got_us / 1000 - want_ms).abs();
83 assert!(d <= tol_ms, "{what}: {} ms, wanted {want_ms} ms (+-{tol_ms})", got_us / 1000);
84}
85
86/// The first and only bitmap track of `path`, checked cue by cue. The muxer that wrote
87/// the file may have moved every cue by one constant offset (ffmpeg's Matroska and TS
88/// muxers start a track at zero), so the times are compared after taking the first
89/// cue's offset off; the spacing and the pictures are what must match.
90fn check(track: &SubtitleTrack) {
91 assert!(track.is_bitmap(), "a DVD/DVB track is pictures");
92 assert_eq!(track.refused, None);
93 assert_eq!(track.cues.len(), 4, "four cues");
94 let shift = track.cues[0].start_us - STARTS_MS[0] * 1000;
95 for (i, cue) in track.cues.iter().enumerate() {
96 within(cue.start_us - shift, STARTS_MS[i], 40, &format!("cue {i} start"));
97 within(cue.end_us - shift, ENDS_MS[i], 100, &format!("cue {i} end"));
98 let image = cue.image.as_ref().expect("a picture");
99 assert_eq!((image.width, image.height), (720, 576));
100 let rgba = image.rgba().expect("it decodes");
101 assert_eq!(rgba.len(), 720 * 576 * 4);
102 let painted = rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count();
103 assert!(painted > 200, "cue {i} paints text, got {painted} pixels");
104 assert!(painted < 720 * 576 / 2, "and leaves most of the canvas clear");
105 }
106}
107
108fn the_only_track(path: &Path) -> SubtitleTrack {
109 let mut tracks = PlaybackSession::parse_subtitles(path).expect("the file's subtitles");
110 assert_eq!(tracks.len(), 1, "one subtitle track in {}", path.display());
111 tracks.remove(0)
112}
113
114#[test]
115fn a_matroska_vobsub_track_imports_and_draws() {
116 let Some(dir) = fixtures() else { return };
117 check(&the_only_track(&dir.join("dvd.mkv")));
118}
119
120#[test]
121fn a_matroska_dvb_track_imports_and_draws() {
122 let Some(dir) = fixtures() else { return };
123 check(&the_only_track(&dir.join("dvb.mkv")));
124}
125
126#[test]
127fn a_transport_stream_dvb_track_imports_and_draws() {
128 let Some(dir) = fixtures() else { return };
129 let ts = the_only_track(&dir.join("dvb.ts"));
130 check(&ts);
131 // The probe lists it as a subtitle of its own kind.
132 let facts = engine::demux::probe_media(&dir.join("dvb.ts"));
133 assert!(
134 facts.streams.iter().any(|s| s.codec_id.as_deref() == Some("dvb_subtitle")),
135 "the probe names the stream dvb_subtitle"
136 );
137}
138
139#[test]
140fn an_idx_sub_pair_imports_from_either_file() {
141 let Some(dir) = fixtures() else { return };
142 for name in ["dvd.idx", "dvd.sub"] {
143 let track = the_only_track(&dir.join(name));
144 // A pair's cues carry the muxer's offset: compare the spacing, not the origin.
145 assert!(track.is_bitmap());
146 assert_eq!(track.cues.len(), 4);
147 let shift = track.cues[0].start_us - STARTS_MS[0] * 1000;
148 for (i, cue) in track.cues.iter().enumerate() {
149 within(cue.start_us - shift, STARTS_MS[i], 40, "pair cue start");
150 assert!(cue.image.as_ref().unwrap().rgba().unwrap().chunks(4).any(|p| p[3] > 0));
151 }
152 }
153}