forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

subtitles.rs1553 lines, 58.6 KiBHistoryRawDownload
1//! Subtitles: the cues of a file beside the media and of a track inside it are
2//! the same cues, a project keeps them across a save, and a track that is
3//! pictures rather than text is read as pictures rather than listed and
4//! skipped.
5//!
6//! ```text
7//! cargo test -p engine --release --test subtitles -- --nocapture
8//! ```
9
10use std::path::PathBuf;
11
12use engine::project::{Edge, Lane, LaneKind, SubClip};
13use engine::scratch::Scratch;
14use engine::subtitle::{self, Cue, SubtitleTrack};
15
16fn asset(name: &str) -> PathBuf {
17 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
18 .join("../../assets")
19 .join(name)
20}
21
22fn data(name: &str) -> PathBuf {
23 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
24 .join("tests/data")
25 .join(name)
26}
27
28fn scratch(name: &str) -> Scratch {
29 Scratch::dir(&format!("ve_subs_{name}"))
30}
31
32/// The three cues both hand-written fixtures hold, with the markup resolved:
33/// the italics of the `.ass` third line are not text, and the `\N` of its
34/// second one is a line break like the `.srt`'s.
35fn expected() -> Vec<Cue> {
36 vec![
37 Cue {
38 start_us: 500_000,
39 end_us: 1_500_000,
40 text: "first line".into(),
41 image: None,
42 words: Vec::new(),
43 karaoke: Vec::new(),
44 },
45 Cue {
46 start_us: 2_000_000,
47 end_us: 3_250_000,
48 text: "second line\nwith a break".into(),
49 image: None,
50 words: Vec::new(),
51 karaoke: Vec::new(),
52 },
53 Cue {
54 start_us: 4_000_000,
55 end_us: 4_750_000,
56 text: "third line".into(),
57 image: None,
58 words: Vec::new(),
59 karaoke: Vec::new(),
60 },
61 ]
62}
63
64/// The whole of the parse half: four routes to the same three cues -- an
65/// `.srt`, an `.ass` with override tags in it, and the two tracks of the
66/// Matroska file both were muxed into, whose timing lives on the block and
67/// whose text lives in it.
68#[test]
69fn a_file_beside_the_media_and_a_track_inside_it_read_the_same() {
70 let srt = subtitle::open(&data("test_subs.srt"), None);
71 assert_eq!(srt.refused, None, "the .srt parses");
72 assert_eq!(srt.cues, expected());
73 assert_eq!(srt.label, "test_subs.srt");
74
75 let ass = subtitle::open(&data("test_subs.ass"), None);
76 assert_eq!(ass.refused, None, "the .ass parses");
77 assert_eq!(ass.cues, expected(), "the override tags are resolved");
78
79 let embedded = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked");
80 let text: Vec<_> = embedded.iter().map(|t| (&t.label, &t.cues)).collect();
81 assert_eq!(embedded.len(), 2, "two subtitle tracks: {text:?}");
82 for track in &embedded {
83 assert_eq!(track.refused, None, "{} parses", track.label);
84 assert_eq!(
85 track.cues,
86 expected(),
87 "{} holds the same cues",
88 track.label
89 );
90 }
91 // ...and each is named by what the file says about it, so a list has
92 // something to show but the track number.
93 assert_eq!(embedded[0].label, "eng");
94 assert_eq!(embedded[1].label, "fra — Signs");
95 assert_eq!(embedded[0].track, Some(2));
96 assert_eq!(embedded[1].track, Some(3));
97
98 // The one door a saved line comes back through reaches the same track.
99 let one = subtitle::open(&asset("test_subs.mkv"), Some(3));
100 assert_eq!(one.cues, expected());
101 // A track number the file does not have is refused by name, not an error:
102 // the project it was saved in still opens.
103 let gone = subtitle::open(&asset("test_subs.mkv"), Some(9));
104 assert!(
105 gone.refused.as_deref().unwrap_or_default().contains("9"),
106 "{:?}",
107 gone.refused
108 );
109}
110
111/// The whole of the bitmap half on a file small enough to read in one screen:
112/// four PGS tracks, the first of them carrying one picture and the disc's own
113/// "take it off again" after it. A row per track, cues on the one with blocks,
114/// and the picture decodes to the pixels the display set describes.
115///
116/// Written here rather than muxed by the fixture script because ffmpeg cannot
117/// encode text subtitles into pictures; the bytes below are that Matroska file.
118#[test]
119fn a_pgs_track_is_read_as_pictures_and_the_erase_after_one_ends_it() {
120 let dir = scratch("pgs");
121 let file = dir.join("remux.mkv");
122 std::fs::write(&file, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv");
123
124 let tracks = subtitle::of_matroska(&file).expect("the walk does not fail over them");
125 assert_eq!(tracks.len(), 4, "every PGS track is listed");
126 for (i, track) in tracks.iter().enumerate() {
127 assert_eq!(track.track, Some(i as u64 + 1));
128 assert_eq!(track.refused, None, "a PGS track is read, not refused");
129 }
130 // The language is what a list shows, and `und` is what the spec says a
131 // track that names none is.
132 assert_eq!(tracks[0].label, "eng");
133 assert_eq!(tracks[3].label, "und");
134 // The three tracks with no blocks are tracks with no cues -- and still
135 // tracks of pictures, because that is the codec and not a count: one whose
136 // every display set is an erase would otherwise pass for text, and an
137 // export would promise to write words it has none of.
138 for track in &tracks[1..] {
139 assert_eq!(track.cues, Vec::new());
140 assert!(track.is_bitmap(), "a PGS track with no cue is still PGS");
141 }
142
143 // Two blocks, one cue: the second composes no object, which is the disc
144 // clearing the screen, and that is where the first one ends. `BlockDuration`
145 // says nothing here, exactly as it says zero on a real remux.
146 let track = &tracks[0];
147 assert!(track.is_bitmap(), "its cues are pictures");
148 assert_eq!(track.cues.len(), 1, "the erase is not a cue of its own");
149 let cue = &track.cues[0];
150 assert_eq!((cue.start_us, cue.end_us), (500_000, 2_000_000));
151 assert_eq!(cue.text, "", "a picture has no words");
152
153 let image = cue.image.as_ref().expect("the cue is a picture");
154 assert_eq!(
155 (image.width, image.height),
156 (8, 4),
157 "the canvas is the disc's frame, not the object's box"
158 );
159 let rgba = image.rgba().expect("the display set decodes");
160 assert_eq!(rgba.len(), 8 * 4 * 4);
161 // A 2x2 white square at (1, 1) on an otherwise transparent canvas: opaque
162 // where the object is, and nothing anywhere else.
163 let at = |x: usize, y: usize| rgba[(y * 8 + x) * 4..(y * 8 + x) * 4 + 4].to_vec();
164 assert_eq!(at(1, 1), vec![235, 235, 235, 255]);
165 assert_eq!(at(2, 2), vec![235, 235, 235, 255]);
166 assert_eq!(at(0, 0), vec![0, 0, 0, 0]);
167 assert_eq!(at(3, 1), vec![0, 0, 0, 0], "and no wider than it is");
168 assert_eq!(
169 rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count(),
170 4,
171 "four painted pixels and no more"
172 );
173}
174
175/// The muxer that packs a display set and the erase after it into one block:
176/// the cue is still the picture. The sup handed to the decoder stops at the end
177/// of the first set that composes something, and without that cut the erase is
178/// the last word and the cue decodes to a canvas with nothing on it.
179#[test]
180fn a_block_holding_the_erase_after_the_picture_still_draws_the_picture() {
181 let dir = scratch("pgs_packed");
182 let file = dir.join("packed.mkv");
183 let packed = [pgs_display_set(), pgs_erase()].concat();
184 std::fs::write(&file, pgs_matroska(packed)).expect("write the hand-made mkv");
185
186 let tracks = subtitle::of_matroska(&file).expect("the walk");
187 let cue = &tracks[0].cues[0];
188 let image = cue
189 .image
190 .as_ref()
191 .expect("the packed block is still a picture");
192 assert_eq!((image.width, image.height), (8, 4));
193 let rgba = image.rgba().expect("it decodes");
194 assert_eq!(
195 rgba.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).count(),
196 4,
197 "the picture, not the erase written after it"
198 );
199}
200
201/// The film that reported the bug: four PGS tracks beside one `S_TEXT/UTF8`
202/// one, none of them refused any more. Skipped where the file is not -- it is
203/// a 4K remux named by the local `real_library.toml`, not in this repository.
204#[test]
205fn the_remux_that_reported_the_bug_reads_all_five_of_its_tracks() {
206 let Some(film) = engine::real_library::film("hevc_4k_pgs") else {
207 return;
208 };
209 let tracks = subtitle::of_matroska(&film).expect("the walk");
210 assert_eq!(tracks.len(), 5);
211 assert!(
212 tracks.iter().all(|t| t.refused.is_none()),
213 "every row is one a click can pick: {:?}",
214 tracks.iter().map(|t| &t.refused).collect::<Vec<_>>()
215 );
216 // One text track and four of pictures, which is what the remux carries.
217 let bitmap: Vec<_> = tracks.iter().filter(|t| t.is_bitmap()).collect();
218 assert_eq!(bitmap.len(), 4);
219 for track in &bitmap {
220 assert!(
221 track.cues.len() > 100,
222 "{} — {} cues",
223 track.label,
224 track.cues.len()
225 );
226 let cue = &track.cues[0];
227 let image = cue.image.as_ref().expect("a picture cue");
228 assert_eq!(
229 (image.width, image.height),
230 (1920, 1080),
231 "the BluRay canvas"
232 );
233 assert!(cue.end_us > cue.start_us, "a cue that is up for a while");
234 let rgba = image.rgba().expect("the first display set decodes");
235 assert_eq!(rgba.len(), 1920 * 1080 * 4);
236 assert!(
237 rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 0),
238 "{} — the first cue paints something",
239 track.label
240 );
241 }
242}
243
244/// A saved project comes back with its subtitles: the `.edith` names the file
245/// and the track, and the cues are read out of them again on the way in. The
246/// engine's own door for both halves -- import, save, open -- since that is
247/// what a front-end will drive.
248#[test]
249fn a_project_keeps_its_subtitles_across_a_save() {
250 let dir = scratch("save");
251 let media = dir.join("test_av.mp4");
252 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
253 // Beside the media, which is where a subtitle file lives: the project then
254 // writes it relative, and the whole folder stays movable.
255 let subs = dir.join("test_subs.srt");
256 std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture");
257
258 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
259 session.set_gain(0.0); // silent like the rest of the suites
260 assert_eq!(session.subtitles().len(), 0, "nothing to start with");
261 assert_eq!(
262 session.import_subtitles(&subs).expect("the .srt imports"),
263 1
264 );
265 // The same file twice is the same subtitles, not two rows of them.
266 assert_eq!(session.import_subtitles(&subs).expect("no error"), 0);
267 assert_eq!(session.subtitles()[0].cues, expected());
268
269 let project = dir.join("cut.edith");
270 session.save_project(&project).expect("save");
271 let text = std::fs::read_to_string(&project).expect("read the project back");
272 assert!(text.starts_with("edith 30\n"), "{text}");
273 assert!(
274 text.contains("\nsubtitle - test_subs.srt\n"),
275 "the reference is written relative, and no cue is: {text}"
276 );
277
278 let back = engine::PlaybackSession::open_project(&project).expect("open the project");
279 assert_eq!(back.subtitles().len(), 1);
280 assert_eq!(back.subtitles()[0].cues, expected());
281 assert_eq!(back.subtitles()[0].track, None);
282 drop(back);
283
284 // A subtitle file that has gone missing is listed, refused by name, and
285 // written out again: the project still opens and the row is not lost.
286 std::fs::remove_file(&subs).expect("take the subtitles away");
287 let gone = engine::PlaybackSession::open_project(&project).expect("the project still opens");
288 assert_eq!(gone.subtitles().len(), 1);
289 assert!(gone.subtitles()[0].refused.is_some());
290 let again = dir.join("cut2.edith");
291 gone.save_project(&again).expect("save again");
292 assert!(
293 std::fs::read_to_string(&again)
294 .expect("read")
295 .contains("\nsubtitle - test_subs.srt\n"),
296 "a re-save keeps the row"
297 );
298}
299
300/// The two-door import: the parse runs with no session in hand -- which is what
301/// lets a front-end run it off the render thread -- and the tracks it hands back
302/// go on the timeline for the cost of a push. Same dedupe as the one-call door,
303/// so the same file twice is still one set of rows, and what lands is saved and
304/// loaded as a reference exactly like an `import_subtitles` row.
305#[test]
306fn parsed_tracks_can_be_handed_to_a_session_without_it_reading_the_file() {
307 let dir = scratch("handoff");
308 let media = dir.join("test_av.mp4");
309 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
310 let mkv = dir.join("test_subs.mkv");
311 std::fs::copy(asset("test_subs.mkv"), &mkv).expect("copy the subtitle fixture");
312
313 // The door a background executor calls: no `&self`, so nothing about the
314 // session is borrowed while the container is walked.
315 let tracks =
316 engine::PlaybackSession::parse_subtitles(&mkv).expect("the mkv is walked off-thread");
317 assert_eq!(tracks.len(), 2, "both tracks of the fixture");
318 // Owned data all the way down, so the parse may run on a background task
319 // and its result be sent back: a track holding a handle would put the walk
320 // back on the thread that draws.
321 fn sendable<T: Send + 'static>(_: &T) {}
322 sendable(&tracks);
323
324 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
325 session.set_gain(0.0);
326 assert_eq!(session.add_subtitle_tracks(tracks.clone()), 2, "both go on");
327 // The same tracks again are the same subtitles: the (path, track) dedupe is
328 // what a front-end's "already on the timeline" line falls out of.
329 assert_eq!(session.add_subtitle_tracks(tracks), 0, "and no repeat rows");
330 assert_eq!(session.subtitles().len(), 2);
331 // And the one-call door agrees with it, over the very same file.
332 assert_eq!(session.import_subtitles(&mkv).expect("no error"), 0);
333 assert_eq!(session.subtitles()[0].cues, expected());
334
335 let project = dir.join("cut.edith");
336 session.save_project(&project).expect("save");
337 let back = engine::PlaybackSession::open_project(&project).expect("open the project");
338 assert_eq!(
339 back.subtitles().iter().map(|t| t.track).collect::<Vec<_>>(),
340 session
341 .subtitles()
342 .iter()
343 .map(|t| t.track)
344 .collect::<Vec<_>>(),
345 "a handed-over row is a reference like any other"
346 );
347 assert_eq!(back.subtitles()[1].cues, expected());
348}
349
350/// Whatever an import added comes back off: three tracks go on, the middle one
351/// is removed, and what is left is the other two *in the order they were added*
352/// -- a save then writes exactly those two references and a load reads back
353/// exactly them. The bad index is a refusal naming the index, not a silent
354/// no-op, since a front-end holding a stale row has picked the wrong one.
355#[test]
356fn a_subtitle_row_can_be_removed_and_the_survivors_round_trip() {
357 let dir = scratch("remove");
358 let media = dir.join("test_av.mp4");
359 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
360 // Three files rather than three tracks of one: `add_subtitles` dedupes by
361 // (path, track), so three names are three rows.
362 for name in ["a.srt", "b.srt", "c.srt"] {
363 std::fs::copy(data("test_subs.srt"), dir.join(name)).expect("copy the subtitle fixture");
364 }
365
366 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
367 session.set_gain(0.0);
368 for name in ["a.srt", "b.srt", "c.srt"] {
369 assert_eq!(
370 session
371 .import_subtitles(&dir.join(name))
372 .expect("the .srt imports"),
373 1
374 );
375 }
376 assert_eq!(session.subtitles().len(), 3);
377
378 session.remove_subtitles(1).expect("the middle row goes");
379 let names: Vec<String> = session
380 .subtitles()
381 .iter()
382 .map(|t| {
383 t.path
384 .file_name()
385 .expect("a name")
386 .to_string_lossy()
387 .into_owned()
388 })
389 .collect();
390 assert_eq!(
391 names,
392 vec!["a.srt", "c.srt"],
393 "the survivors keep their order"
394 );
395 assert_eq!(session.subtitles()[0].cues, expected(), "and their cues");
396
397 let project = dir.join("cut.edith");
398 session.save_project(&project).expect("save");
399 let text = std::fs::read_to_string(&project).expect("read the project back");
400 assert!(
401 text.contains("\nsubtitle - a.srt\n") && text.contains("\nsubtitle - c.srt\n"),
402 "the survivors are written, by reference: {text}"
403 );
404 assert!(
405 !text.contains("b.srt"),
406 "and the removed one is not: {text}"
407 );
408
409 let back = engine::PlaybackSession::open_project(&project).expect("open the project");
410 assert_eq!(
411 back.subtitles()
412 .iter()
413 .map(|t| t
414 .path
415 .file_name()
416 .expect("a name")
417 .to_string_lossy()
418 .into_owned())
419 .collect::<Vec<_>>(),
420 vec!["a.srt", "c.srt"],
421 "and a load is the same two, in the same order"
422 );
423 assert_eq!(back.subtitles()[1].cues, expected());
424
425 // A row that is not there says so, naming the index a front-end passed.
426 let why = session
427 .remove_subtitles(9)
428 .expect_err("there is no row 9")
429 .to_string();
430 assert!(why.contains('9') && why.contains("subtitle"), "{why}");
431 assert_eq!(session.subtitles().len(), 2, "and nothing moved");
432}
433
434/// The whole point of the add-subtitles door: another release's subtitle
435/// tracks go onto the timeline that is already open, and the file they came out
436/// of joins *nothing* -- no source row, no lane, no clip. Nobody has to import a
437/// second copy of a film, or break the edit they have, to get its subtitles.
438///
439/// And a file the walk found no subtitle track in is refused as that, in words,
440/// rather than counted as zero: zero added is what a file whose tracks are here
441/// already answers, and the two are opposite instructions to the person reading
442/// them.
443#[test]
444fn subtitles_come_off_another_file_without_it_joining_the_timeline() {
445 let media = asset("test_av.mp4");
446 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
447 session.set_gain(0.0);
448 let sources: Vec<_> = session.sources().iter().map(|s| s.path.clone()).collect();
449 let lanes = session.lanes();
450 let clips: Vec<_> = lanes.iter().map(|&l| session.lane_clips(l).len()).collect();
451 assert_eq!(sources.len(), 1, "one file is open");
452
453 // A different file entirely, carrying two subtitle tracks.
454 let other = asset("test_subs.mkv");
455 assert_eq!(
456 session
457 .import_subtitles(&other)
458 .expect("its subtitles come"),
459 2
460 );
461 assert_eq!(session.subtitles().len(), 2);
462 for track in session.subtitles() {
463 assert_eq!(track.path, other, "the rows name the file they came out of");
464 assert!(!track.cues.is_empty(), "with their cues read");
465 }
466 // ...and the timeline is exactly the timeline it was.
467 assert_eq!(
468 session
469 .sources()
470 .iter()
471 .map(|s| s.path.clone())
472 .collect::<Vec<_>>(),
473 sources,
474 "the file whose subtitles these are did not join the library"
475 );
476 assert_eq!(session.lanes(), lanes, "no lane was added");
477 assert_eq!(
478 session
479 .lanes()
480 .iter()
481 .map(|&l| session.lane_clips(l).len())
482 .collect::<Vec<_>>(),
483 clips,
484 "and nothing was cut, moved or dropped on one"
485 );
486
487 // The same file again is the same two tracks, not four.
488 assert_eq!(session.import_subtitles(&other).expect("no error"), 0);
489 assert_eq!(session.subtitles().len(), 2);
490
491 // A container walked and carrying none says so, naming the file -- and the
492 // claim is only made after the walk looked.
493 let why = session
494 .import_subtitles(&media)
495 .expect_err("the fixture carries no subtitle track")
496 .to_string();
497 assert!(
498 why.contains("no subtitle tracks in") && why.contains("test_av.mp4"),
499 "{why}"
500 );
501 assert_eq!(session.subtitles().len(), 2, "and nothing changed over it");
502}
503
504/// A bitmap track survives a save the same way a text one does, and for the
505/// same reason: a `.edith` holds the file and the track number, never a cue, so
506/// what comes back is what the file still says. The pictures are read out of
507/// the remux again on the way in -- thirty megabytes a track is exactly what a
508/// project file is not for.
509#[test]
510fn a_project_keeps_a_bitmap_track_as_a_reference_and_reads_its_pictures_back() {
511 let dir = scratch("save_pgs");
512 let media = dir.join("test_av.mp4");
513 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
514 let remux = dir.join("remux.mkv");
515 std::fs::write(&remux, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv");
516
517 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
518 session.set_gain(0.0);
519 assert_eq!(
520 session.import_subtitles(&remux).expect("the remux imports"),
521 4,
522 "one row per PGS track"
523 );
524 assert!(session.subtitles()[0].is_bitmap());
525 // An mkv export writes a *text* track and these cues are pictures, so the
526 // card says so before the button rather than the file coming out short.
527 // The same `is_bitmap` is what makes `export_subtitles` write none.
528 let planned = session.planned_subtitles(engine::export::Format::Hevc, Some(0));
529 assert!(
530 planned.contains("pictures") && planned.contains("not written"),
531 "{planned}"
532 );
533
534 let project = dir.join("cut.edith");
535 session.save_project(&project).expect("save");
536 let text = std::fs::read_to_string(&project).expect("read the project back");
537 assert!(
538 text.contains("\nsubtitle 1 remux.mkv\n"),
539 "the track is a reference and no picture is written: {text}"
540 );
541
542 let back = engine::PlaybackSession::open_project(&project).expect("open the project");
543 assert_eq!(back.subtitles().len(), 4);
544 let track = &back.subtitles()[0];
545 assert_eq!(track.refused, None);
546 assert!(track.is_bitmap(), "and it comes back as pictures");
547 assert_eq!(track.cues.len(), 1);
548 let image = track.cues[0].image.as_ref().expect("the picture is back");
549 assert_eq!((image.width, image.height), (8, 4));
550 assert_eq!(image.rgba().expect("it decodes").len(), 8 * 4 * 4);
551
552 // Each row is the track it was saved as, in the order it was saved in: what
553 // a click picks is a place in this list, so a load that reordered the rows
554 // would repoint the picked track without saying anything. A re-save writing
555 // the same bytes is that order proved from both ends.
556 assert_eq!(
557 back.subtitles().iter().map(|t| t.track).collect::<Vec<_>>(),
558 vec![Some(1), Some(2), Some(3), Some(4)]
559 );
560 let again = dir.join("cut2.edith");
561 back.save_project(&again).expect("save again");
562 assert_eq!(
563 std::fs::read(&again).expect("read"),
564 std::fs::read(&project).expect("read"),
565 "a save, a load and a save again are the same file"
566 );
567}
568
569/// Bytes the calling thread has asked the kernel for so far, which is what a
570/// walk of a Matroska file costs and a page cache cannot hide: `rchar` counts
571/// what `read` handed back, warm or cold. It is per thread, not per process,
572/// so the other tests of this binary running in parallel do not count here;
573/// the walks measured are synchronous calls on the test's own thread.
574fn read_bytes() -> u64 {
575 let io = std::fs::read_to_string("/proc/thread-self/io")
576 .expect("Linux, like the rest of this suite");
577 io.lines()
578 .find_map(|l| l.strip_prefix("rchar: "))
579 .expect("rchar")
580 .trim()
581 .parse()
582 .expect("a number")
583}
584
585/// A project naming four tracks of one file walks that file *once*, and hands
586/// the rows back in the order they were saved in.
587///
588/// The order is the invariant with teeth: a subtitle is picked by its place in
589/// this list, so a reader that grouped the rows by file and handed them back
590/// grouped would silently repoint what the user had picked. And the walk count
591/// is the reason the grouping exists at all -- a saved film with thirty-five
592/// tracks was thirty-five walks of a 25 GB file with the window stopped.
593#[test]
594fn a_project_naming_many_tracks_of_one_file_walks_it_once_and_keeps_its_order() {
595 let dir = scratch("one_walk");
596 let media = dir.join("test_av.mp4");
597 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
598 let remux = dir.join("remux.mkv");
599 std::fs::write(&remux, pgs_matroska(pgs_display_set())).expect("write the hand-made mkv");
600 let subs = dir.join("test_subs.srt");
601 std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture");
602
603 // One walk, for the measurement below to be compared against.
604 let before = read_bytes();
605 let all = subtitle::of_matroska(&remux).expect("the walk");
606 let one_walk = read_bytes() - before;
607 assert_eq!(all.len(), 4);
608 assert!(one_walk > 0, "a walk reads something");
609
610 // The rows a `.edith` holds, deliberately out of file order and with the
611 // standalone file in the middle of them.
612 let rows: Vec<(PathBuf, Option<u64>)> = vec![
613 (remux.clone(), Some(3)),
614 (remux.clone(), Some(1)),
615 (subs.clone(), None),
616 (remux.clone(), Some(4)),
617 (remux.clone(), Some(2)),
618 (remux.clone(), Some(9)), // gone: refused by name, still a row
619 ];
620 let before = read_bytes();
621 let opened = subtitle::open_all(&rows);
622 let cost = read_bytes() - before;
623 assert_eq!(
624 opened
625 .iter()
626 .map(|t| (&t.path, t.track))
627 .collect::<Vec<_>>(),
628 rows.iter().map(|(p, n)| (p, *n)).collect::<Vec<_>>(),
629 "every row comes back where it was saved"
630 );
631 assert_eq!(opened[1].label, "eng", "and it is that file's track 1");
632 assert_eq!(
633 opened[2].cues,
634 expected(),
635 "the standalone row is untouched"
636 );
637 assert!(
638 opened[5]
639 .refused
640 .as_deref()
641 .unwrap_or_default()
642 .contains("no subtitle track 9"),
643 "{:?}",
644 opened[5].refused
645 );
646 assert!(
647 cost < one_walk * 2,
648 "four rows of one file is one walk of it: {cost} bytes read against {one_walk} for a walk"
649 );
650}
651
652/// A refusal a front-end shows at the moment of the import, rather than a row
653/// nobody asked for: a file that is not a subtitle format at all.
654#[test]
655fn importing_something_that_is_not_a_subtitle_says_so() {
656 let dir = scratch("refuse");
657 let media = dir.join("test_av.mp4");
658 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
659 let notes = dir.join("notes.txt");
660 std::fs::write(&notes, "not a subtitle").expect("write");
661
662 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
663 session.set_gain(0.0);
664 let err = session
665 .import_subtitles(&notes)
666 .expect_err("a .txt is not a subtitle")
667 .to_string();
668 assert!(err.contains("txt"), "{err}");
669 assert_eq!(session.subtitles().len(), 0, "and nothing was added");
670}
671
672/// The Matroska that is the subtitles alone: `.mks`, what a subtitle release
673/// ships beside the film, imported by the door an `.mkv` is imported by.
674///
675/// The refusal it used to get -- *"mks" is not a subtitle format this reads* --
676/// was a claim about a container this very binary parses: the bytes are a
677/// Matroska's and the same walk reads them, so only the extension list said no.
678#[test]
679fn a_matroska_that_is_the_subtitles_alone_imports_like_any_other() {
680 let dir = scratch("mks");
681 let media = dir.join("test_av.mp4");
682 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
683
684 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
685 session.set_gain(0.0);
686 let added = session
687 .import_subtitles(&asset("test_subs.mks"))
688 .expect("a .mks is a Matroska and imports as one");
689 assert_eq!(added, 2, "both its tracks came in");
690 let labels: Vec<&str> = session.subtitles().iter().map(|t| &*t.label).collect();
691 assert_eq!(labels, ["eng", "fra — Signs"], "with their own names");
692 for track in session.subtitles() {
693 assert_eq!(track.refused, None, "{} parses", track.label);
694 assert_eq!(track.cues, expected(), "{} holds the cues", track.label);
695 }
696}
697
698/// A track that states its language the way a modern muxer states it --
699/// `LanguageBCP47` and no legacy `Language` element at all -- keeps that
700/// language, where it used to come in as `und`.
701///
702/// The shape of every English track of one real 4K web remux and all four
703/// of another film's: they read as `und` while the file said `en`,
704/// and the loss survived into the exported file's track list.
705#[test]
706fn a_track_that_states_its_language_the_modern_way_keeps_it() {
707 // The fixture is what it claims to be: the modern element is in it and the
708 // legacy one is not, so what is being read is the new element and not a
709 // leftover of the old one.
710 let bytes = std::fs::read(asset("test_subs_bcp47.mkv")).expect("the fixture is there");
711 assert!(
712 bytes.windows(3).any(|w| w == [0x22, 0xB5, 0x9D]),
713 "the fixture states LanguageBCP47"
714 );
715 for legacy in [b"\x22\xb5\x9c\x83eng".as_slice(), b"\x22\xb5\x9c\x83fra"] {
716 assert!(
717 !bytes.windows(legacy.len()).any(|w| w == legacy),
718 "and states no legacy Language element for its subtitle tracks"
719 );
720 }
721
722 let tracks = subtitle::of_matroska(&asset("test_subs_bcp47.mkv")).expect("the mkv is walked");
723 let languages: Vec<&str> = tracks.iter().map(|t| &*t.language).collect();
724 assert_eq!(languages, ["eng", "fra"], "`en` is English, `fr` is French");
725 // ...and the same file with the legacy element reads exactly the same, which
726 // is the point: which element a muxer chose is not something a row shows.
727 let legacy = subtitle::of_matroska(&asset("test_subs.mkv")).expect("the mkv is walked");
728 let want: Vec<&str> = legacy.iter().map(|t| &*t.label).collect();
729 let got: Vec<&str> = tracks.iter().map(|t| &*t.label).collect();
730 assert_eq!(got, want, "the two files list the same two tracks");
731}
732
733/// The frame rate every placement test below counts in: at 30 fps a frame is
734/// 33333 microseconds and a second is 30 frames exactly, so a window and a span
735/// can be read against each other by eye.
736const LANE_FPS: f64 = 30.0;
737/// Never opened -- a `Project` is pure data ([`engine::Project::single`] reads
738/// no file), so a path that is not there simply dedups by spelling.
739const FILE: &str = "/nonexistent/subs.mp4";
740
741/// A project with the three-cue `.srt` on its palette and one empty subtitle
742/// lane: `V1`, `A1`, `S1`, which is the state a `+ S` press leaves.
743fn with_subtitle_lane() -> (engine::Project, Lane) {
744 let mut project = engine::Project::single(FILE, 150);
745 assert!(
746 project.add_subtitles(&subtitle::open(&data("test_subs.srt"), None)),
747 "the palette takes the track"
748 );
749 let lane = project.add_lane(LaneKind::Subtitle);
750 assert_eq!(lane, Lane::S1, "the first subtitle lane is S1");
751 assert_eq!(lane.label(), "S1", "and is written S1");
752 (project, lane)
753}
754
755/// A placement of the whole of palette track 0, five seconds of it.
756fn whole(track: usize) -> SubClip {
757 SubClip {
758 start: 0,
759 frames: 150,
760 track,
761 in_us: 0,
762 out_us: 5_000_000,
763 link: None,
764 }
765}
766
767/// The lane half of the model: a caption is placed, trimmed at either end,
768/// moved and taken back -- all of it through the machinery a clip already goes
769/// through, so an undo is the lane snapshot every other edit pushes.
770#[test]
771fn a_caption_is_placed_trimmed_moved_and_undone_on_its_lane() {
772 let (mut project, lane) = with_subtitle_lane();
773 project.place_sub(lane, 30, whole(0)).expect("it goes down");
774 assert_eq!(
775 project.sub_lane(lane),
776 [SubClip {
777 start: 30,
778 ..whole(0)
779 }],
780 "placed where it was asked for, window untouched"
781 );
782
783 // The tail in: fewer frames, and the window loses exactly the seconds the
784 // frames did (90 frames of 30 fps is 3s, so [0, 2s) is what is left).
785 project
786 .trim_sub(lane, 0, Edge::End, 90, LANE_FPS)
787 .expect("the tail comes in");
788 assert_eq!(
789 project.sub_lane(lane)[0],
790 SubClip {
791 start: 30,
792 frames: 60,
793 track: 0,
794 in_us: 0,
795 out_us: 2_000_000,
796 link: None,
797 }
798 );
799
800 // ...and the head, which moves the window's *start* with it: the words that
801 // stay are the words that were there.
802 project
803 .trim_sub(lane, 0, Edge::Start, 45, LANE_FPS)
804 .expect("the head comes in");
805 assert_eq!(
806 project.sub_lane(lane)[0],
807 SubClip {
808 start: 45,
809 frames: 45,
810 track: 0,
811 in_us: 500_000,
812 out_us: 2_000_000,
813 link: None,
814 }
815 );
816
817 // A move is `start` and nothing else -- the same words, later.
818 project
819 .move_sub(lane, 0, lane, 300)
820 .expect("it slides down the lane");
821 assert_eq!(
822 project.sub_lane(lane)[0],
823 SubClip {
824 start: 300,
825 frames: 45,
826 track: 0,
827 in_us: 500_000,
828 out_us: 2_000_000,
829 link: None,
830 }
831 );
832
833 // ...and onto another subtitle track, which is the same call: a drag across
834 // lanes is where a second caption row is *for*.
835 let s2 = project.add_lane(LaneKind::Subtitle);
836 project.move_sub(lane, 0, s2, 300).expect("it changes lane");
837 assert!(project.sub_lane(lane).is_empty(), "off the first row");
838 assert_eq!(project.sub_lane(s2).len(), 1, "and onto the second");
839 assert!(
840 project.undo() && project.undo(),
841 "the move and the added lane"
842 );
843
844 // Every one of the four was one undo step, and the snapshots are the lane
845 // list's own: subtitles joined the history without a history of their own.
846 for want in [
847 SubClip {
848 start: 45,
849 frames: 45,
850 track: 0,
851 in_us: 500_000,
852 out_us: 2_000_000,
853 link: None,
854 },
855 SubClip {
856 start: 30,
857 frames: 60,
858 track: 0,
859 in_us: 0,
860 out_us: 2_000_000,
861 link: None,
862 },
863 SubClip {
864 link: None,
865 start: 30,
866 ..whole(0)
867 },
868 ] {
869 assert!(project.undo(), "there is a step to walk back");
870 assert_eq!(project.sub_lane(lane)[0], want);
871 }
872 assert!(project.undo(), "and the placement itself");
873 assert!(
874 project.sub_lane(lane).is_empty(),
875 "which leaves the lane as it was added"
876 );
877}
878
879/// Two captions may not cover one frame of one lane, and every refusal says so
880/// in words -- the one place this model *differs* from
881/// [`engine::Project::place`], which overwrites what it lands on. A refusal
882/// costs no undo step.
883#[test]
884fn two_captions_may_not_cover_one_frame_and_the_refusal_says_which() {
885 let (mut project, lane) = with_subtitle_lane();
886 project
887 .place_sub(
888 lane,
889 30,
890 SubClip {
891 frames: 60,
892 ..whole(0)
893 },
894 )
895 .expect("the first goes down");
896 let err = project
897 .place_sub(
898 lane,
899 60,
900 SubClip {
901 frames: 60,
902 ..whole(0)
903 },
904 )
905 .expect_err("the second lands inside it");
906 assert!(
907 err.to_string().contains("already covers [30, 90)"),
908 "the refusal names the one in the way: {err}"
909 );
910
911 project
912 .place_sub(
913 lane,
914 200,
915 SubClip {
916 frames: 60,
917 ..whole(0)
918 },
919 )
920 .expect("clear of it, it goes down");
921 let err = project
922 .move_sub(lane, 0, lane, 150)
923 .expect_err("and a drag onto it is refused too");
924 assert!(
925 err.to_string().contains("already covers [200, 260)"),
926 "by the same words: {err}"
927 );
928
929 // Neither refusal moved anything, and neither cost a step: one undo takes
930 // the *second placement* back, not a refusal.
931 assert_eq!(
932 project
933 .sub_lane(lane)
934 .iter()
935 .map(|s| s.start)
936 .collect::<Vec<_>>(),
937 [30, 200]
938 );
939 assert!(project.undo());
940 assert_eq!(
941 project
942 .sub_lane(lane)
943 .iter()
944 .map(|s| s.start)
945 .collect::<Vec<_>>(),
946 [30]
947 );
948
949 // The other refusals of the door, each in its own words.
950 for (lane, at, sub, want) in [
951 (Lane::V1, 0, whole(0), "not a subtitle track"),
952 (
953 Lane::new(LaneKind::Subtitle, 4),
954 0,
955 whole(0),
956 "there is no S5",
957 ),
958 (
959 Lane::S1,
960 0,
961 SubClip {
962 frames: 0,
963 ..whole(0)
964 },
965 "is empty",
966 ),
967 (
968 Lane::S1,
969 0,
970 SubClip {
971 track: 7,
972 ..whole(0)
973 },
974 "subtitle track 7 of 1",
975 ),
976 ] {
977 let err = project.place_sub(lane, at, sub).expect_err("refused");
978 assert!(
979 err.to_string().contains(want),
980 "{want:?} is what it says, not {err:?}"
981 );
982 }
983}
984
985/// The mapping: what a lane *shows* is its placements' windows of their track,
986/// cut to the window and shifted to where the placement sits -- the twin of
987/// `export::timeline_cues` for a track that is placed rather than carried.
988#[test]
989fn a_lane_maps_to_cues_clipped_to_the_window_and_shifted_onto_the_timeline() {
990 let (mut project, lane) = with_subtitle_lane();
991 // Two seconds of the track, placed two seconds in: the first cue and no
992 // more -- the second starts at exactly 2s, which the half-open window ends
993 // at.
994 project
995 .place_sub(
996 lane,
997 60,
998 SubClip {
999 frames: 60,
1000 out_us: 2_000_000,
1001 ..whole(0)
1002 },
1003 )
1004 .expect("it goes down");
1005 let cues = project.sub_lane_cues(lane, LANE_FPS);
1006 assert_eq!(cues.len(), 1, "one cue is inside that window");
1007 assert_eq!(
1008 (cues[0].start_us, cues[0].end_us, &*cues[0].text),
1009 (2_500_000, 3_500_000, "first line"),
1010 "shifted by the two seconds the placement sits at"
1011 );
1012
1013 // A window that starts mid-cue keeps the half that is inside it, exactly as
1014 // a cut clip keeps the frames that are.
1015 project.undo();
1016 project
1017 .place_sub(
1018 lane,
1019 0,
1020 SubClip {
1021 frames: 60,
1022 in_us: 1_000_000,
1023 out_us: 3_000_000,
1024 ..whole(0)
1025 },
1026 )
1027 .expect("it goes down");
1028 let cues = project.sub_lane_cues(lane, LANE_FPS);
1029 assert_eq!(
1030 cues.iter()
1031 .map(|c| (c.start_us, c.end_us, c.text.clone()))
1032 .collect::<Vec<_>>(),
1033 [
1034 (0, 500_000, "first line".to_string()),
1035 (
1036 1_000_000,
1037 2_000_000,
1038 "second line\nwith a break".to_string()
1039 ),
1040 ],
1041 "both cues clipped to the window and shifted to the placement"
1042 );
1043
1044 // The palette row cannot be taken off under the placement that plays it --
1045 // the refusal names the lane and the frame it is at.
1046 let why = project
1047 .remove_subtitles(0)
1048 .expect_err("a placed row does not come off")
1049 .to_string();
1050 assert!(
1051 why.contains("S1 at frame 0") && why.contains("delete those clips first"),
1052 "the refusal names where it is placed: {why}"
1053 );
1054
1055 // A placement whose track is gone all the same -- a load that put a shorter
1056 // palette back, which is the only door left -- shows nothing, never another
1057 // track's words.
1058 let project = project.with_subtitles(Vec::new());
1059 assert!(
1060 project.sub_lane_cues(lane, LANE_FPS).is_empty(),
1061 "a placement with no track left shows nothing"
1062 );
1063 assert!(
1064 project.sub_lane_cues(lane, 0.0).is_empty(),
1065 "and a rate that is not a rate maps nothing"
1066 );
1067}
1068
1069/// A palette row taken off while *another* row is placed: the bug a
1070/// placement-that-names-an-index invites, and the rule
1071/// [`engine::Project::remove_source`] already follows -- the rows below the one
1072/// that went move down, so every clip that named one has to move with them or
1073/// it plays somebody else's words.
1074#[test]
1075fn a_removed_palette_row_walks_the_placements_below_it_down() {
1076 let mut project = engine::Project::single(FILE, 150);
1077 let base = subtitle::open(&data("test_subs.srt"), None);
1078 // Three rows of one file: `add_subtitles` dedupes by (path, track), so
1079 // three track numbers are three rows without three files.
1080 for (n, label) in [(0u64, "eng"), (1, "fra - Signs"), (2, "spa")] {
1081 assert!(
1082 project.add_subtitles(&SubtitleTrack {
1083 track: Some(n),
1084 label: label.into(),
1085 ..base.clone()
1086 }),
1087 "row {label} goes on the palette"
1088 );
1089 }
1090 let lane = project.add_lane(LaneKind::Subtitle);
1091 project
1092 .place_sub(lane, 30, whole(1))
1093 .expect("the middle row is placed");
1094 assert_eq!(
1095 project.subtitles()[project.sub_lane(lane)[0].track].label,
1096 "fra - Signs"
1097 );
1098
1099 // The row above it comes off -- nothing plays it -- and the placement is
1100 // walked down with the palette, so it still says the same words.
1101 project
1102 .remove_subtitles(0)
1103 .expect("an unplaced row comes off");
1104 assert_eq!(
1105 project
1106 .subtitles()
1107 .iter()
1108 .map(|t| &*t.label)
1109 .collect::<Vec<_>>(),
1110 ["fra - Signs", "spa"],
1111 "the survivors keep their order"
1112 );
1113 assert_eq!(
1114 project.sub_lane(lane)[0].track,
1115 0,
1116 "the placement moved down"
1117 );
1118 assert_eq!(
1119 project.subtitles()[project.sub_lane(lane)[0].track].label,
1120 "fra - Signs",
1121 "and names the very track it named before"
1122 );
1123
1124 // The history went with it -- and it *can*, now that the entry carries the
1125 // palette ([`Snapshot`]'s own `subtitles`, beside the lanes and the
1126 // settings): the reindex is a step like any other, so an undo puts the row
1127 // and the placement's own index back together and the same clip goes on
1128 // naming the same words.
1129 assert!(
1130 project.undo(),
1131 "a reindex the entry carries is a step; the history was thrown away instead"
1132 );
1133 assert_eq!(
1134 project
1135 .subtitles()
1136 .iter()
1137 .map(|t| &*t.label)
1138 .collect::<Vec<_>>(),
1139 ["eng", "fra - Signs", "spa"],
1140 "the undo did not put the removed row back"
1141 );
1142 assert_eq!(
1143 project.subtitles()[project.sub_lane(lane)[0].track].label,
1144 "fra - Signs",
1145 "and the placement names the very track it named before the removal"
1146 );
1147 // ...and the step again, which is where the rest of this test starts: the
1148 // row off and the placement walked down with it (`undo` left it on the
1149 // redo stack).
1150 assert!(project.redo(), "the step is a step both ways");
1151 assert_eq!(
1152 project.sub_lane(lane)[0].track,
1153 0,
1154 "the placement moved down again"
1155 );
1156
1157 // ...and now that it *is* placed, the same row does not come off at all:
1158 // the refusal names the lane, the frame, and the way out.
1159 let why = project
1160 .remove_subtitles(0)
1161 .expect_err("a placed row stays")
1162 .to_string();
1163 assert!(
1164 why.contains("fra - Signs") && why.contains("S1 at frame 30"),
1165 "the refusal names the row and where it plays: {why}"
1166 );
1167 assert_eq!(project.subtitles().len(), 2, "and nothing came off");
1168}
1169
1170/// A drag that changes nothing is not a mistake to report: a caption picked up
1171/// and put back down, and an edge pulled past a wall it already stands against,
1172/// both come back `Ok` and cost no undo step -- a front-end shows every `Err`
1173/// as a notice, and neither of these two is worth one.
1174#[test]
1175fn a_drag_that_changes_nothing_is_ok_and_costs_no_step() {
1176 let (mut project, lane) = with_subtitle_lane();
1177 project
1178 .place_sub(
1179 lane,
1180 30,
1181 SubClip {
1182 frames: 60,
1183 ..whole(0)
1184 },
1185 )
1186 .expect("it goes down");
1187 let placed = project.sub_lane(lane)[0];
1188
1189 project
1190 .move_sub(lane, 0, lane, 30)
1191 .expect("put back where it was picked up");
1192 assert_eq!(project.sub_lane(lane)[0], placed, "and nothing moved");
1193
1194 let (_lo, hi) = project
1195 .trim_sub_room(lane, 0, Edge::End, LANE_FPS)
1196 .expect("the room the tail has");
1197 project
1198 .trim_sub(lane, 0, Edge::End, hi, LANE_FPS)
1199 .expect("out to the wall");
1200 let at_wall = project.sub_lane(lane)[0];
1201 project
1202 .trim_sub(lane, 0, Edge::End, hi + 5, LANE_FPS)
1203 .expect("and past it, which is the wall again");
1204 assert_eq!(project.sub_lane(lane)[0], at_wall, "the edge stayed put");
1205
1206 // Two edits happened, so two steps exist: the trim, then the placement.
1207 assert!(project.undo(), "the trim walks back");
1208 assert_eq!(project.sub_lane(lane)[0], placed);
1209 assert!(project.undo(), "and the placement");
1210 assert!(
1211 project.sub_lane(lane).is_empty(),
1212 "the two no-ops left no step of their own"
1213 );
1214}
1215
1216/// The razor and the ripple, which is the whole reason a caption is a lane and
1217/// not a setting: a cut through the picture cuts the words over it, and the
1218/// windows follow by proportion -- no frame rate anywhere in that arithmetic.
1219#[test]
1220fn a_caption_is_cut_and_rippled_with_the_picture_under_it() {
1221 let (mut project, lane) = with_subtitle_lane();
1222 project
1223 .place_sub(
1224 lane,
1225 0,
1226 SubClip {
1227 frames: 60,
1228 out_us: 2_000_000,
1229 ..whole(0)
1230 },
1231 )
1232 .expect("it goes down");
1233
1234 // The razor: halves that add up to the whole, in frames and in microseconds.
1235 assert!(
1236 project.split(30),
1237 "the cut lands on the picture and the words"
1238 );
1239 assert_eq!(
1240 project
1241 .sub_lane(lane)
1242 .iter()
1243 .map(|s| (s.start, s.frames, s.in_us, s.out_us))
1244 .collect::<Vec<_>>(),
1245 [(0, 30, 0, 1_000_000), (30, 30, 1_000_000, 2_000_000)]
1246 );
1247 // ...and its inverse puts the caption back exactly as it was.
1248 assert!(project.regroup(30), "the halves rejoin");
1249 assert_eq!(
1250 project
1251 .sub_lane(lane)
1252 .iter()
1253 .map(|s| (s.start, s.frames, s.in_us, s.out_us))
1254 .collect::<Vec<_>>(),
1255 [(0, 60, 0, 2_000_000)]
1256 );
1257
1258 // A rippling delete through the middle of it: the hole closes, what was
1259 // inside it is gone from the words as well as from the picture, and the two
1260 // halves keep exactly the seconds they kept frames for.
1261 assert!(
1262 project.ripple_delete(20, 20),
1263 "the hole closes on every lane"
1264 );
1265 assert_eq!(
1266 project
1267 .sub_lane(lane)
1268 .iter()
1269 .map(|s| (s.start, s.frames, s.in_us, s.out_us))
1270 .collect::<Vec<_>>(),
1271 [(0, 20, 0, 666_666), (20, 20, 1_333_333, 2_000_000)],
1272 "cut by proportion of the window, not by a frame rate"
1273 );
1274 assert!(project.undo(), "and the whole ripple is one step");
1275 assert_eq!(project.sub_lane(lane).len(), 1);
1276}
1277
1278/// An EBML element: its id as it is written in the file, then an 8-byte
1279/// length, which is always a legal encoding of one.
1280fn element(id: &[u8], body: &[u8]) -> Vec<u8> {
1281 let mut out = id.to_vec();
1282 let mut len = (body.len() as u64).to_be_bytes();
1283 len[0] |= 0x01; // the 8-byte length marker
1284 out.extend_from_slice(&len);
1285 out.extend_from_slice(body);
1286 out
1287}
1288
1289/// A Matroska file carrying four PGS subtitle tracks, the first of them with
1290/// `first` in a block at 500 ms and the erase that ends it at 2 s. No `Info`,
1291/// so the timestamp scale is the spec's default of a millisecond a tick.
1292fn pgs_matroska(first: Vec<u8>) -> Vec<u8> {
1293 let mut tracks = Vec::new();
1294 for (number, language) in [(1u8, "eng"), (2, "fra"), (3, "spa"), (4, "")] {
1295 let mut entry = Vec::new();
1296 entry.extend(element(&[0xD7], &[number])); // TrackNumber
1297 entry.extend(element(&[0x83], &[0x11])); // TrackType: subtitle
1298 entry.extend(element(&[0x86], b"S_HDMV/PGS")); // CodecID
1299 if !language.is_empty() {
1300 entry.extend(element(&[0x22, 0xB5, 0x9C], language.as_bytes()));
1301 }
1302 tracks.extend(element(&[0xAE], &entry)); // TrackEntry
1303 }
1304 // A `SimpleBlock` on track 1: the track number as a one-byte vint, the
1305 // timestamp relative to the cluster's, and no flags.
1306 let block = |at: i16, data: Vec<u8>| {
1307 let mut body = vec![0x81, (at >> 8) as u8, at as u8, 0x00];
1308 body.extend(data);
1309 element(&[0xA3], &body)
1310 };
1311 let mut cluster = element(&[0xE7], &[0x00]); // Timestamp: 0
1312 cluster.extend(block(500, first));
1313 cluster.extend(block(2000, pgs_erase()));
1314
1315 let mut segment = element(&[0x16, 0x54, 0xAE, 0x6B], &tracks); // Tracks
1316 segment.extend(element(&[0x1F, 0x43, 0xB6, 0x75], &cluster)); // Cluster
1317 element(&[0x18, 0x53, 0x80, 0x67], &segment) // Segment
1318}
1319
1320/// One PGS segment as a Matroska block holds it: the type, a big-endian size,
1321/// the body -- and none of the `PG` magic or timestamps a `.sup` file writes,
1322/// which the muxer takes off.
1323fn pgs_segment(kind: u8, body: &[u8]) -> Vec<u8> {
1324 let mut out = vec![kind];
1325 out.extend_from_slice(&(body.len() as u16).to_be_bytes());
1326 out.extend_from_slice(body);
1327 out
1328}
1329
1330/// A display set that paints a 2x2 white square at (1, 1) of an 8x4 canvas:
1331/// the composition, the palette it colours by, the run-length object itself,
1332/// and the end of the set.
1333fn pgs_display_set() -> Vec<u8> {
1334 // Canvas 8x4, a frame-rate byte, composition 0, epoch start, no palette
1335 // update, palette 0 -- and one object, id 0, at (1, 1) with no flags.
1336 #[rustfmt::skip]
1337 let pcs = [
1338 0, 8, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1,
1339 0, 0, 0, 0, 0, 1, 0, 1,
1340 ];
1341 // Palette 0, version 0, then colour 1: white at full opacity, in the
1342 // limited-range YCbCr a disc writes (index, Y, Cr, Cb, A). Colour 0 is the
1343 // transparent one every palette starts with.
1344 let pds = [0, 0, 1, 235, 128, 128, 255];
1345 // Two rows of "two pixels of colour 1, end of line", which is the shortest
1346 // run PGS can write and still be a picture.
1347 let rle = [0x00, 0x82, 0x01, 0x00, 0x00, 0x00, 0x82, 0x01, 0x00, 0x00];
1348 // Object 0, version 0, first *and* last fragment of the sequence; then the
1349 // length of what follows, and the object's own 2x2 box.
1350 let mut ods = vec![0, 0, 0, 0xC0];
1351 ods.extend_from_slice(&[0, 0, (4 + rle.len()) as u8, 0, 2, 0, 2]);
1352 ods.extend_from_slice(&rle);
1353
1354 let mut set = pgs_segment(0x16, &pcs);
1355 set.extend(pgs_segment(0x14, &pds));
1356 set.extend(pgs_segment(0x15, &ods));
1357 set.extend(pgs_segment(0x80, &[]));
1358 set
1359}
1360
1361/// The display set that composes nothing: the same canvas with no object on
1362/// it, which is how a disc says the picture before it is over.
1363fn pgs_erase() -> Vec<u8> {
1364 let mut set = pgs_segment(0x16, &[0, 8, 0, 4, 0x10, 0, 1, 0, 0, 0, 0]);
1365 set.extend(pgs_segment(0x80, &[]));
1366 set
1367}
1368
1369/// The v15 lines: a subtitle lane is written in its place among the others, a
1370/// caption on it is one `sub` line -- both clocks and the palette row it names
1371/// -- and an empty one is the bare line a video lane's is. The whole of it
1372/// comes back the placement it was, and a re-save is the same bytes, which is
1373/// what "the file is the timeline" means for words as much as for pictures.
1374#[test]
1375fn subtitle_lanes_and_their_captions_survive_a_save() {
1376 let dir = scratch("lanes_save");
1377 let media = dir.join("test_av.mp4");
1378 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
1379 let subs = dir.join("test_subs.srt");
1380 std::fs::copy(data("test_subs.srt"), &subs).expect("copy the subtitle fixture");
1381
1382 let mut session = engine::PlaybackSession::open(&media).expect("open the fixture");
1383 session.set_gain(0.0); // silent like the rest of the suites
1384 assert_eq!(
1385 session.import_subtitles(&subs).expect("the .srt imports"),
1386 1
1387 );
1388
1389 let s1 = session.add_lane(LaneKind::Subtitle);
1390 let s2 = session.add_lane(LaneKind::Subtitle);
1391 let caption = SubClip {
1392 start: 0,
1393 frames: 45,
1394 track: 0,
1395 in_us: 500_000,
1396 out_us: 1_500_000,
1397 link: None,
1398 };
1399 session
1400 .place_sub(s1, 10, caption)
1401 .expect("a caption goes down");
1402
1403 let project = dir.join("cut.edith");
1404 session.save_project(&project).expect("save");
1405 let text = std::fs::read_to_string(&project).expect("read the project back");
1406 assert!(text.starts_with("edith 30\n"), "{text}");
1407 assert!(
1408 text.contains("\nsub 1 10 45 0 500000 1500000\n"),
1409 "the placement is one line: where it sits, how long, whose words, and \
1410 the window of them in microseconds: {text}"
1411 );
1412 assert!(
1413 text.contains("\nsub 2\n"),
1414 "and an empty subtitle lane says so on a line of its own: {text}"
1415 );
1416
1417 let back = engine::PlaybackSession::open_project(&project).expect("open the project");
1418 assert_eq!(
1419 back.subtitle_lanes(),
1420 [s1, s2],
1421 "both lanes come back, in the order they were laid out"
1422 );
1423 assert_eq!(
1424 back.sub_lane(s1),
1425 [SubClip {
1426 start: 10,
1427 ..caption
1428 }],
1429 "and the caption is the very placement it was"
1430 );
1431 assert!(back.sub_lane(s2).is_empty(), "the empty one is still empty");
1432 assert_eq!(back.subtitles()[0].cues, expected(), "palette intact");
1433
1434 // ...and saving what was loaded writes the file it was loaded from.
1435 let again = dir.join("cut2.edith");
1436 back.save_project(&again).expect("save again");
1437 assert_eq!(
1438 std::fs::read_to_string(&again).expect("read"),
1439 text,
1440 "a load and a re-save is the same file"
1441 );
1442}
1443
1444/// The dialect before the lanes: a v14 project names its subtitle files and
1445/// places none of them -- there was no line to place one on -- so it loads with
1446/// its palette whole and no subtitle lane at all, and re-saves as v15 with the
1447/// same one `subtitle` line and nothing on any lane.
1448#[test]
1449fn a_version_14_project_keeps_its_palette_and_places_nothing() {
1450 let dir = scratch("v14");
1451 let media = dir.join("test_av.mp4");
1452 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
1453 let srt = dir.join("test_subs.srt");
1454 std::fs::copy(data("test_subs.srt"), &srt).expect("copy the subtitle fixture");
1455 let path = dir.join("old.edith");
1456 std::fs::write(
1457 &path,
1458 "edith 14\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
1459 subtitle - test_subs.srt\nvideo 1 0 0 30 0 0 - - fit 1000\n\
1460 audio 1 0 0 30 0 0 - - fit 1000\n",
1461 )
1462 .expect("write a v14 file");
1463
1464 let loaded = engine::PlaybackSession::open_project(&path).expect("a v14 file still opens");
1465 assert_eq!(loaded.subtitles().len(), 1, "the palette row is there");
1466 assert_eq!(loaded.subtitles()[0].cues, expected(), "cues and all");
1467 assert!(
1468 loaded.subtitle_lanes().is_empty(),
1469 "and nothing of it is placed: that dialect had nowhere to place it"
1470 );
1471
1472 let now = dir.join("new.edith");
1473 loaded.save_project(&now).expect("save");
1474 let text = std::fs::read_to_string(&now).expect("read back");
1475 assert!(text.starts_with("edith 30\n"), "{text}");
1476 assert!(
1477 text.contains("\nsubtitle - test_subs.srt\n"),
1478 "the row survives the migration: {text}"
1479 );
1480 assert!(
1481 !text.contains("\nsub "),
1482 "and no lane and no placement were invented for it: {text}"
1483 );
1484}
1485
1486/// The palette bound, which is a clip's source bound for words: a caption names
1487/// a `subtitle` line by position, so one naming a row that is not there is
1488/// refused -- at the parser, which names the line, and at
1489/// [`engine::Project::with_subs`], which names the lane. Neither is a file this
1490/// editor wrote; both are files it may be handed.
1491#[test]
1492fn a_caption_naming_a_track_the_palette_does_not_have_is_refused() {
1493 let dir = scratch("badtrack");
1494 let media = dir.join("test_av.mp4");
1495 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the media fixture");
1496 std::fs::copy(data("test_subs.srt"), dir.join("test_subs.srt")).expect("copy the subtitles");
1497 let path = dir.join("bad.edith");
1498 std::fs::write(
1499 &path,
1500 "edith 16\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
1501 subtitle - test_subs.srt\nvideo 1 0 0 30 0 0 - - fit 1000\n\
1502 audio 1 0 0 30 0 0 - - fit 1000\nsub 1 0 45 3 0 1000000\n",
1503 )
1504 .expect("write it");
1505 let err = engine::PlaybackSession::open_project(&path)
1506 .err()
1507 .expect("a caption may not name a row that is not there")
1508 .to_string();
1509 assert_eq!(err, "line 9: caption names subtitle track 3 of 1");
1510
1511 // An empty placement is refused by the same door, at either clock.
1512 let empty = dir.join("empty.edith");
1513 std::fs::write(
1514 &empty,
1515 "edith 16\nplayhead 0\nresolution 1280 720\nfps 30.0\nsource 0 test_av.mp4\n\
1516 subtitle - test_subs.srt\nvideo 1 0 0 30 0 0 - - fit 1000\n\
1517 audio 1 0 0 30 0 0 - - fit 1000\nsub 1 0 45 0 1000000 1000000\n",
1518 )
1519 .expect("write it");
1520 let err = engine::PlaybackSession::open_project(&empty)
1521 .err()
1522 .expect("a window of nothing is not a caption")
1523 .to_string();
1524 assert_eq!(
1525 err,
1526 "line 9: caption at 0 is empty: 45 frames of [1000000, 1000000)"
1527 );
1528
1529 // ...and the load's own door says the same thing about the same file, by
1530 // the lane rather than by the line: `from_parts` for words.
1531 let (project, _lane) = with_subtitle_lane();
1532 let beyond = SubClip {
1533 track: 3,
1534 ..whole(0)
1535 };
1536 let refused = project
1537 .clone()
1538 .with_subs(vec![Vec::new(), Vec::new(), vec![beyond]])
1539 .expect_err("the palette holds one row")
1540 .to_string();
1541 assert_eq!(refused, "S1 caption at 0 names subtitle track 3 of 1");
1542
1543 // A caption on a lane that is not a subtitle lane is refused there too --
1544 // the media lanes hold pictures and sound, and never words.
1545 let wrong = project
1546 .with_subs(vec![vec![whole(0)], Vec::new(), Vec::new()])
1547 .expect_err("V1 is not a subtitle track")
1548 .to_string();
1549 assert!(
1550 wrong.starts_with("V1 is not a subtitle track and holds 1 caption(s)"),
1551 "{wrong}"
1552 );
1553}