forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

export_subs.rs1112 lines, 45.8 KiBHistoryRawDownload
1//! Subtitles leave with the file, whichever file: a Matroska export carries
2//! every picked track as `S_TEXT/UTF8` and an mp4 carries it as `tx3g` timed
3//! text, both timed on the *exported* timeline -- so a cut moves the cues with
4//! the pictures they belong to in either container.
5//!
6//! Two witnesses for every cue: this project's own Matroska reader
7//! (`demux::matroska_subtitles`, the way an exported file comes back into a
8//! project) and, where the box has it, ffmpeg -- which is what "it plays
9//! elsewhere" means and the only thing that can say this file is not merely
10//! self-consistent.
11//!
12//! ```text
13//! cargo test -p engine --release --test export_subs -- --nocapture
14//! ```
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18use std::sync::Once;
19use std::time::{Duration, Instant};
20
21use engine::export::{ExportSettings, Format};
22use engine::project::{Lane, LaneKind, SubClip};
23use engine::scratch::Scratch;
24use engine::subtitle::{self, Cue, SubtitleTrack};
25use engine::{ExportHandle, Project};
26
27/// The media fixture: five seconds at 30 fps, and a picture this box can decode
28/// with nothing installed.
29const MEDIA: &str = "test_av.mp4";
30const FRAMES: u32 = 150;
31/// What a cue may be out by: the file's own tick, a millisecond. The mapping is
32/// exact microseconds -- only the write rounds -- so nothing wider than this is
33/// being allowed for.
34const SLACK_US: i64 = 1_000;
35
36fn asset(name: &str) -> PathBuf {
37 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
38 .join("../../assets")
39 .join(name)
40}
41
42fn out_path(name: &str) -> Scratch {
43 Scratch::file(&format!("ve_subs_export_{name}"), "mkv")
44}
45
46fn pin_software() {
47 static PIN: Once = Once::new();
48 PIN.call_once(|| unsafe {
49 std::env::set_var("VE_SW", "1");
50 std::env::set_var("VE_SW_ENC", "1");
51 });
52}
53
54/// One export alone costs ~70 s software-seat on the machine of record, and
55/// the harness runs this binary's tests together -- the limit is a hang
56/// guard against a stuck export, never a speed claim.
57fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
58 let started = Instant::now();
59 while !handle.is_finished() {
60 assert!(
61 started.elapsed() < limit,
62 "export did not finish in {limit:?}"
63 );
64 std::thread::sleep(Duration::from_millis(20));
65 }
66 handle.result().expect("a finished export has an outcome")
67}
68
69/// The three cues the subtitle fixtures hold (`tests/subtitles.rs` pins them
70/// against the real `.srt`, `.ass` and `.mkv`), on a timeline of the media they
71/// are timed against.
72///
73/// The track says it came out of *this* media file, which is what an embedded
74/// track is and what makes its cues the file's own clock rather than the
75/// timeline's. Written out here rather than read out of `test_subs.mkv` because
76/// that fixture's picture is AV1 and there is no software AV1 decoder to export
77/// it through; the cues are the same three either way.
78fn track() -> SubtitleTrack {
79 SubtitleTrack {
80 path: asset(MEDIA),
81 track: Some(2),
82 language: "eng".into(),
83 name: String::new(),
84 label: "eng".into(),
85 bitmap: false,
86 cues: vec![
87 Cue {
88 start_us: 500_000,
89 end_us: 1_500_000,
90 text: "first line".into(),
91 image: None,
92 },
93 Cue {
94 start_us: 2_000_000,
95 end_us: 3_250_000,
96 text: "second line\nwith a break".into(),
97 image: None,
98 },
99 Cue {
100 start_us: 4_000_000,
101 end_us: 4_750_000,
102 text: "third line".into(),
103 image: None,
104 },
105 ],
106 refused: None,
107 }
108}
109
110fn project() -> Project {
111 Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()])
112}
113
114/// The two subtitle tracks `assets/test_subs.mkv` really carries -- `eng` as
115/// `S_TEXT/UTF8` and `fra` (titled `Signs`) as `S_TEXT/ASS`, the same three cues
116/// twice -- read back out of it the way an import reads them, and repointed at
117/// the media this box can encode: that fixture's own picture is AV1 and there is
118/// no software AV1 decoder to export it through.
119fn both_tracks() -> Vec<SubtitleTrack> {
120 let mut tracks = subtitle::of_matroska(&asset("test_subs.mkv")).expect("read the fixture");
121 assert_eq!(
122 tracks.len(),
123 2,
124 "the fixture carries two tracks: {tracks:?}"
125 );
126 for track in &mut tracks {
127 track.path = asset(MEDIA);
128 }
129 tracks
130}
131
132/// Exports `project` as an HEVC Matroska carrying the subtitle tracks `picks`,
133/// and hands back what our own reader finds in the file -- one track per pick,
134/// in the order they were picked.
135fn exported(name: &str, project: Project, picks: &[usize]) -> (Scratch, Vec<SubtitleTrack>) {
136 exported_want(name, project, picks, picks.len())
137}
138
139/// The same, for a project whose tracks are its subtitle *lanes*: the picks say
140/// nothing then ([`engine::export::planned_subtitles`] reads the lanes instead),
141/// so how many tracks the file must carry is the caller's own statement.
142fn exported_want(
143 name: &str,
144 project: Project,
145 picks: &[usize],
146 want: usize,
147) -> (Scratch, Vec<SubtitleTrack>) {
148 pin_software();
149 let out = out_path(name);
150 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
151 let handle = engine::export::start(
152 project,
153 meta,
154 &out,
155 &ExportSettings {
156 format: Format::Hevc,
157 subtitles: picks.to_vec(),
158 ..Default::default()
159 },
160 None,
161 );
162 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
163 // The bar ends where it was told it would: the picture loop's own count and
164 // the total published for it are one number ([`export::export_spans`]), so a
165 // walk that ran past the media would show up here as well as in the file.
166 assert_eq!(handle.progress(), 1.0, "finished at full progress");
167 let tracks = subtitle::of_matroska(&out).expect("read the export back");
168 assert_eq!(tracks.len(), want, "exactly the tracks asked for: {tracks:?}");
169 for track in &tracks {
170 assert_eq!(track.refused, None, "the track reads back as text");
171 }
172 (out, tracks)
173}
174
175/// The same, as an **mp4**: the picked tracks leave as `tx3g` timed text, which
176/// is what an mp4 says a subtitle with. Nothing here reads the file back with
177/// this project's own reader -- there is no mp4 subtitle reader to read it with
178/// -- so ffmpeg is the witness and the caller asks it.
179fn exported_mp4(name: &str, project: Project, picks: &[usize]) -> Scratch {
180 pin_software();
181 let out = Scratch::file(&format!("ve_subs_export_{name}"), "mp4");
182 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
183 let handle = engine::export::start(
184 project,
185 meta,
186 &out,
187 &ExportSettings {
188 format: Format::Mp4,
189 subtitles: picks.to_vec(),
190 ..Default::default()
191 },
192 None,
193 );
194 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
195 out
196}
197
198/// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout:
199/// a second implementation reading the bytes, which is the whole point of it.
200/// `None` where there is no ffmpeg on the box -- the test is not about this
201/// machine's packages.
202fn ffmpeg_srt(path: &Path, which: usize) -> Option<String> {
203 let out = Command::new("ffmpeg")
204 .args(["-v", "error", "-i"])
205 .arg(path)
206 .args(["-map", &format!("0:s:{which}"), "-f", "srt", "-"])
207 .output()
208 .ok()?;
209 assert!(
210 out.status.success(),
211 "ffmpeg refused the exported subtitles: {}",
212 String::from_utf8_lossy(&out.stderr)
213 );
214 Some(String::from_utf8_lossy(&out.stdout).into_owned())
215}
216
217/// What streams ffmpeg lists in the file, as it prints them -- `ffmpeg -i` with
218/// no output, whose exit status is an error by design, so only the stream lines
219/// are read. That listing carries each track's *language* beside its type
220/// (`Stream #0:3(fra): Subtitle: subrip`), which is the second implementation's
221/// word on what language the file says it is in. `None` where there is no
222/// ffmpeg on the box.
223fn ffmpeg_streams(path: &Path) -> Option<String> {
224 let out = Command::new("ffmpeg").arg("-i").arg(path).output().ok()?;
225 let listing = String::from_utf8_lossy(&out.stderr).into_owned();
226 println!("ffmpeg sees:\n{listing}");
227 Some(listing)
228}
229
230/// The average luma of the **last** picture in `path`, as ffmpeg's
231/// `signalstats` measures it: what says a file's tail is a picture and not the
232/// encoded black a walk past the media would leave. `None` where there is no
233/// ffmpeg on the box, the same posture the readers above take.
234fn ffmpeg_last_luma(path: &Path) -> Option<f64> {
235 let out = Command::new("ffmpeg")
236 .args(["-v", "error", "-i"])
237 .arg(path)
238 .args([
239 "-vf",
240 "signalstats,metadata=print:key=lavfi.signalstats.YAVG:file=-",
241 "-f",
242 "null",
243 "-",
244 ])
245 .output()
246 .ok()?;
247 assert!(
248 out.status.success(),
249 "ffmpeg refused the exported picture: {}",
250 String::from_utf8_lossy(&out.stderr)
251 );
252 let printed = String::from_utf8_lossy(&out.stdout).into_owned();
253 let last = printed
254 .lines()
255 .filter_map(|line| line.split_once("YAVG=").map(|(_, v)| v.trim().to_string()))
256 .next_back()
257 .expect("signalstats printed a YAVG per frame");
258 println!("last written picture: YAVG {last}");
259 Some(last.parse().expect("YAVG is a number"))
260}
261
262/// When the file's **last sound** is, as ffprobe reads the packets: the sound is
263/// the other end that has to stop with the picture -- a copied lane's trailing
264/// gap is silence written past the last frame. `None` where there is no ffprobe.
265fn ffprobe_last_audio_pts(path: &Path) -> Option<f64> {
266 let out = Command::new("ffprobe")
267 .args(["-v", "error", "-select_streams", "a:0"])
268 .args(["-show_entries", "packet=pts_time", "-of", "csv=p=0"])
269 .arg(path)
270 .output()
271 .ok()?;
272 let printed = String::from_utf8_lossy(&out.stdout).into_owned();
273 let last = printed.lines().filter(|l| !l.trim().is_empty()).next_back()?;
274 println!("last audio packet: {last} s");
275 last.trim_end_matches(',').parse().ok()
276}
277
278fn near(got: i64, want: i64, what: &str) {
279 assert!(
280 (got - want).abs() <= SLACK_US,
281 "{what}: {got} us is not within a frame of {want} us"
282 );
283}
284
285/// The whole timeline, untouched: the file comes back with the very cues the
286/// source's track holds, at the times it holds them -- and ffmpeg reads the
287/// same three lines out of it.
288#[test]
289fn an_mkv_export_carries_the_picked_subtitle_track() {
290 let (out, tracks) = exported("plain", project(), &[0]);
291 let cues = &tracks[0].cues;
292 assert_eq!(cues.len(), 3, "three cues: {cues:?}");
293 let want = [
294 (500_000, 1_500_000, "first line"),
295 (2_000_000, 3_250_000, "second line\nwith a break"),
296 (4_000_000, 4_750_000, "third line"),
297 ];
298 for (cue, (start, end, text)) in cues.iter().zip(want) {
299 near(cue.start_us, start, "cue start");
300 near(cue.end_us, end, "cue end");
301 assert_eq!(cue.text, text, "the text travels, line breaks and all");
302 }
303 // ...and the track is named the way it was named in the source, so the
304 // subtitle menu of whatever plays this says `eng` too.
305 let tracks = subtitle::of_matroska(&out).expect("read back");
306 assert_eq!(tracks[0].label, "eng");
307 let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
308 assert_eq!(raw[0].codec, "S_TEXT/UTF8");
309 assert_eq!(raw[0].language, "eng", "the label went in as a language");
310
311 match ffmpeg_srt(&out, 0) {
312 Some(srt) => {
313 println!("ffmpeg reads the exported track back as:\n{srt}");
314 assert!(srt.contains("first line"), "{srt}");
315 assert!(srt.contains("with a break"), "{srt}");
316 assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}");
317 assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}");
318 }
319 None => println!("no ffmpeg on this box: our own reader is the only witness"),
320 }
321 std::fs::remove_file(&out).unwrap();
322}
323
324/// A cut timeline: `[0.5s, 2.5s)` rippled out of it, which is one cue gone
325/// entirely, one that straddles the far edge and keeps the half still there,
326/// and one that simply moves back with the picture.
327#[test]
328fn a_cut_moves_the_cues_with_the_pictures() {
329 let mut project = project();
330 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
331 assert_eq!(project.timeline_frames(), 90, "three seconds are left");
332 assert_eq!(
333 project.lane(Lane::V1).len(),
334 2,
335 "the hole closed, over two placements of the one source"
336 );
337
338 let (out, tracks) = exported("cut", project, &[0]);
339 let cues = &tracks[0].cues;
340 assert_eq!(
341 cues.len(),
342 2,
343 "the cue inside the cut is gone, the other two are not: {cues:?}"
344 );
345 // 2.0s..3.25s of the source, of which 2.5s on survived, landing where the
346 // cut left it: 0.5s..1.25s.
347 near(
348 cues[0].start_us,
349 500_000,
350 "the straddling cue starts at the cut",
351 );
352 near(
353 cues[0].end_us,
354 1_250_000,
355 "...and keeps the rest of its length",
356 );
357 assert_eq!(cues[0].text, "second line\nwith a break");
358 // 4.0s..4.75s of the source, two seconds back.
359 near(
360 cues[1].start_us,
361 2_000_000,
362 "the last cue moves back by the cut",
363 );
364 near(cues[1].end_us, 2_750_000, "...end with it");
365 assert_eq!(cues[1].text, "third line");
366
367 if let Some(srt) = ffmpeg_srt(&out, 0) {
368 println!("ffmpeg reads the cut export back as:\n{srt}");
369 assert!(
370 !srt.contains("first line"),
371 "the cut cue is not there: {srt}"
372 );
373 assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}");
374 assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}");
375 assert!(srt.contains("third line"), "{srt}");
376 }
377 std::fs::remove_file(&out).unwrap();
378}
379
380/// Nothing picked is nothing written -- the file every export of a timeline
381/// without subtitles has always been.
382#[test]
383fn an_export_with_no_pick_carries_no_subtitle_track() {
384 // `exported` asserts the file has no subtitle track at all; this is the
385 // pick being absent rather than the timeline having nothing to pick.
386 let (out, tracks) = exported("none", project(), &[]);
387 assert!(tracks.is_empty());
388 std::fs::remove_file(&out).unwrap();
389}
390
391/// As many tracks as the timeline holds, not one: both of a film's own subtitle
392/// tracks go into the export, each numbered and named for itself, and a player
393/// -- ffmpeg here -- offers the two of them.
394#[test]
395fn every_picked_track_travels_with_its_own_name() {
396 let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
397 let (out, tracks) = exported("both", project, &[0, 1]);
398 // The labels the fixture states: a language on one, a language and a muxer's
399 // title on the other, and neither is the other's.
400 assert_eq!(tracks[0].label, "eng");
401 assert_eq!(tracks[1].label, "fra — Signs");
402 for track in &tracks {
403 assert_eq!(track.cues.len(), 3, "three cues each: {track:?}");
404 near(track.cues[0].start_us, 500_000, "cue start");
405 near(track.cues[2].end_us, 4_750_000, "cue end");
406 assert_eq!(
407 track.cues[2].text, "third line",
408 "the ASS markup is resolved to text, not carried into the file"
409 );
410 }
411
412 // In the file itself: two text tracks, numbered from 3 up, and the second
413 // one's number is what its blocks name -- the reason the cues above came
414 // back apart rather than doubled onto one track.
415 let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
416 assert_eq!(
417 raw.iter().map(|t| t.number).collect::<Vec<_>>(),
418 vec![3, 4],
419 "the picture is 1, the sound 2, the text 3 and 4"
420 );
421 assert!(
422 raw.iter().all(|t| t.codec == "S_TEXT/UTF8"),
423 "both are written as text: {raw:?}"
424 );
425 assert_eq!(raw[0].language, "eng", "a three-letter label is a language");
426 // The language and the title are two fields, not one string: a track that
427 // says `fra` is what a player's "French" setting finds, and a track that
428 // says only `Signs` is an *English* track to every reader, Matroska's
429 // default language being `eng`.
430 assert_eq!(raw[1].language, "fra", "the French track says so in the file");
431 assert_eq!(raw[1].name, "Signs", "...and keeps its own title beside it");
432 assert_eq!(raw[1].codec, "S_TEXT/UTF8");
433
434 match ffmpeg_streams(&out) {
435 Some(listing) => {
436 let n = listing.matches("Subtitle:").count();
437 assert_eq!(n, 2, "ffmpeg lists both subtitle streams");
438 // The other implementation reads the same two languages -- this is
439 // the assertion that used to come back `(eng)` for the French one.
440 assert!(
441 listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
442 "ffmpeg sees one English and one French track: {listing}"
443 );
444 let second = ffmpeg_srt(&out, 1).expect("ffmpeg is here");
445 println!("ffmpeg reads the second track back as:\n{second}");
446 assert!(second.contains("third line"), "{second}");
447 assert!(second.contains("00:00:00,500 --> 00:00:01,500"), "{second}");
448 }
449 None => println!("no ffmpeg on this box: our own reader is the only witness"),
450 }
451 std::fs::remove_file(&out).unwrap();
452}
453
454/// The mp4 half of [`every_picked_track_travels_with_its_own_name`]: the very
455/// same two tracks into the container the export *defaults* to, where they used
456/// to be dropped with a card saying an mp4 carried none. ffmpeg is the whole
457/// witness here -- a second implementation reading the bytes -- and it reads two
458/// `mov_text` streams, one English and one French, the French one still titled
459/// `Signs`, with the three cues at the three times.
460#[test]
461fn an_mp4_export_carries_the_picked_tracks_as_timed_text() {
462 let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
463 let out = exported_mp4("mp4_both", project, &[0, 1]);
464 let Some(listing) = ffmpeg_streams(&out) else {
465 println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
466 std::fs::remove_file(&out).unwrap();
467 return;
468 };
469 assert_eq!(
470 listing.matches("Subtitle: mov_text").count(),
471 2,
472 "two timed-text streams, not none and not one: {listing}"
473 );
474 // The language is the `mdhd` field of each track, which is what a player's
475 // subtitle menu offers -- the mp4 spelling of the Matroska `Language` the
476 // sibling test pins.
477 assert!(
478 listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
479 "one English and one French: {listing}"
480 );
481 // ...and the title beside it, which an mp4 states in a `trak/udta/name` box
482 // that `mp4 0.14` has no field for and this project patches in.
483 assert!(
484 listing.contains("name : Signs"),
485 "the French track keeps its own title: {listing}"
486 );
487 for which in 0..2 {
488 let srt = ffmpeg_srt(&out, which).expect("ffmpeg is here");
489 println!("ffmpeg reads mp4 track {which} back as:\n{srt}");
490 assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}");
491 assert!(srt.contains("first line"), "{srt}");
492 // The line break inside a cue survives a sample that states its length
493 // in bytes and nothing else.
494 assert!(srt.contains("with a break"), "{srt}");
495 assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}");
496 assert!(srt.contains("third line"), "{srt}");
497 }
498 std::fs::remove_file(&out).unwrap();
499}
500
501/// The pair a container states, carried through as a *pair*, into both
502/// containers: a track's language and its title are two fields at every step
503/// from the demuxer to the muxer, and neither is derived from the other.
504///
505/// The two tracks here are the shapes that used to be lost. `fra` titled `Signs`
506/// is the one every multi-language export declared English -- the two were
507/// flattened into one label and split back apart by guessing, and a title that
508/// was not three lowercase letters took the language down with it. `und` titled
509/// `Commentary` is the same fault from the other side: a track that states its
510/// language is undetermined said nothing at all in the file, and a Matroska
511/// track with no `Language` *is* an English one by spec.
512///
513/// Read back with this project's own readers -- ffmpeg is no witness for `und`,
514/// which both its demuxers drop from the listing rather than print.
515#[test]
516fn a_language_and_a_title_are_two_fields_in_both_containers() {
517 let named = |language: &str, name: &str| SubtitleTrack {
518 language: language.into(),
519 name: name.into(),
520 label: format!("{language} — {name}"),
521 ..track()
522 };
523 let tracks = vec![named("fra", "Signs"), named("und", "Commentary")];
524 let project = || Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks.clone());
525
526 let (out, read) = exported("pair", project(), &[0, 1]);
527 let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
528 assert_eq!(
529 raw.iter()
530 .map(|t| (&t.language[..], &t.name[..]))
531 .collect::<Vec<_>>(),
532 vec![("fra", "Signs"), ("und", "Commentary")],
533 "the Matroska keeps both fields of both tracks"
534 );
535 // ...and the label a row shows is built back out of them, not stored:
536 // an undetermined language is no language to a reader.
537 assert_eq!(read[0].label, "fra — Signs");
538 assert_eq!(read[1].label, "Commentary");
539 std::fs::remove_file(&out).unwrap();
540
541 let out = exported_mp4("mp4_pair", project(), &[0, 1]);
542 let read = subtitle::of_mp4(&out).expect("read the mp4 back");
543 assert_eq!(
544 read.iter()
545 .map(|t| (&t.language[..], &t.name[..]))
546 .collect::<Vec<_>>(),
547 vec![("fra", "Signs"), ("und", "Commentary")],
548 "and so does the mp4, in its `mdhd` and its `udta/name`"
549 );
550 for track in &read {
551 assert_eq!(track.cues.len(), 3, "three cues each: {track:?}");
552 }
553 std::fs::remove_file(&out).unwrap();
554}
555
556/// The other mp4: an HEVC one, whose *video* sample entry is rewritten by hand
557/// after the file is closed (`mux::patch_entry` turns the crate's `avc1` into
558/// `hvc1`) -- the same rebuild of `moov` the subtitle track's title is patched
559/// into. The two patches are one walk, so this is the file that says they do not
560/// tread on each other: ffmpeg reads an HEVC picture *and* the timed text.
561#[test]
562fn an_hevc_mp4_keeps_its_rewritten_entry_and_its_text() {
563 pin_software();
564 let out = Scratch::file("ve_subs_export_hevc_mp4", "mp4");
565 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
566 let handle = engine::export::start(
567 Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks()),
568 meta,
569 &out,
570 &ExportSettings {
571 format: Format::HevcMp4,
572 subtitles: vec![1],
573 ..Default::default()
574 },
575 None,
576 );
577 wait(&handle, Duration::from_secs(1800)).expect("the export finishes");
578 let Some(listing) = ffmpeg_streams(&out) else {
579 println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
580 std::fs::remove_file(&out).unwrap();
581 return;
582 };
583 assert!(listing.contains("Video: hevc"), "the entry patch held: {listing}");
584 assert!(
585 listing.contains("(fra): Subtitle: mov_text"),
586 "...and the text track beside it: {listing}"
587 );
588 let srt = ffmpeg_srt(&out, 0).expect("ffmpeg is here");
589 assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}");
590 assert!(srt.contains("third line"), "{srt}");
591 std::fs::remove_file(&out).unwrap();
592}
593
594/// ...and the cut lands in an mp4 where it lands in a Matroska: the samples of a
595/// timed-text track are timed by their own durations, so a cue that moved with
596/// its pictures has to come out moved here too.
597#[test]
598fn a_cut_moves_the_mp4_cues_with_the_pictures() {
599 let mut project = project();
600 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
601 let out = exported_mp4("mp4_cut", project, &[0]);
602 let Some(srt) = ffmpeg_srt(&out, 0) else {
603 println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
604 std::fs::remove_file(&out).unwrap();
605 return;
606 };
607 println!("ffmpeg reads the cut mp4 export back as:\n{srt}");
608 assert!(!srt.contains("first line"), "the cut cue is not there: {srt}");
609 assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}");
610 assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}");
611 assert!(srt.contains("third line"), "{srt}");
612 std::fs::remove_file(&out).unwrap();
613}
614
615/// The ceiling itself, from underneath: a file carrying exactly
616/// `MAX_SUB_TRACKS` tracks comes back whole. The last of them is track 126,
617/// whose block byte is `0xFE` -- one under the all-ones `0xFF` that EBML spells
618/// *unknown* with, which is what a 127th track's blocks would say and why its
619/// cues would come back nowhere. Read back with our own reader, so the file is
620/// one edith can re-import and not merely write.
621#[test]
622fn the_last_numberable_track_keeps_its_cues() {
623 let full = engine::mux::MAX_SUB_TRACKS;
624 let picks: Vec<usize> = (0..full).collect();
625 let project =
626 Project::single(asset(MEDIA), FRAMES).with_subtitles((0..full).map(|_| track()).collect());
627 let (out, tracks) = exported("ceiling_at", project, &picks);
628 let empty: Vec<usize> = tracks
629 .iter()
630 .enumerate()
631 .filter(|(_, t)| t.cues.is_empty())
632 .map(|(i, _)| i)
633 .collect();
634 assert!(
635 empty.is_empty(),
636 "every one of the {full} tracks keeps its three cues; these came back with none: {empty:?}"
637 );
638 let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
639 assert_eq!(
640 raw.iter().map(|t| t.number).collect::<Vec<_>>(),
641 (3..3 + full as u64).collect::<Vec<_>>(),
642 "numbered 3 up to the last one a block byte can name"
643 );
644 assert_eq!(raw.last().map(|t| t.number), Some(126));
645 std::fs::remove_file(&out).unwrap();
646}
647
648/// The ceiling is said out loud: a Matroska block names its track in one byte,
649/// so past `MAX_SUB_TRACKS` the export refuses by name instead of writing a byte
650/// that means some other track -- and leaves no file behind.
651#[test]
652fn more_tracks_than_a_block_can_number_are_refused_by_name() {
653 pin_software();
654 let over = engine::mux::MAX_SUB_TRACKS + 1;
655 let project =
656 Project::single(asset(MEDIA), FRAMES).with_subtitles((0..over).map(|_| track()).collect());
657 let out = out_path("ceiling");
658 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
659 let handle = engine::export::start(
660 project,
661 meta,
662 &out,
663 &ExportSettings {
664 format: Format::Hevc,
665 subtitles: (0..over).collect(),
666 ..Default::default()
667 },
668 None,
669 );
670 let said = wait(&handle, Duration::from_secs(1800))
671 .expect_err("a file that cannot be numbered is not written")
672 .to_string();
673 assert!(
674 said.contains(&format!("{over} subtitle tracks"))
675 && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)),
676 "the refusal says how many were asked for and how many fit: {said}"
677 );
678 assert!(!out.exists(), "and no half-written file is left: {said}");
679}
680
681/// A language stated the modern way (`LanguageBCP47`, no legacy element) leaves
682/// with the file, in the element every reader looks at.
683///
684/// The loss used to survive the export: a 22-track Matroska listed
685/// `2,subrip,English (UK) (SDH)` with an *empty* language field beside
686/// neighbours that kept `ara` and `chi`, because the source stated `en` in an
687/// element nothing here read. What is written is still the legacy element -- a
688/// three-letter code is what Matroska's `Language` and an mp4's `mdhd` hold, and
689/// ffmpeg 8.1.2 reads no `LanguageBCP47` at all.
690#[test]
691fn a_language_stated_the_modern_way_leaves_with_the_file() {
692 let mut tracks =
693 subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("read the fixture");
694 assert_eq!(
695 tracks.len(),
696 2,
697 "the fixture carries two tracks: {tracks:?}"
698 );
699 for track in &mut tracks {
700 track.path = asset(MEDIA);
701 }
702 assert_eq!(
703 tracks.iter().map(|t| &*t.language).collect::<Vec<_>>(),
704 ["eng", "fra"],
705 "`en` and `fr` are read as the codes an export writes"
706 );
707
708 let project = Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks);
709 let (out, back) = exported("bcp47", project, &[0, 1]);
710 assert_eq!(
711 back.iter().map(|t| &*t.language).collect::<Vec<_>>(),
712 ["eng", "fra"],
713 "and they are the codes the file states"
714 );
715 let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element");
716 assert_eq!(
717 raw[1].name, "Signs",
718 "the title travels beside the language"
719 );
720 if let Some(listing) = ffmpeg_streams(&out) {
721 assert!(
722 listing.contains("(eng): Subtitle") && listing.contains("(fra): Subtitle"),
723 "a second implementation reads both languages: {listing}"
724 );
725 }
726 std::fs::remove_file(&out).unwrap();
727}
728
729/// What the card says before the button is pressed, which is where an mp4's
730/// refusal has to land: the file is not the place to find out.
731#[test]
732fn the_plan_says_what_each_container_does_with_them() {
733 let project = project();
734 let plan = |format| engine::export::planned_subtitles(&project, format, Some(0));
735 assert_eq!(plan(Format::Hevc), "eng → embedded");
736 assert_eq!(plan(Format::Av1), "eng → embedded");
737 // An mp4 carries them too, as `tx3g` -- so the card says what travels
738 // rather than which container to switch to. The refusal it used to print
739 // ("mkv only — an mp4 carries none") was a claim about the container that
740 // the container never made.
741 assert_eq!(plan(Format::Mp4), "eng → embedded");
742 assert_eq!(plan(Format::HevcMp4), "eng → embedded");
743 assert_eq!(plan(Format::Av1Mp4), "eng → embedded");
744 assert_eq!(plan(Format::Wav), "none — this format is the sound alone");
745 // A track of *pictures* on a format that is the sound alone says what the
746 // file cannot do rather than what the track cannot: the per-track reason
747 // used to be pushed first, which left the sentence above unreachable for a
748 // pick that was all bitmaps -- an MP3 with a PGS track picked read
749 // "pictures; drawn, not written", a true sentence about the wrong thing.
750 let mut pictures = track();
751 pictures.bitmap = true;
752 pictures.label = "PGS".into();
753 let pgs = Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![pictures]);
754 assert_eq!(
755 engine::export::planned_subtitles(&pgs, Format::Mp3, Some(0)),
756 "none — this format is the sound alone"
757 );
758 // ...and on a container that carries text it is the *track* that cannot
759 // travel, which is the other sentence and just as true: both are reachable.
760 assert_eq!(
761 engine::export::planned_subtitles(&pgs, Format::Hevc, Some(0)),
762 "PGS — pictures; drawn, not written"
763 );
764 // Nothing picked is "none" whatever the format -- there is no track for a
765 // container to have nowhere to put.
766 assert_eq!(
767 engine::export::planned_subtitles(&pgs, Format::Mp3, None),
768 "none"
769 );
770 // No pick is "none" rather than a panic or a lie...
771 assert_eq!(
772 engine::export::planned_subtitles(&project, Format::Hevc, None),
773 "none"
774 );
775 // ...and a pick the project has no row for is *named*, like every other
776 // reason a pick does not travel: an index nothing answers is a caller's bug
777 // and the card is where a bug is seen, not the finished file.
778 assert_eq!(
779 engine::export::planned_subtitles(&project, Format::Hevc, Some(9)),
780 "#9 — no such track"
781 );
782 let bare = Project::single(asset(MEDIA), FRAMES);
783 assert_eq!(
784 engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)),
785 "#0 — no such track"
786 );
787 // ...and it costs its own row and not the others': the tracks around it
788 // still travel, which is what made this one easy to miss.
789 assert_eq!(
790 engine::export::planned_subtitles(&project, Format::Hevc, [0, 99]),
791 "eng → embedded; #99 — no such track"
792 );
793
794 // Two picks are two tracks, named: the count first, because that is what the
795 // row is answering, and the names after it because that is what a menu will
796 // show.
797 let two = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
798 assert_eq!(
799 engine::export::planned_subtitles(&two, Format::Hevc, [0, 1]),
800 "2 tracks → embedded (eng, fra — Signs)"
801 );
802 // ...and a pick that cannot travel costs its own row and not the other's:
803 // the empty track is dropped by name, the real one still goes.
804 let mut mixed = both_tracks();
805 mixed[1].cues.clear();
806 let mixed = Project::single(asset(MEDIA), FRAMES).with_subtitles(mixed);
807 assert_eq!(
808 engine::export::planned_subtitles(&mixed, Format::Hevc, [0, 1]),
809 "eng → embedded; fra — Signs — no cues"
810 );
811}
812
813// --- The lanes -------------------------------------------------------------
814//
815// A timeline that *places* its words writes one track per subtitle lane, in
816// lane order, and the pick list above says nothing about it. Every project that
817// exists today has no placement and takes the old door -- which is what the
818// tests above are, unchanged.
819
820/// A project of the fixture media with one subtitle lane per `(track, at,
821/// frames, in_us, out_us)`, in the order given: `S1` first.
822fn on_lanes(tracks: Vec<SubtitleTrack>, placed: &[(usize, u32, u32, i64, i64)]) -> Project {
823 let mut project = Project::single(asset(MEDIA), FRAMES).with_subtitles(tracks);
824 for &(track, at, frames, in_us, out_us) in placed {
825 let lane = project.add_lane(LaneKind::Subtitle);
826 project
827 .place_sub(
828 lane,
829 at,
830 SubClip {
831 start: at,
832 frames,
833 track,
834 in_us,
835 out_us,
836 link: None,
837 },
838 )
839 .expect("the lane is empty, so the placement lands");
840 }
841 project
842}
843
844/// The whole of a palette row, placed at frame 0: the window every "this lane
845/// carries that track" test wants.
846const WHOLE: (u32, u32, i64, i64) = (0, FRAMES, 0, 5_000_000);
847
848/// Two lanes are two tracks, **in lane order** -- not in the palette's. `S1`
849/// carries the French row and `S2` the English one, and the file declares them
850/// that way round, which is what a subtitle menu will list.
851#[test]
852fn a_lane_is_a_track_and_the_lanes_order_the_file() {
853 let project = on_lanes(
854 both_tracks(),
855 &[
856 (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
857 (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
858 ],
859 );
860 // The card says the same before the button is pressed, lane by lane.
861 assert_eq!(
862 engine::export::planned_subtitles(&project, Format::Hevc, [0, 1]),
863 "2 lanes → embedded (S1 fra — Signs, S2 eng)"
864 );
865
866 // ...and the picks are *not* what travels: this asks for the palette's order
867 // and gets the lanes' one.
868 let (out, tracks) = exported_want("lanes_two", project, &[0, 1], 2);
869 assert_eq!(tracks[0].label, "fra — Signs", "S1 is the first track");
870 assert_eq!(tracks[1].label, "eng", "S2 is the second");
871 for track in &tracks {
872 assert_eq!(track.cues.len(), 3, "the lane's whole window: {track:?}");
873 near(track.cues[0].start_us, 500_000, "cue start");
874 near(track.cues[2].end_us, 4_750_000, "cue end");
875 }
876 if let Some(listing) = ffmpeg_streams(&out) {
877 assert!(
878 listing.contains("(fra): Subtitle") && listing.contains("(eng): Subtitle"),
879 "a second implementation reads both lanes: {listing}"
880 );
881 }
882 std::fs::remove_file(&out).unwrap();
883}
884
885/// The same two lanes into an **mp4**, where a track is `tx3g` timed text:
886/// ffmpeg reads two `mov_text` streams in the lanes' order.
887#[test]
888fn two_lanes_leave_an_mp4_as_two_timed_text_tracks() {
889 let project = on_lanes(
890 both_tracks(),
891 &[
892 (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
893 (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
894 ],
895 );
896 let out = exported_mp4("lanes_mp4", project, &[]);
897 let Some(listing) = ffmpeg_streams(&out) else {
898 println!("no ffmpeg on this box: an mp4's tx3g has no other reader here");
899 std::fs::remove_file(&out).unwrap();
900 return;
901 };
902 assert_eq!(
903 listing.matches("Subtitle: mov_text").count(),
904 2,
905 "one stream per lane, though nothing was picked: {listing}"
906 );
907 assert!(
908 listing.contains("(fra): Subtitle") && listing.contains("(eng): Subtitle"),
909 "both lanes' languages: {listing}"
910 );
911 let srt = ffmpeg_srt(&out, 0).expect("ffmpeg is here");
912 println!("ffmpeg reads mp4 lane S1 back as:\n{srt}");
913 assert!(
914 srt.contains("first line") && srt.contains("third line"),
915 "{srt}"
916 );
917 std::fs::remove_file(&out).unwrap();
918}
919
920/// A *trimmed* placement carries the cues its window keeps and no others, at the
921/// times the placement puts them: 2.5s..5.0s of the track, dropped at timeline
922/// frame 60, is the last two cues two and a half seconds earlier than the track
923/// states them -- and the first one, outside the window, is not in the file.
924#[test]
925fn a_trimmed_placement_writes_the_cues_it_keeps_where_it_puts_them() {
926 let project = on_lanes(vec![track()], &[(0, 60, 75, 2_500_000, 5_000_000)]);
927 let (out, tracks) = exported_want("lanes_trim", project, &[], 1);
928 let cues = &tracks[0].cues;
929 assert_eq!(cues.len(), 2, "the first cue is outside the window: {cues:?}");
930 // 2.0..3.25 of the track, of which 2.5s on is inside the window, landing at
931 // the placement's frame 60 (2.0s).
932 near(
933 cues[0].start_us,
934 2_000_000,
935 "the straddling cue starts at the drop",
936 );
937 near(cues[0].end_us, 2_750_000, "...and keeps the rest of its length");
938 assert_eq!(cues[0].text, "second line\nwith a break");
939 // 4.0..4.75, a second and a half into the window.
940 near(
941 cues[1].start_us,
942 3_500_000,
943 "the last cue moves with the placement",
944 );
945 near(cues[1].end_us, 4_250_000, "...end with it");
946 assert_eq!(cues[1].text, "third line");
947 if let Some(srt) = ffmpeg_srt(&out, 0) {
948 println!("ffmpeg reads the trimmed lane back as:\n{srt}");
949 assert!(!srt.contains("first line"), "{srt}");
950 assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}");
951 assert!(srt.contains("00:00:03,500 --> 00:00:04,250"), "{srt}");
952 }
953 std::fs::remove_file(&out).unwrap();
954}
955
956/// A lane nobody has placed anything on is not a project that uses lanes: the
957/// picks still say what travels, byte for byte the file today's app exports.
958#[test]
959fn an_empty_lane_leaves_the_pick_list_in_charge() {
960 let mut project = Project::single(asset(MEDIA), FRAMES).with_subtitles(both_tracks());
961 project.add_lane(LaneKind::Subtitle);
962 assert_eq!(
963 engine::export::planned_subtitles(&project, Format::Hevc, [0]),
964 "eng → embedded",
965 "the pick list's words, not a lane's"
966 );
967 let (out, tracks) = exported("lanes_none", project, &[0]);
968 assert_eq!(tracks.len(), 1, "the pick, and only the pick");
969 assert_eq!(tracks[0].label, "eng");
970 assert_eq!(tracks[0].cues.len(), 3);
971 std::fs::remove_file(&out).unwrap();
972}
973
974/// A lane of **pictures** writes nothing at all, and says why before the button
975/// is pressed: both muxers write words (`S_TEXT/UTF8`, `tx3g`) and neither has a
976/// path that could write a bitmap -- the refusal is the capability's absence and
977/// not a policy.
978#[test]
979fn a_lane_of_pictures_is_refused_in_words_and_written_nowhere() {
980 let mut pictures = track();
981 pictures.bitmap = true;
982 pictures.label = "PGS".into();
983 let project = on_lanes(
984 vec![track(), pictures],
985 &[
986 (0, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
987 (1, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3),
988 ],
989 );
990 assert_eq!(
991 engine::export::planned_subtitles(&project, Format::Hevc, []),
992 "S1 eng → embedded; S2 PGS — pictures; drawn, not written",
993 "the picture lane costs its own row and not the other's"
994 );
995 // ...and the file has the one lane's track and nothing for the other: zero
996 // streams for a lane of pictures, not an empty one.
997 let (out, tracks) = exported_want("lanes_pgs", project, &[], 1);
998 assert_eq!(
999 tracks[0].label, "eng",
1000 "the words travelled; the pictures did not"
1001 );
1002 std::fs::remove_file(&out).unwrap();
1003}
1004
1005/// A caption hanging past the last picture: the timeline is held open under it
1006/// ([`Project::timeline_frames`]) but the export ends with the picture, so what
1007/// is out there is cut off -- a cue straddling the end keeps the half inside, a
1008/// lane wholly past it writes no track, and the card says so.
1009#[test]
1010fn a_caption_past_the_last_picture_is_cut_off_with_the_file() {
1011 // S1 straddles the end: dropped at frame 120 (4.0s) with a 60-frame window
1012 // of the track's first two seconds, so its one cue runs 4.5s..5.5s and the
1013 // media stops at 5.0s. S2 sits entirely past the end.
1014 let project = on_lanes(
1015 vec![track(), track()],
1016 &[(0, 120, 60, 0, 2_000_000), (1, FRAMES, 60, 0, 2_000_000)],
1017 );
1018 assert_eq!(project.timeline_frames(), 210, "the captions hold it open");
1019 assert_eq!(project.media_frames(), FRAMES, "the pictures do not");
1020 assert_eq!(
1021 engine::export::planned_subtitles(&project, Format::Hevc, []),
1022 "S1 eng → embedded; S2 eng — past the last picture; cues past the last picture are cut \
1023 off there"
1024 );
1025
1026 let (out, tracks) = exported_want("lanes_tail", project, &[], 1);
1027 let cues = &tracks[0].cues;
1028 assert_eq!(cues.len(), 1, "the one cue the window holds: {cues:?}");
1029 near(cues[0].start_us, 4_500_000, "where the placement puts it");
1030 near(cues[0].end_us, 5_000_000, "cut off with the last picture");
1031
1032 // ...and the *file* is that long, which is what makes the sentence above
1033 // true rather than merely written: the picture stops with the media and the
1034 // 60 frames the caption hangs over it are not encoded black.
1035 let (written, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
1036 assert_eq!(
1037 written.frame_count, FRAMES,
1038 "the pictures end with the media, not with the caption"
1039 );
1040 // A count alone would pass on a file whose tail is black, so the last
1041 // picture is *looked at*: a padded frame is 16/128/128 and reads back at
1042 // YAVG 16. ffmpeg does the looking -- this file is HEVC and there is no
1043 // software HEVC decoder here to read it back with.
1044 match ffmpeg_last_luma(&out) {
1045 Some(luma) => assert!(
1046 luma > 20.0,
1047 "the last written picture is black (YAVG {luma:.2}): the walk ran past the media"
1048 ),
1049 None => println!("no ffmpeg on this box: the frame count is the only witness"),
1050 }
1051 // ...and the sound stops with the picture: the copied lane's trailing gap
1052 // is the same overhang, written as silence rather than as black.
1053 let duration_s = f64::from(written.frame_count) / written.frame_rate;
1054 match ffprobe_last_audio_pts(&out) {
1055 Some(pts) => assert!(
1056 pts <= duration_s,
1057 "the sound runs to {pts:.3} s, past the picture's {duration_s:.3} s"
1058 ),
1059 None => println!("no ffprobe on this box: the picture is the only witness"),
1060 }
1061 // The cue is inside the file it was clipped to, by the file's own clock.
1062 let duration_us = (duration_s * 1e6).round() as i64;
1063 assert!(
1064 cues[0].end_us <= duration_us + SLACK_US,
1065 "the cue ends at {} us, past the file's {duration_us} us",
1066 cues[0].end_us
1067 );
1068 std::fs::remove_file(&out).unwrap();
1069}
1070
1071/// The Matroska ceiling counts lanes as it counts picks: past `MAX_SUB_TRACKS` a
1072/// block could not number the track, so the card says so and the export refuses
1073/// by name and leaves no file.
1074#[test]
1075fn more_lanes_than_a_block_can_number_are_refused_by_name() {
1076 pin_software();
1077 let over = engine::mux::MAX_SUB_TRACKS + 1;
1078 let project = on_lanes(
1079 (0..over).map(|_| track()).collect(),
1080 &(0..over)
1081 .map(|i| (i, WHOLE.0, WHOLE.1, WHOLE.2, WHOLE.3))
1082 .collect::<Vec<_>>(),
1083 );
1084 let said = engine::export::planned_subtitles(&project, Format::Hevc, []);
1085 assert!(
1086 said.contains(&format!("{over} subtitle lanes"))
1087 && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)),
1088 "the card says how many were placed and how many fit: {said}"
1089 );
1090
1091 let out = out_path("lanes_ceiling");
1092 let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media");
1093 let handle = engine::export::start(
1094 project,
1095 meta,
1096 &out,
1097 &ExportSettings {
1098 format: Format::Hevc,
1099 ..Default::default()
1100 },
1101 None,
1102 );
1103 let said = wait(&handle, Duration::from_secs(1800))
1104 .expect_err("a file that cannot be numbered is not written")
1105 .to_string();
1106 assert!(
1107 said.contains(&format!("{over} subtitle tracks"))
1108 && said.contains(&format!("at most {}", engine::mux::MAX_SUB_TRACKS)),
1109 "the muxer refuses it again, in its own words: {said}"
1110 );
1111 assert!(!out.exists(), "and no half-written file is left: {said}");
1112}