forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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