forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

import_mp4_subs.rs232 lines, 8.4 KiBHistoryRawDownload
1//! An mp4's subtitles come back *in*: what `mux` writes as `tx3g` timed text,
2//! `subtitle::of_mp4` reads, so the default export format round-trips -- a file
3//! edith wrote is a file edith opens with its subtitle tracks still on it.
4//!
5//! Two witnesses again, the other way round from `export_subs.rs`: our own
6//! writer's file read by our own reader (the round trip), and a file **ffmpeg**
7//! muxed read by the same reader -- so what is pinned here is the format and
8//! not this project agreeing with itself.
9//!
10//! ```text
11//! cargo test -p engine --release --test import_mp4_subs -- --nocapture
12//! ```
13
14use std::path::PathBuf;
15use std::process::Command;
16use std::sync::Once;
17use std::time::{Duration, Instant};
18
19use engine::export::{ExportSettings, Format};
20use engine::scratch::Scratch;
21use engine::subtitle::{self, SubtitleTrack};
22use engine::{ExportHandle, Project};
23
24/// The media fixture: five seconds at 30 fps, a picture this box decodes and
25/// encodes with nothing installed.
26const MEDIA: &str = "test_av.mp4";
27const FRAMES: u32 = 150;
28/// What a cue may be out by: the track's own tick, a millisecond.
29const SLACK_US: i64 = 1_000;
30
31/// The three cues both fixtures carry, and the times an export puts them at.
32const WANT: [(i64, i64, &str); 3] = [
33 (500_000, 1_500_000, "first line"),
34 (2_000_000, 3_250_000, "second line\nwith a break"),
35 (4_000_000, 4_750_000, "third line"),
36];
37
38fn asset(name: &str) -> PathBuf {
39 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
40 .join("../../assets")
41 .join(name)
42}
43
44fn pin_software() {
45 static PIN: Once = Once::new();
46 PIN.call_once(|| {
47 engine::envcfg::set("VE_SW", "1");
48 engine::envcfg::set("VE_SW_ENC", "1");
49 });
50}
51
52fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
53 let started = Instant::now();
54 while !handle.is_finished() {
55 assert!(
56 started.elapsed() < limit,
57 "export did not finish in {limit:?}"
58 );
59 std::thread::sleep(Duration::from_millis(20));
60 }
61 handle.result().expect("a finished export has an outcome")
62}
63
64fn near(got: i64, want: i64, what: &str) {
65 assert!(
66 (got - want).abs() <= SLACK_US,
67 "{what}: {got} us is not within a millisecond of {want} us"
68 );
69}
70
71/// The two tracks `assets/test_subs.mkv` carries -- `eng` as `S_TEXT/UTF8` and
72/// `fra` titled `Signs` as `S_TEXT/ASS`, the same three cues twice -- repointed
73/// at the media this box can encode, exactly as `export_subs.rs` does it.
74fn both_tracks() -> Vec<SubtitleTrack> {
75 let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture");
76 assert_eq!(
77 tracks.len(),
78 2,
79 "the fixture carries two tracks: {tracks:?}"
80 );
81 for track in &mut tracks {
82 track.path = asset(MEDIA);
83 }
84 tracks
85}
86
87/// An mp4 export of both tracks, on disk.
88fn exported_mp4(name: &str) -> Scratch {
89 pin_software();
90 let out = Scratch::file(&format!("ve_import_mp4_subs_{name}"), "mp4");
91 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
92 let handle = engine::export::start(
93 Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()),
94 meta,
95 &out,
96 &ExportSettings {
97 format: Format::Mp4,
98 subtitles: vec![0, 1],
99 ..Default::default()
100 },
101 None,
102 );
103 wait(&handle, Duration::from_secs(300)).expect("the export finishes");
104 out
105}
106
107fn check_pair(tracks: &[SubtitleTrack], what: &str) {
108 for track in tracks {
109 println!(
110 "{what}: {} track {:?} {:?}",
111 track.label,
112 track.track,
113 track
114 .cues
115 .iter()
116 .map(|c| (c.start_us, c.end_us, &c.text))
117 .collect::<Vec<_>>()
118 );
119 }
120 assert_eq!(tracks.len(), 2, "{what}: two tracks: {tracks:?}");
121 // The language and the title, apart: `eng` is a language alone, `Signs` is
122 // a French track's own name -- the pair `mdhd` and `trak/udta/name` hold.
123 assert_eq!(tracks[0].label, "eng", "{what}");
124 assert_eq!(tracks[1].label, "fra — Signs", "{what}");
125 for track in tracks {
126 assert_eq!(track.refused, None, "{what}: the track reads");
127 assert!(!track.is_bitmap(), "{what}: timed text is not pictures");
128 assert_eq!(
129 track.cues.len(),
130 3,
131 "{what}: the empty samples between the cues are not cues: {:?}",
132 track.cues
133 );
134 for (cue, (start, end, text)) in track.cues.iter().zip(WANT) {
135 near(cue.start_us, start, &format!("{what}: cue start"));
136 near(cue.end_us, end, &format!("{what}: cue end"));
137 assert_eq!(cue.text, text, "{what}: the words travel, breaks and all");
138 assert!(cue.image.is_none(), "{what}: text, not a picture");
139 }
140 }
141}
142
143/// The round trip: two tracks out as `tx3g`, the same two back in -- languages,
144/// titles, words and times.
145#[test]
146fn an_mp4_export_comes_back_with_the_subtitles_it_left_with() {
147 let out = exported_mp4("round");
148 let tracks = subtitle::of_mp4(&out).expect("read our own mp4 back");
149 println!(
150 "our mp4 reads back as: {:?}",
151 tracks
152 .iter()
153 .map(|t| (&t.label, t.track, t.cues.len()))
154 .collect::<Vec<_>>()
155 );
156 check_pair(&tracks, "our own writer");
157 // The picture is track 1 and the sound 2, so the text is 3 and 4 -- the
158 // numbers a `.edith` row names, which is what makes the row openable.
159 assert_eq!(
160 tracks.iter().map(|t| t.track).collect::<Vec<_>>(),
161 vec![Some(3), Some(4)]
162 );
163
164 // ...and through the door a saved project comes back in by, which is the
165 // point of the numbers above.
166 let second = subtitle::open(&out, Some(4));
167 assert_eq!(second.refused, None, "the saved row opens: {second:?}");
168 assert_eq!(second.label, "fra — Signs");
169 assert_eq!(second.cues.len(), 3);
170 std::fs::remove_file(&out).unwrap();
171}
172
173/// The same file read by the same door the *import button* goes through, which
174/// is what makes this reachable rather than merely written.
175#[test]
176fn the_import_door_walks_an_mp4_for_its_subtitles() {
177 let out = exported_mp4("import");
178 let tracks =
179 engine::PlaybackSession::parse_subtitles(&out).expect("the import door walks the mp4");
180 check_pair(&tracks, "the import door");
181 std::fs::remove_file(&out).unwrap();
182}
183
184/// A file with no timed-text track: no tracks, no refusal, nothing invented.
185#[test]
186fn an_mp4_without_subtitles_reads_as_no_tracks_at_all() {
187 let tracks = subtitle::of_mp4(&asset(MEDIA)).expect("the fixture opens");
188 assert!(tracks.is_empty(), "nothing was invented: {tracks:?}");
189 let raw = engine::demux::mp4_subtitles(&asset(MEDIA)).expect("the walk itself");
190 assert!(raw.is_empty(), "{raw:?}");
191}
192
193/// The other implementation's file: what `ffmpeg -c:s mov_text` muxes, read by
194/// this reader. Skipped where there is no ffmpeg on the box -- the test is not
195/// about this machine's packages.
196#[test]
197fn an_ffmpeg_muxed_mov_text_track_reads_the_same_way() {
198 let out = Scratch::file("ve_import_mp4_subs_ffmpeg", "mp4");
199 let made = Command::new("ffmpeg")
200 .args(["-y", "-v", "error", "-i"])
201 .arg(asset("test_subs.mkv"))
202 .args([
203 "-map", "0:v", "-map", "0:s", "-c:v", "copy", "-c:s", "mov_text",
204 ])
205 .arg(&*out)
206 .status();
207 let Ok(status) = made else {
208 println!("no ffmpeg on this box: the round trip is the only witness");
209 return;
210 };
211 assert!(status.success(), "ffmpeg refused to mux the fixture");
212
213 let tracks = subtitle::of_mp4(&out).expect("read ffmpeg's mp4");
214 println!(
215 "ffmpeg's mp4 reads back as: {:?}",
216 tracks
217 .iter()
218 .map(|t| (&t.label, t.track, t.cues.len()))
219 .collect::<Vec<_>>()
220 );
221 // ffmpeg's timed-text tracks are timed in *microseconds* where ours are in
222 // milliseconds, and it writes the same `trak/udta/name` for the title: the
223 // two things a reader of one muxer's quirks would get wrong.
224 check_pair(&tracks, "ffmpeg's muxer");
225 let raw = engine::demux::mp4_subtitles(&out).expect("the walk itself");
226 assert_eq!(
227 raw[1].language, "fra",
228 "the language is the file's: {raw:?}"
229 );
230 assert_eq!(raw[1].name, "Signs", "...and the title is beside it");
231 std::fs::remove_file(&out).unwrap();
232}