forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

media.rs1907 lines, 84.7 KiBHistoryRawDownload
1//! What the workers hand back: the progress lines, the file named on the
2//! command line, the scans, the codecs offered, and the subtitles found.
3
4use super::*;
5use crate::player::library::{
6 auto_proxies_pref_path, load_auto_proxies_pref, save_auto_proxies_pref,
7};
8use crate::subs::{
9 SUB_SIZE_RANGE, SubOutline, SubPlace, SubStyle, audio_import_tail, load_subtitle_style,
10 save_subtitle_style, sub_line_h_for, sub_size_at, subtitle_style_path,
11};
12use crate::ui::dock_stance::{viz_glow_at, viz_strands_at};
13use crate::ui::preview::{bgra_to_rgba, screenshot_path};
14
15/// The notice queue's own half of the sound watch, and the three words it is
16/// spelled with -- reached by name because the app's own glob does not carry
17/// them (`notices` is a private module re-exported for the window).
18use crate::notices::{
19 audio_change_notice, audio_lost_line, audio_tail, decode_change_notice, decode_failed_line,
20};
21
22/// The picture twin of the sound watch above, and the same shape for the same
23/// reason: a decode failure that arrives between two frames used to reach no
24/// consumer at all, because the worker printed it to stderr and dropped the
25/// channel -- and a closed channel is what a finished film looks like from the
26/// app's side, so the transport said ENDED over a frozen frame with nothing in
27/// the window saying why.
28///
29/// Driven through the queue step, because a test cannot make a decoder fail on
30/// cue; the engine's writer is the decode worker's, and
31/// `engine::tests::decode_failure` observes it end to end on the engine side.
32#[test]
33fn a_decode_that_fails_under_an_open_file_says_so_and_unsays_it() {
34 // A question stays on screen beside the one ordinary slot, so it is the
35 // line that must survive every change below.
36 let mut notices: std::collections::VecDeque<crate::notices::Toast> = Default::default();
37 crate::notices::push_sticky_toast(
38 &mut notices,
39 "Opened take.mp4".into(),
40 crate::notices::Tone::Info,
41 Vec::new(),
42 );
43 let failed = decode_failed_line("decode error at access unit 130");
44 assert!(
45 failed.starts_with("Decode failed"),
46 "the line lost the state word the strip reads first: {failed}"
47 );
48 // The file was fine, and then the picture stopped: the reason arrives
49 // between two frames.
50 decode_change_notice(&mut notices, None, Some("decode error at access unit 130"));
51 assert_eq!(
52 notices.back().map(|notice| notice.text.as_ref()),
53 Some(failed.as_str()),
54 "a decode failure that arrives mid-session is never pushed"
55 );
56 // The same reason read again on the next frame is not news.
57 decode_change_notice(
58 &mut notices,
59 Some("decode error at access unit 130"),
60 Some("decode error at access unit 130"),
61 );
62 assert_eq!(notices.len(), 2, "one failure was announced twice");
63 // Seeked away from, and it decodes again: the line goes with it, or the
64 // strip keeps saying DECODE FAILED over a film that plays.
65 decode_change_notice(&mut notices, Some("decode error at access unit 130"), None);
66 assert_eq!(
67 notices
68 .iter()
69 .map(|notice| notice.text.as_ref())
70 .collect::<Vec<_>>(),
71 vec!["Opened take.mp4"],
72 "the decode failed line is still on the strip over a film that plays"
73 );
74 // The sound line is a different line, and the one slot means the newest
75 // error is the one on screen: taking that newest line back leaves the
76 // question beside it, and nothing else is touched.
77 audio_change_notice(&mut notices, None, Some("AUDIO_LOST"));
78 decode_change_notice(&mut notices, None, Some("decode error at access unit 7"));
79 decode_change_notice(&mut notices, Some("decode error at access unit 7"), None);
80 assert_eq!(
81 notices
82 .iter()
83 .map(|notice| notice.text.as_ref())
84 .collect::<Vec<_>>(),
85 vec!["Opened take.mp4"],
86 "retracting one reason took more than its own line"
87 );
88 // The wiring: the pump is the one place every frame passes through, and a
89 // watcher nothing calls is a message nobody reads.
90 assert!(
91 fn_body("pump").contains("self.watch_decode();"),
92 "the pump stopped watching the engine's decode reason, so a corrupt \
93 file is a silent freeze again"
94 );
95 // ...and it reads the reason off the session the pump is serving, the same
96 // rule the sound watch follows.
97 assert!(
98 fn_body("decode_reason").contains("self.active_session()"),
99 "the decode watch reads a reason off a session the pump is not \
100 serving, so a preview flip announces the other session's failure"
101 );
102}
103
104/// A reason that changes under a session that is already open says so, and stops
105/// saying so when it clears. This side is the *reader*: the writer of a reason is
106/// the engine's own `audio_disabled_reason`, and the app's two call sites were
107/// the *open* paths -- so a reason that arrived mid-session reached no consumer
108/// at all and the window played on in silence with nothing said. The engine's
109/// writer is the wave branch's, so the flip is driven through the seam here and
110/// asserted end to end on the merged tree; nothing below depends on when the
111/// engine's `tick` sets it.
112///
113/// Driven through the queue step itself -- [`audio_change_notice`] is the whole
114/// of what a reason change does to the strip -- because a test cannot make a
115/// sound card fail on cue; the caching around it is the same comparison plus the
116/// source guard below.
117#[test]
118fn a_device_that_dies_under_an_open_file_says_so_and_unsays_it() {
119 // A question stays on screen beside the one ordinary slot, so it is the
120 // line that must survive every change below.
121 let mut notices: std::collections::VecDeque<crate::notices::Toast> = Default::default();
122 crate::notices::push_sticky_toast(
123 &mut notices,
124 "Opened take.mp4".into(),
125 crate::notices::Tone::Info,
126 Vec::new(),
127 );
128 let lost = audio_lost_line("AUDIO_LOST");
129 // The file was fine, and then the sound is gone: the reason arrives between
130 // two frames.
131 audio_change_notice(&mut notices, None, Some("AUDIO_LOST"));
132 assert_eq!(
133 notices.back().map(|notice| notice.text.as_ref()),
134 Some(lost.as_str()),
135 "a reason that arrives mid-session is never pushed"
136 );
137 assert!(
138 lost.starts_with("Audio lost") && lost.ends_with(&audio_tail("AUDIO_LOST")),
139 "the standing line lost its state word, or stopped sharing \
140 `audio_notice`'s own tail"
141 );
142 // The same reason read again on the next frame is not news.
143 audio_change_notice(&mut notices, Some("AUDIO_LOST"), Some("AUDIO_LOST"));
144 assert_eq!(notices.len(), 2, "one death was announced twice");
145 // The re-arm takes: the line goes with it, and nothing else does.
146 audio_change_notice(&mut notices, Some("AUDIO_LOST"), None);
147 assert_eq!(
148 notices
149 .iter()
150 .map(|notice| notice.text.as_ref())
151 .collect::<Vec<_>>(),
152 vec!["Opened take.mp4"],
153 "the no audio line is still on the strip over a film that plays"
154 );
155 // A second death later says so again.
156 audio_change_notice(&mut notices, None, Some("AUDIO_LOST"));
157 assert_eq!(
158 notices.back().map(|notice| notice.text.as_ref()),
159 Some(lost.as_str())
160 );
161 // The wiring: the pump is the one place every frame passes through, and a
162 // watcher nothing calls is a message nobody reads.
163 assert!(
164 fn_body("pump").contains("self.watch_audio();"),
165 "the pump stopped watching the engine's sound reason, so a device that \
166 dies mid-session is silent again"
167 );
168 // ...and the watch keys its cache to the session it is a statement about:
169 // the two generations are what the *step call* is asked, so a preview flip
170 // cannot be answered as if it were the cached session's own change.
171 let watch = fn_body("watch_audio");
172 let args = watch
173 .split_once("reason_step(")
174 .expect(
175 "the watch decides for itself instead of through the pure step the flip test drives",
176 )
177 .1;
178 let args = args.split_once(')').map_or(args, |(args, _)| args);
179 assert!(
180 args.contains("self.audio_watch_gen") && args.contains("self.session_gen"),
181 "the watch asks the step about something other than the session it serves, \
182 so a preview opening or closing announces the other session's device"
183 );
184 assert!(
185 fn_body("sound_reason").contains("self.active_session()"),
186 "the watch reads a reason off a session the pump is not serving, so its \
187 cache and the frame disagree the moment a preview is up"
188 );
189 // ...and every door that installs or drops a session says so, the preview's
190 // two among them (the one the flip was missed on).
191 for door in ["close_session", "open_preview", "close_preview"] {
192 assert!(
193 fn_body(door).contains("self.session_swapped();"),
194 "{door} installs or drops a session without telling anything keyed to \
195 one, so a flip reads as news"
196 );
197 }
198}
199
200/// The flip logic itself, pure: a preview opening or closing is a *different*
201/// session, so the reason it reports is not news about the cached one -- the
202/// phantom device loss the verifier caught, and the reason the cache carries a
203/// generation at all. A change on the session the cache describes is the one that
204/// speaks.
205#[test]
206fn a_preview_flip_is_not_a_device_that_came_back() {
207 use crate::notices::{ReasonStep, reason_step};
208 // A swap, every way round: seeded, never announced.
209 assert_eq!(
210 reason_step(7, 8, None, Some("AUDIO_LOST")),
211 ReasonStep::Seed
212 );
213 assert_eq!(
214 reason_step(7, 8, Some("AUDIO_LOST"), None),
215 ReasonStep::Seed
216 );
217 assert_eq!(
218 reason_step(7, 8, Some("AUDIO_LOST"), Some("AUDIO_LOST")),
219 ReasonStep::Seed,
220 "a flip whose reason reads the same on both sides is still a flip"
221 );
222 // The same session, the reason arriving, changing, and going.
223 assert_eq!(
224 reason_step(7, 7, None, Some("AUDIO_LOST")),
225 ReasonStep::Push
226 );
227 assert_eq!(
228 reason_step(7, 7, Some("AUDIO_LOST"), Some("device gone")),
229 ReasonStep::Push
230 );
231 assert_eq!(
232 reason_step(7, 7, Some("AUDIO_LOST"), None),
233 ReasonStep::Clear
234 );
235 assert_eq!(
236 reason_step(7, 7, Some("AUDIO_LOST"), Some("AUDIO_LOST")),
237 ReasonStep::Nothing,
238 "the same reason read again on the next frame is not news"
239 );
240 assert_eq!(reason_step(7, 7, None, None), ReasonStep::Nothing);
241 assert_eq!(reason_step(0, 0, None, None), ReasonStep::Nothing);
242}
243
244/// The toast tail an audio import earns: rate, channel count and rounded
245/// length, in the words the IMPORTED line appends them in
246/// ([`Player::take_import`], [`Player::install_media`]). A film gets none of
247/// it -- the gate is the probed has-video answer, not the extension, so an
248/// audio-only container wearing .mp4 reads its numbers too.
249#[test]
250fn an_audio_import_names_its_rate_channels_and_length() {
251 let tail = audio_import_tail(&asset("test_tone.mp3"), false);
252 assert_eq!(tail, " — 44100 Hz, 2 ch, 3s", "{tail}");
253 assert_eq!(audio_import_tail(&asset("test_av.mp4"), true), "");
254 let mp4 = audio_import_tail(&asset("test_audio_only.mp4"), false);
255 assert_eq!(mp4, " — 44100 Hz, 1 ch, 3s", "{mp4}");
256}
257
258/// The import line's own state machine, driven the way a repaint drives
259/// it: the worker writes a stage, the poll notices it changed and restarts
260/// the stall clock, and the line's words change only when a stage has
261/// actually stood still. The whole point is that a stuck read reads as a
262/// stuck read and never as a frozen window.
263#[test]
264fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() {
265 use std::sync::Arc;
266 use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
267 let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8));
268 let started = Instant::now() - Duration::from_secs(9);
269 let mut import = Import {
270 path: PathBuf::from("/films/A Film.mkv"),
271 started,
272 stage: Arc::clone(&stage),
273 seen: ImportStage::Header,
274 // As if the header had been running for those nine seconds.
275 since: started,
276 cancelled: Arc::default(),
277 };
278 // Nine seconds inside one stage: past the wait a person tolerates, so
279 // the line stops pretending it is a progress line.
280 let since = import.poll();
281 assert!(since > IMPORT_STALL, "{since}");
282 let stalled = import_line("A Film.mkv", import.seen, 9., since, 0, false);
283 assert!(stalled.contains("still reading the header"), "{stalled}");
284 assert!(stalled.contains("not frozen"), "{stalled}");
285 assert!(stalled.contains("0:09 elapsed"), "{stalled}");
286 // The worker moves on: the stall clock restarts even though the elapsed
287 // one does not, which is the distinction the two clocks exist for.
288 stage.store(ImportStage::Subtitles as u8, Relaxed);
289 let since = import.poll();
290 assert_eq!(import.seen, ImportStage::Subtitles);
291 assert!(since < IMPORT_STALL, "{since}");
292 let moving = import_line("A Film.mkv", import.seen, 9., since, 2, false);
293 assert!(
294 moving.starts_with("Importing A Film.mkv · reading the subtitle tracks"),
295 "{moving}"
296 );
297 assert!(!moving.contains("still"), "{moving}");
298 // ...and what is behind it in the queue, which is what a drop of three
299 // files or an argv of three files leaves waiting.
300 assert!(moving.ends_with("· 2 more waiting"), "{moving}");
301 assert!(!stalled.ends_with("waiting"), "an empty queue says nothing");
302 // A stage that does not move is not the same fact as a stage that came
303 // back to the same value: the poll only restarts on a change.
304 let held = import.since;
305 import.poll();
306 assert_eq!(import.since, held, "an unchanged stage must not reset it");
307}
308
309/// The launch, from argv to the window being up: nothing named on the
310/// command line is read before there is a window, so all a launch does is
311/// sort argv into the file that becomes the timeline and the queue that is
312/// read through -- and a run with no arguments has neither, exactly as it
313/// had none before.
314#[test]
315fn a_launch_queues_the_file_it_names_instead_of_opening_it() {
316 let film = PathBuf::from("/films/Dune.mkv");
317 let extra = PathBuf::from("/films/Titles.mov");
318 let (arg, queue) = launch_queue([film.clone(), extra.clone()].into_iter());
319 assert_eq!(arg.as_deref(), Some(film.as_path()), "argv[1] is the open");
320 // In the order they were named, the timeline's file first: six header
321 // walks racing over one disk finish no sooner than six in a row, and
322 // the one the person is waiting to watch goes first.
323 assert_eq!(queue, [film, extra], "argv, in arrival order");
324 // ...and no argument at all is still the empty window: nothing to open
325 // and nothing to read.
326 let (arg, queue) = launch_queue(std::iter::empty());
327 assert_eq!(arg, None);
328 assert!(queue.is_empty(), "no argv, nothing queued");
329}
330
331/// Which door a queued file goes through. One queue carries the file argv
332/// named and every import behind it, so this fork -- made when the worker
333/// starts and carried to the landing as a [`Landed`] -- is the whole state
334/// machine: the named file becomes the timeline (a `.edith` restoring a
335/// whole one), everything else joins the library, including the very same
336/// film dropped again once the open has landed.
337#[test]
338fn the_file_argv_named_lands_as_the_timeline_and_everything_behind_it_as_imports() {
339 let film = PathBuf::from("/films/Dune.mkv");
340 let extra = PathBuf::from("/films/Titles.mov");
341 let project = PathBuf::from("/films/Dune.edith");
342 assert_eq!(arrival(Some(&film), &film), Landing::Open);
343 assert_eq!(arrival(Some(&project), &project), Landing::Project);
344 assert_eq!(arrival(Some(&film), &extra), Landing::Import);
345 // Cleared as it lands: a drop of the film already on the timeline is an
346 // import, which is what a drop has always been.
347 assert_eq!(arrival(None, &film), Landing::Import);
348 // ...except a `.edith`, which is a whole timeline and has nothing to be
349 // imported into: dropped or picked, it lands where argv's does, and its
350 // open is the worker's like every other.
351 assert_eq!(arrival(None, &project), Landing::Project);
352 assert_eq!(arrival(Some(&film), &project), Landing::Project);
353}
354
355/// What the window says while the file argv named is being read: the file's
356/// name, the read that is running, and a clock proving the window is
357/// answering -- in the *opening* wording, because the one person who typed
358/// that name is not importing anything.
359#[test]
360fn the_named_file_is_read_under_an_opening_line_not_an_importing_one() {
361 let opening = import_line("Dune.mkv", ImportStage::Header, 0.4, 0.4, 1, true);
362 assert!(
363 opening.starts_with("Opening Dune.mkv · reading the header"),
364 "{opening}"
365 );
366 assert!(opening.ends_with("· 1 more waiting"), "{opening}");
367 // Twelve seconds into a cold 25 GB header walk, which is the whole
368 // reason the window is up: it says the read is still moving through the
369 // same stage and that this is not a freeze.
370 let stalled = import_line("Dune.mkv", ImportStage::Header, 12., 12., 0, true);
371 assert!(stalled.starts_with("Opening Dune.mkv · still"), "{stalled}");
372 assert!(stalled.contains("not frozen"), "{stalled}");
373 assert!(stalled.contains("0:12 elapsed"), "{stalled}");
374 // The files behind it are imports and still say so.
375 let import = import_line("Titles.mov", ImportStage::Header, 0.4, 0.4, 0, false);
376 assert!(import.starts_with("Importing Titles.mov"), "{import}");
377}
378
379/// One gesture over the real gate, with the plumbing around it spelled out:
380/// a write reseeks (the worker owes a frame again), a landed frame clears
381/// that and flushes what is held, and the release flushes whatever the
382/// worker is doing. Forty snapped steps and four frames delivered must cost
383/// five writes -- the press's and one per frame -- and not forty, which is
384/// the 22-30 s freeze this exists to remove.
385#[test]
386fn a_bar_wide_sweep_writes_once_per_frame_delivered() {
387 let mut stash: Option<i32> = None;
388 let mut written = Vec::new();
389 let mut busy = false;
390 for step in 0..40 {
391 if let Some(value) = stash_or_write(&mut stash, step, step == 0, busy) {
392 // What `write_color` does: the write supersedes the stash and
393 // reseeks, so the worker owes a frame from here.
394 stash = None;
395 written.push(value);
396 busy = true;
397 }
398 // A frame lands every tenth sample: `pump` clears the seek and the
399 // render flushes what the drag held back.
400 if step % 10 == 9 {
401 busy = false;
402 if let Some(value) = stash.take() {
403 written.push(value);
404 busy = true;
405 }
406 }
407 }
408 // The release, whatever the worker is doing.
409 written.extend(stash.take());
410 assert_eq!(
411 written,
412 vec![0, 9, 19, 29, 39],
413 "one write per frame landed"
414 );
415}
416
417/// The one value a gesture may never lose: where the hand let go. The
418/// release samples into a busy worker -- so the sample is held -- and the
419/// flush behind it is what writes it.
420#[test]
421fn a_release_lands_the_value_the_hand_let_go_on() {
422 let mut stash = None;
423 assert_eq!(stash_or_write(&mut stash, 7, false, true), None);
424 assert_eq!(stash_or_write(&mut stash, 11, false, true), None);
425 assert_eq!(stash.take(), Some(11), "the release writes the last sample");
426 // The press is never held: it is the undo step the gesture rolls back
427 // to, and one taken a frame late is a snapshot of the wrong grade.
428 assert_eq!(stash_or_write(&mut stash, 3, true, true), Some(3));
429 assert_eq!(stash, None);
430 // Nothing to hold when the worker is idle: the write goes straight out.
431 assert_eq!(stash_or_write(&mut stash, 5, false, false), Some(5));
432 assert_eq!(stash, None);
433}
434
435/// The wheel's own version of the same gesture, and the one thing a drag on it
436/// may not lose while the worker is behind: the mark follows the hand. A held
437/// sample is what the wheel draws -- the clip carries the ink from before it
438/// until the holding frame lands -- and the pen's own settings, which are not
439/// part of a hue/saturation sample, survive it untouched.
440#[test]
441fn the_wheel_draws_the_sample_a_drag_is_holding() {
442 // Nothing held: the clip's own ink, byte for byte -- the default 0
443 // included, which materializes to azure where it is read.
444 assert_eq!(viz_held_paint(0, None), 0);
445 assert_eq!(viz_held_paint(0x0208_d2fd, None), 0x0208_d2fd);
446 // Held: that hue and saturation over what the clip already carries.
447 let held = viz_held_paint(0, Some((VizSlot::Main, 253, 210)));
448 assert_eq!(engine::decode::viz_hue_ui(held), 253);
449 assert_eq!(engine::decode::viz_sat_ui(held), 210);
450 // ...in that order, never the other way round: a mark drawn at the wrong
451 // angle is the whole gesture showing the wrong colour.
452 let flipped = viz_held_paint(0, Some((VizSlot::Main, 210, 253)));
453 assert_ne!(held, flipped);
454 assert_eq!(engine::decode::viz_hue_ui(flipped), 210);
455 assert_eq!(engine::decode::viz_sat_ui(flipped), 253);
456 // Strands and glow are the clip's, not the sample's: the wheel carries no
457 // row for either, so a held hue may not move them.
458 assert_eq!(engine::decode::viz_strands_of(held), 8);
459 assert_eq!(engine::decode::viz_glow_of(held), 2);
460 let pen = engine::decode::with_viz_paint_glow(0x0208_d2fd, 9);
461 assert_eq!(
462 engine::decode::viz_glow_of(viz_held_paint(pen, Some((VizSlot::Main, 253, 210)))),
463 9
464 );
465}
466
467/// The strands and glow sliders: a press's share of the track lands on a
468/// count the engine keeps, at both ends and at the middle, and a share past
469/// an end pins to that end rather than wrapping.
470#[test]
471fn the_strand_and_glow_sliders_land_on_the_engine_range() {
472 assert_eq!(viz_strands_at(0.), 1);
473 assert_eq!(viz_strands_at(1.), 32);
474 // Half a track is 15.5 steps on from one: it rounds up to 17.
475 assert_eq!(viz_strands_at(0.5), 17);
476 assert_eq!(viz_strands_at(-0.2), 1);
477 assert_eq!(viz_strands_at(1.7), 32);
478 assert_eq!(viz_glow_at(0.), 0);
479 assert_eq!(viz_glow_at(1.), 16);
480 assert_eq!(viz_glow_at(0.5), 8);
481 assert_eq!(viz_glow_at(9.), 16);
482 // The default paint's own counts sit inside what the sliders can reach.
483 let azure = engine::decode::VIZ_PAINT_AZURE;
484 assert!((1..=32).contains(&engine::decode::viz_strands_of(azure)));
485 assert!(engine::decode::viz_glow_of(azure) <= 16);
486}
487
488/// The strand's half of the same gesture, and the two things a second ink on
489/// the one wheel may not get wrong. A strand the clip has not chosen starts at
490/// the automatic complement the painter draws there -- the clip's hue half a
491/// turn round, at the clip's own saturation -- so the mark is on a colour the
492/// picture already has and the first write only says "this one, then". And the
493/// clip's own ink is not touched by any of it: the whole point of a second ink
494/// is that one slot's writes leave the other alone.
495#[test]
496fn the_strand_slot_starts_at_the_complement_and_the_write_chooses_it() {
497 use engine::decode::{
498 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_hue_ui, viz_strand_sat_ui,
499 viz_strand_set, with_viz_paint_hue, with_viz_paint_strands,
500 };
501
502 let paint = with_viz_paint_strands(VIZ_PAINT_AZURE, 2);
503 assert!(!viz_strand_set(paint), "no strand colour chosen yet");
504 assert_eq!(
505 VizSlot::Strand.hue_sat(paint),
506 (viz_hue_ui(paint).wrapping_add(128), viz_sat_ui(paint)),
507 "the unset strand stands where the painter draws its complement"
508 );
509 // ...half a turn round, wrapping: hue 200's complement is 72, not 328.
510 let late = with_viz_paint_hue(paint, 200);
511 assert_eq!(VizSlot::Strand.hue_sat(late).0, 200u8.wrapping_add(128));
512 assert_eq!(VizSlot::Strand.hue_sat(late).0, 72);
513
514 // The write is what chooses it, and reads back as what was written.
515 let picked = VizSlot::Strand.set_hue_sat(paint, 0, 255);
516 assert!(viz_strand_set(picked));
517 assert_eq!(viz_strand_hue_ui(picked), 0);
518 assert_eq!(viz_strand_sat_ui(picked), 255);
519 assert_eq!(VizSlot::Strand.hue_sat(picked), (0, 255));
520 // The clip's own colour survives the strand's writes untouched.
521 assert_eq!(viz_hue_ui(picked), viz_hue_ui(paint));
522 assert_eq!(viz_sat_ui(picked), viz_sat_ui(paint));
523 // A held strand sample draws the strand, not the clip's colour: the slot
524 // rides with the sample.
525 let held = viz_held_paint(paint, Some((VizSlot::Strand, 0, 255)));
526 assert_eq!(VizSlot::Strand.hue_sat(held), (0, 255));
527 assert!(viz_strand_set(held));
528 // And the wheel's own slot writes only its own bytes.
529 let main = VizSlot::Main.set_hue_sat(picked, 33, 44);
530 assert_eq!((viz_hue_ui(main), viz_sat_ui(main)), (33, 44));
531 assert_eq!((viz_strand_hue_ui(main), viz_strand_sat_ui(main)), (0, 255));
532}
533
534/// One strand has no dual half, so the strand slot falls back to the clip's own
535/// colour: a write there lands on the ink the picture actually paints instead
536/// of choosing a strand colour nothing wears. Two strands put it back -- the
537/// same reading the Strand chip is enabled by.
538#[test]
539fn a_strand_slot_on_a_single_strand_clip_is_the_clip_s_own_colour() {
540 use engine::decode::{
541 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, viz_strands_of,
542 with_viz_paint_hue, with_viz_paint_sat, with_viz_paint_strands,
543 };
544
545 let one = with_viz_paint_strands(
546 with_viz_paint_sat(with_viz_paint_hue(VIZ_PAINT_AZURE, 64), 200),
547 1,
548 );
549 assert_eq!(viz_strands_of(one), 1);
550 assert_eq!(VizSlot::Strand.picked(one), VizSlot::Main);
551 let hit = VizSlot::Strand.picked(one).set_hue_sat(one, 0, 255);
552 assert!(!viz_strand_set(hit), "one strand chooses no strand colour");
553 assert_eq!((viz_hue_ui(hit), viz_sat_ui(hit)), (0, 255));
554 // The clip's own slot is never redirected -- it is what the fallback
555 // lands on.
556 assert_eq!(VizSlot::Main.picked(one), VizSlot::Main);
557 assert_eq!(
558 VizSlot::Strand.picked(with_viz_paint_strands(one, 2)),
559 VizSlot::Strand
560 );
561}
562
563/// A seek says nothing until it has stood: an ordinary one is a flicker and
564/// a cold read of a big file is the case worth words.
565#[test]
566fn a_seek_says_so_only_once_it_has_stood() {
567 assert_eq!(seek_line(None), None, "no seek, no line");
568 assert_eq!(seek_line(Some(Duration::from_millis(300))), None);
569 let line = seek_line(Some(SEEK_STALL + Duration::from_secs(4))).expect("past the stall");
570 assert_eq!(line, "Opening the picture\u{2026} 6 s");
571 assert_eq!(
572 seek_line(Some(SEEK_STALL + Duration::from_millis(100))).as_deref(),
573 Some("Opening the picture\u{2026}"),
574 "the seconds only once they say something"
575 );
576}
577
578/// A read that has stood past the give-up mark says why in plain words instead of a running
579/// count. A missing file is not in this line at all: the banner over the picture says it.
580#[test]
581fn a_picture_that_is_not_coming_says_why() {
582 assert_eq!(
583 seek_line(Some(SEEK_GIVE_UP)).as_deref(),
584 Some("Can't show this frame: nothing could be read at the playhead.")
585 );
586 assert!(seek_line(Some(SEEK_GIVE_UP - Duration::from_millis(1))).unwrap().starts_with("Opening"));
587 let overlays = src_text("ui/overlays.rs");
588 assert!(overlays.contains("if self.picture_is_missing() {\n return None;"), "a missing file is the banner's");
589}
590
591/// The silence card's own state machine, driven the way a repaint drives
592/// it: a worker moves its mark, the poll notices and restarts the stall
593/// clock, and the line says a read has stopped only when it actually has.
594/// The card is up through all of it -- that is the whole change, since the
595/// same decode used to run on the render thread and hold the frame for
596/// fifty-one seconds on a 25 GB film.
597#[test]
598fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {
599 use std::sync::Arc;
600 use std::sync::atomic::Ordering::Relaxed;
601 let progress = Arc::new(engine::silence::Progress::default());
602 // Two hours and eight minutes, as the header claims it.
603 progress.total.store(7680, Relaxed);
604 let started = Instant::now() - Duration::from_secs(9);
605 let mut scan = SilenceScan {
606 key: (PathBuf::from("/films/A Film.mkv"), 0, 0, 192_000),
607 started,
608 progress: Arc::clone(&progress),
609 seen: 0,
610 since: started,
611 };
612 // Nine seconds and the mark has not moved: past the wait a person
613 // tolerates, so the line stops pretending it is a progress line.
614 let since = scan.poll();
615 assert!(since > IMPORT_STALL, "{since}");
616 let stalled = silence_line(0., 768., 9., since);
617 assert!(stalled.contains("still reading the sound"), "{stalled}");
618 assert!(stalled.contains("not frozen"), "{stalled}");
619 assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}");
620 assert!(stalled.contains("0:09 elapsed"), "{stalled}");
621 // The worker reports, and the stall clock restarts even though the
622 // elapsed one does not -- the two clocks' whole distinction.
623 let mut last = 0;
624 for deci in [83, 1_140, 4_002] {
625 progress.scanned.store(deci, Relaxed);
626 let since = scan.poll();
627 assert!(since < IMPORT_STALL, "{since}");
628 assert!(scan.seen > last, "{} after {last}", scan.seen);
629 last = scan.seen;
630 }
631 let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2);
632 assert_eq!(moving, "Scanning · 6:40 of ~12:48 scanned · 0:09 elapsed");
633 assert!(!moving.contains("still"), "{moving}");
634 // A header that does not say how long the track is says nothing rather
635 // than guessing at it.
636 let unknown = silence_line(60., 0., 61., 0.2);
637 assert_eq!(unknown, "Scanning · 1:00 scanned · 1:01 elapsed");
638 // A mark that comes back the same is not the same fact as one that
639 // moved: the poll only restarts on a change.
640 let held = scan.since;
641 scan.poll();
642 assert_eq!(scan.since, held, "an unchanged mark must not reset it");
643}
644
645/// The cache is per scanned stretch, which is what stops two films
646/// thrashing each other's fifty seconds: A, then B, then A again is *one*
647/// decode of A. And a stretch already being read is waited for rather than
648/// read twice -- both halves of an A/V take name the same file and the same
649/// frames. A *trimmed* A is not A: it is a shorter read of its own, which
650/// is the whole point of scanning the clip instead of the file.
651#[test]
652fn a_second_film_does_not_cost_the_first_one_its_levels() {
653 let (a, b) = (
654 (PathBuf::from("/films/a.mkv"), 0, 0, 3000),
655 (PathBuf::from("/films/b.mkv"), 0, 0, 3000),
656 );
657 let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500);
658 let mut cache: std::collections::HashMap<ScanKey, ()> = std::collections::HashMap::new();
659 let mut started = Vec::new();
660 // What a card open does, three times over, with the worker landing
661 // between each: plan, and start what the plan says to start.
662 for key in [&a, &b, &a] {
663 match scan_plan(cache.contains_key(key), None, key) {
664 ScanPlan::Start => {
665 started.push(key.clone());
666 cache.insert(key.clone(), ());
667 }
668 ScanPlan::Marks => {}
669 ScanPlan::Wait => unreachable!("nothing is running"),
670 }
671 }
672 assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice");
673 // The single-slot cache this replaced would have evicted A when B
674 // landed; both are held.
675 assert!(cache.contains_key(&a) && cache.contains_key(&b));
676 // A scan in flight on the same source is joined, not restarted -- and
677 // one on another source is not waited for.
678 assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait);
679 assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
680 // Levels in hand beat a worker either way: the marks are arithmetic.
681 assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
682 // The same file cut in half is a read of its own: neither A's levels
683 // nor A's worker answers for it.
684 assert_eq!(
685 scan_plan(cache.contains_key(&half), None, &half),
686 ScanPlan::Start
687 );
688 assert_eq!(scan_plan(false, Some(&a), &half), ScanPlan::Start);
689 // ...and the seconds asked for are the clip's, at the project's rate.
690 assert_eq!(source_secs(&half, 30.), (0., 50.));
691 assert_eq!(
692 source_secs(&(half.0.clone(), 0, 900, 1500), 30.),
693 (30., 50.)
694 );
695 // A rate that is not one reads the file rather than nothing.
696 assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY));
697}
698
699/// The background scan started at import ([`Player::cache_media`]) lands its
700/// whole-file levels under [`full_scan_key`], and that entry alone is what
701/// makes the card's own cache check answer "already read" for *every* clip
702/// cut from that source -- without the per-clip decode `start_silence_scan`
703/// used to be the only way to get one. The whole point of moving the scan to
704/// import: the card must find it warm.
705#[test]
706fn a_warm_whole_source_scan_answers_the_card_for_every_clip_cut_from_it() {
707 use std::sync::Arc;
708 let mut levels: std::collections::HashMap<ScanKey, Arc<Vec<f32>>> =
709 std::collections::HashMap::new();
710 let clip_a = (PathBuf::from("/films/a.mkv"), 0, 300, 900);
711 let clip_b = (PathBuf::from("/films/a.mkv"), 0, 1_200, 1_800);
712 // Nothing yet -- neither clip's own read nor a background one.
713 assert!(!silence_cached(&levels, &clip_a));
714 assert!(!silence_cached(&levels, &clip_b));
715 // The background scan lands, once, before either half of the take was
716 // ever opened on the card.
717 levels.insert(full_scan_key(&clip_a.0, clip_a.1), Arc::new(vec![0.; 100]));
718 assert!(
719 silence_cached(&levels, &clip_a) && silence_cached(&levels, &clip_b),
720 "one whole-source entry answers for both halves of the take"
721 );
722 // A clip cut from a *different* file is not answered by it -- the
723 // sentinel is per (path, stream), exactly like every other scan key.
724 let other_file = (PathBuf::from("/films/b.mkv"), 0, 300, 900);
725 assert!(!silence_cached(&levels, &other_file));
726 // A clip's own exact read still counts too, same as before this existed.
727 levels.insert(clip_a.clone(), Arc::new(vec![-40.; 10]));
728 assert!(silence_cached(&levels, &clip_a));
729}
730
731/// What the card actually draws from a warm background scan: the same
732/// dBFS-per-window numbers a direct read of the clip's own stretch would
733/// have found, because window `k` of the whole file and window `k` of a read
734/// that started at second 0 name the same slice of the same source
735/// ([`slice_whole_levels`]'s whole contract). No decode in this test at
736/// all -- the numbers are synthetic and distinct per window so a wrong
737/// offset shows up as a wrong value, not a coincidentally-right one.
738#[test]
739fn a_clips_slice_of_the_whole_scan_is_the_windows_its_own_read_would_have_found() {
740 // 50 fps: one timeline frame is exactly one silence window
741 // (`engine::silence::WINDOWS_PER_SEC` is 50), so the arithmetic is exact
742 // and the test does not have to fight rounding to prove the offset.
743 let fps = 50.;
744 let whole: Vec<f32> = (0..40).map(|i| i as f32).collect();
745 let slice = slice_whole_levels(&whole, fps, 10, 20);
746 assert_eq!(slice, (10..20).map(|i| i as f32).collect::<Vec<f32>>());
747 // The clip's own in point is where its slice starts, not the file's:
748 // a take an hour into the film reads the same as one at its head.
749 assert_eq!(
750 slice_whole_levels(&whole, fps, 0, 5),
751 vec![0., 1., 2., 3., 4.]
752 );
753 // Past what the background scan has read so far (still running, or
754 // cancelled) is not padded with zeroes -- the caller is told nothing is
755 // there yet, same as [`SilenceScan`]'s own cancel leaves a prefix.
756 assert_eq!(
757 slice_whole_levels(&whole, fps, 35, 60),
758 vec![35., 36., 37., 38., 39.]
759 );
760 assert_eq!(slice_whole_levels(&whole, fps, 45, 60), Vec::<f32>::new());
761 // A rate that is not a rate reads nothing, the same refusal
762 // `source_secs` makes for a background scan's own range.
763 assert_eq!(slice_whole_levels(&whole, 0., 0, 10), Vec::<f32>::new());
764}
765
766/// The import door's split, which is what keeps the render thread out of a
767/// header walk: what the worker probed and what the landing registers add up
768/// to exactly the rows, lengths and refusals the in-place import lands.
769#[test]
770fn probing_ahead_lands_exactly_what_importing_in_place_lands() {
771 use std::sync::atomic::AtomicU8;
772 let stage = AtomicU8::new(ImportStage::Header as u8);
773 let plain = {
774 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
775 session.set_gain(0.0);
776 session.import(&asset("test_av2.mp4")).expect("av2 matches");
777 (
778 session.sources().to_vec(),
779 session.file_frames(&asset("test_av2.mp4")),
780 session.timeline_duration(),
781 )
782 };
783 let split = {
784 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
785 session.set_gain(0.0);
786 let (subs, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(session.import_gate()));
787 // This mp4 is walked now (an mp4 can carry `tx3g`) and has no
788 // subtitle track in it, so the worker hands over an empty list --
789 // the same thing the import lands with.
790 assert!(subs.expect("an mp4 is readable").is_empty());
791 let probe = probe
792 .expect("a container is probed on the worker")
793 .expect("av2 matches");
794 session
795 .import_probed(&asset("test_av2.mp4"), probe)
796 .expect("av2 matches");
797 (
798 session.sources().to_vec(),
799 session.file_frames(&asset("test_av2.mp4")),
800 session.timeline_duration(),
801 )
802 };
803 assert_eq!(plain, split);
804 // ...and it leaves the stage where the line can read it: a worker that
805 // never announced its second read would show one that never ends.
806 assert_eq!(
807 ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)),
808 ImportStage::Subtitles
809 );
810 // A refusal is the engine's refusal, and now it is *the* refusal: the
811 // walk happens once, on the worker, so what the probe says is what the
812 // notice shows -- worded exactly as importing in place worded it.
813 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
814 session.set_gain(0.0);
815 let (_, probe) = read_parts(
816 &asset("test_25fps.mp4"),
817 &stage,
818 Some(session.import_gate()),
819 );
820 let on_the_worker = probe
821 .expect("a container is probed")
822 .map(|_| ())
823 .map_err(|e| e.to_string());
824 assert_eq!(
825 on_the_worker,
826 session
827 .import(&asset("test_25fps.mp4"))
828 .map(|_| ())
829 .map_err(|e| e.to_string())
830 );
831 // A timeline that moved while the worker read is not one the probe was
832 // decided against, so the probe is not trusted -- the import is simply
833 // taken the slow way and lands the same row.
834 let mut moved = PlaybackSession::open(asset("test_av.mp4")).expect("open");
835 moved.set_gain(0.0);
836 let (_, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(moved.import_gate()));
837 moved
838 .import(&asset("test_still.png"))
839 .expect("a still joins");
840 let stale = probe.expect("a container is probed").expect("av2 matches");
841 assert_eq!(
842 moved.import_probed(&asset("test_av2.mp4"), stale).ok(),
843 Some(2),
844 "a stale probe still lands the file, by the door that re-reads it"
845 );
846 // A path nothing can read is refused by the worker now, in the engine's
847 // own words: nothing walks it a second time to re-word it, and neither
848 // half is a panic.
849 let (subs, probe) = read_parts(
850 std::path::Path::new("/no/such/film.mkv"),
851 &stage,
852 Some(session.import_gate()),
853 );
854 assert!(subs.is_err(), "the cue walk comes back as a refusal");
855 assert!(
856 probe.expect("a container is probed").is_err(),
857 "and so does the container walk"
858 );
859}
860
861/// The import door's two halves, split across the worker hop: what
862/// [`read_ahead`] walks is exactly what the render thread would have walked,
863/// and pushing it says what walking it in place used to say.
864#[test]
865fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() {
866 use std::sync::atomic::AtomicU8;
867 let stage = AtomicU8::new(ImportStage::Header as u8);
868 let film = asset("test_subs.mkv");
869 // The in-place walk (`subtitle_notice`) and the split one land the same
870 // tracks and the same tail on the same timeline.
871 let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open");
872 in_place.set_gain(0.0);
873 let said = subtitle_notice(&mut in_place, &film);
874 let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open");
875 split.set_gain(0.0);
876 let (walked, _) = read_parts(&film, &stage, Some(split.import_gate()));
877 let walked = walked.expect("the mkv is readable");
878 assert_eq!(subtitle_tail(&mut split, Ok(walked)), said);
879 assert_eq!(split.subtitles().len(), in_place.subtitles().len());
880 // The same file twice is still one row, and still says so: the dedupe
881 // lives in the push, which is the half that stayed here.
882 let (again, _) = read_parts(&film, &stage, Some(split.import_gate()));
883 let again = again.expect("the mkv is readable");
884 assert_eq!(subtitle_tail(&mut split, Ok(again)), None);
885 // A standalone `.srt` is walked by the same worker: an import of one is
886 // not a door that reads on the render thread either.
887 let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
888 .join("../engine/tests/data/test_subs.srt")
889 .canonicalize()
890 .expect("the subtitle fixture");
891 assert_eq!(
892 read_parts(&srt, &stage, Some(split.import_gate()))
893 .0
894 .expect("the srt is readable")
895 .len(),
896 1
897 );
898 // ...and a refusal is worded as a tail, never as a failed import.
899 let unread: Subs = Err("nothing to read".into());
900 assert_eq!(
901 subtitle_tail(&mut split, unread),
902 Some(" — subtitles unread: nothing to read".to_string())
903 );
904}
905
906#[test]
907fn every_codec_row_is_offered_or_says_why_not() {
908 // One row per codec, and the boxes it can go in are the container row's
909 // business: ten rows that pick (the picture ones included), two that say why they cannot. A codec
910 // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same
911 // question, and five picture rows above the fold is what the card was
912 // called unfriendly for.
913 let offered: Vec<&[Format]> = FORMATS
914 .iter()
915 .map(|&(row, ..)| row)
916 .filter(|row| !row.is_empty())
917 .collect();
918 assert_eq!(
919 offered,
920 vec![
921 &[Format::Mp4][..],
922 &[Format::Av1, Format::Av1Mp4][..],
923 &[Format::Hevc, Format::HevcMp4][..],
924 &[Format::Wav][..],
925 &[Format::Flac][..],
926 &[Format::Mp3][..],
927 &[Format::Ogg][..],
928 &[Format::Opus][..],
929 &[Format::Still, Format::PngSequence][..],
930 &[Format::Gif][..],
931 ]
932 );
933 // Every format the engine writes is on exactly one row: one the card
934 // cannot reach is one nobody can pick.
935 for format in [
936 Format::Mp4,
937 Format::Av1,
938 Format::Av1Mp4,
939 Format::Hevc,
940 Format::HevcMp4,
941 Format::Wav,
942 Format::Flac,
943 Format::Mp3,
944 Format::Ogg,
945 Format::Opus,
946 Format::Still,
947 Format::PngSequence,
948 Format::Gif,
949 ] {
950 assert_eq!(
951 FORMATS
952 .iter()
953 .filter(|(row, ..)| row.contains(&format))
954 .count(),
955 1,
956 "{format:?}"
957 );
958 }
959 // The boxes the container row offers, and what the extension of each is
960 // -- the destination follows the format, so these are what a file gets
961 // named with.
962 assert_eq!(containers(Format::Av1), [Format::Av1, Format::Av1Mp4]);
963 assert_eq!(containers(Format::HevcMp4), [Format::Hevc, Format::HevcMp4]);
964 assert_eq!(containers(Format::Mp3), [Format::Mp3]);
965 assert_eq!(Format::Av1.ext(), "mkv");
966 assert_eq!(Format::Av1Mp4.ext(), "mp4");
967 assert_eq!(Format::Hevc.ext(), "mkv");
968 assert_eq!(Format::HevcMp4.ext(), "mp4");
969 // The container key walks the row and wraps, and does nothing at all
970 // where there is only one box -- a stroke must not invent a choice the
971 // card is not offering.
972 assert_eq!(next_container(Format::Av1), Format::Av1Mp4);
973 assert_eq!(next_container(Format::Av1Mp4), Format::Av1);
974 assert_eq!(next_container(Format::Hevc), Format::HevcMp4);
975 assert_eq!(next_container(Format::Mp4), Format::Mp4);
976 assert_eq!(next_container(Format::Wav), Format::Wav);
977 for (row, stroke, label, detail) in FORMATS {
978 assert!(!label.is_empty(), "a row with no name");
979 // A refused row is a row with a reason, never a hidden one: an
980 // empty detail column would read as an oversight.
981 assert!(!detail.is_empty(), "{label} says nothing");
982 // Every row that can be picked has a key of its own, and no row
983 // that cannot has one: the card is drivable without a pointer.
984 assert_eq!(!row.is_empty(), !stroke.is_empty(), "{label}");
985 if let Some(&first) = row.first() {
986 assert!(
987 stroke.parse::<u32>().is_err(),
988 "{label} takes a digit the bitrate needs"
989 );
990 // Every box on one row is the same codec, so the quality rows
991 // do not change meaning when the container does.
992 assert!(row.iter().all(|f| f.has_video() == first.has_video()));
993 }
994 }
995 // No two rows share a key, and none of them is a stroke the card already
996 // answers to itself -- an ambiguous key is a key that picks the wrong
997 // thing on a card that has no other input.
998 let keys: Vec<&str> = FORMATS
999 .iter()
1000 .map(|&(_, stroke, ..)| stroke)
1001 .filter(|stroke| !stroke.is_empty())
1002 .collect();
1003 for (i, key) in keys.iter().enumerate() {
1004 assert!(!keys[i + 1..].contains(key), "{key} picks two rows");
1005 assert!(
1006 !["c", "q", "d", "g", "r", "enter", "backspace", ESCAPE].contains(key),
1007 "{key} is already the card's own"
1008 );
1009 }
1010 // The codecs this program reads and cannot write are rows of their own,
1011 // refused by name rather than absent: VP9 and VP8, because AV1 is the
1012 // row that replaced them. Their reason travels with them, in the row or
1013 // the footer line that collects them -- either way it is on screen
1014 // without a click. OGG was the other one until `rusty_vorbis` gave this
1015 // project an encoder, and the row that says so is the row above.
1016 let (row, _, _, detail) = FORMATS
1017 .into_iter()
1018 .find(|(_, _, name, _)| *name == "VP9")
1019 .expect("VP9 has a row");
1020 assert!(row.is_empty(), "VP9 is not offered");
1021 assert!(detail.contains("replaces it"), "VP9: {detail}");
1022 let (row, _, _, detail) = FORMATS
1023 .into_iter()
1024 .find(|(_, _, name, _)| *name == "VP8")
1025 .expect("VP8 has a row");
1026 assert!(row.is_empty(), "VP8 is not offered");
1027 assert!(detail.contains("replaces it"), "VP8: {detail}");
1028 let (row, _, _, detail) = FORMATS
1029 .into_iter()
1030 .find(|(_, _, name, _)| *name == "Ogg")
1031 .expect("Ogg has a row");
1032 assert_eq!(row, [Format::Ogg], "Ogg is a row that picks now");
1033 assert!(
1034 detail.contains("Vorbis"),
1035 "the row names its codec in plain words: {detail}"
1036 );
1037 assert!(
1038 FORMATS
1039 .into_iter()
1040 .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra"))
1041 );
1042 // The destination follows the format and keeps the stem, mp4 included.
1043 assert_eq!(
1044 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
1045 std::path::Path::new("/a/take.export.wav")
1046 );
1047 assert_eq!(
1048 retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4),
1049 std::path::Path::new("/a/take.export.mp4")
1050 );
1051}
1052
1053/// What the budget row says about the file before it is written: the size a
1054/// rate makes over a span, in the unit the row states it in.
1055#[test]
1056fn the_budget_row_states_the_size_before_it_is_written() {
1057 // The rate as a person writes it, and the ratio one spelled out rather
1058 // than rounded to a rate nothing is written at.
1059 assert_eq!(fps_label(30.), "30");
1060 assert_eq!(fps_label(24000. / 1001.), "23.976");
1061 assert_eq!(fps_label(29.97002997), "29.97");
1062 // The lever's own readout, one decimal, in the unit it is moved in --
1063 // including below a megabit, which is where the floor lives now.
1064 assert_eq!(rate_label(6_000_000), "6.0");
1065 assert_eq!(rate_label(6_500_000), "6.5");
1066 assert_eq!(rate_label(600_000), "0.6");
1067 assert_eq!(rate_label(BPS_MIN), "0.1");
1068}
1069
1070/// Which cue is on screen when: the whole of what the overlay decides, and
1071/// the one piece of it that is arithmetic rather than layout.
1072#[test]
1073fn a_cue_is_on_screen_from_its_start_until_the_moment_it_ends() {
1074 use engine::subtitle::Cue;
1075 let cue = |start_us, end_us, text: &str| Cue {
1076 start_us,
1077 end_us,
1078 text: text.to_string(),
1079 image: None,
1080 words: Vec::new(),
1081 karaoke: Vec::new(),
1082 };
1083 // Two cues that hand over exactly, and one that overlaps the second --
1084 // a sign over a line of dialogue, which is two plates at one moment.
1085 let cues = [
1086 cue(500_000, 1_500_000, "first line"),
1087 cue(1_500_000, 2_500_000, "second line"),
1088 cue(2_000_000, 2_200_000, "a sign"),
1089 ];
1090 let at = |t: f64| -> Vec<&str> {
1091 cues_at(&cues, t)
1092 .into_iter()
1093 .map(|c| c.text.as_str())
1094 .collect()
1095 };
1096 // Before the first, between none of them: nothing, which is what makes
1097 // the overlay disappear rather than sit there empty.
1098 assert!(at(0.).is_empty());
1099 assert!(at(0.4).is_empty());
1100 assert!(at(3.).is_empty());
1101 assert_eq!(at(0.5), ["first line"], "on at its own start");
1102 assert_eq!(at(1.4), ["first line"]);
1103 // Half-open: the frame the first ends on is the second's, never both.
1104 assert_eq!(at(1.5), ["second line"]);
1105 assert_eq!(at(2.1), ["second line", "a sign"], "two at once stack");
1106 assert_eq!(at(2.2), ["second line"], "the sign is over");
1107 // ...and the end of the last one is the end of it.
1108 assert!(at(2.5).is_empty());
1109 // A negative time is before everything rather than a panic: the
1110 // playhead is clamped, but nothing here depends on that.
1111 assert!(at(-1.).is_empty());
1112}
1113
1114/// The cue plate and the transient bars share the bottom edge of the picture,
1115/// and the plate is the one that moves: a notice drawn across the line being
1116/// read costs the reader both of them.
1117#[test]
1118fn a_cue_steps_over_whatever_bar_is_hanging_off_the_picture() {
1119 // Nothing hanging there, nothing moved: people know where the line sits,
1120 // and the no-notice position is the one they know, to the pixel.
1121 assert_eq!(sub_bottom(0.), SUB_BOTTOM);
1122 // A bar of any height is a bar the plate is clear of: its bottom edge is
1123 // above the bar's top edge, with the plate's own gap still under it.
1124 for bars in [1., 26., 48., 96., 300.] {
1125 assert!(
1126 sub_bottom(bars) >= bars + SUB_BOTTOM,
1127 "a {bars} px bar reaches the plate"
1128 );
1129 }
1130 // A taller bar never lowers the plate, and a box that was never painted
1131 // (or measured as nothing) reads as no bar at all rather than as a plate
1132 // pulled off the bottom of the window.
1133 assert!(sub_bottom(48.) > sub_bottom(26.));
1134 assert_eq!(sub_bottom(-10.), SUB_BOTTOM);
1135}
1136
1137/// The two places a subtitle is drawn -- the plate over the picture and the
1138/// lanes under the tracks -- inside the 640x360 floor the rest of this window
1139/// is sized for, and the plate readable on whatever the film is showing.
1140#[test]
1141fn the_subtitle_plate_and_lanes_fit_the_smallest_window() {
1142 // A subtitle lane is a lane: it costs the panel exactly what a third
1143 // track costs it, and a timeline with none costs nothing at all -- the
1144 // strip that used to hang under the lanes is gone, and with it the one
1145 // row nothing could be dropped on.
1146 assert_eq!(lanes_h(3) - lanes_h(2), LANE_H + 8.);
1147 // What is left for the picture at the floor, with a project's two tracks
1148 // and a subtitle lane under them.
1149 let picture = 360. - HEADER_H - panel_h(3);
1150 assert!(
1151 picture > 0.,
1152 "a subtitle lane pushed the picture off the window"
1153 );
1154 // A two-line cue and the gap under it fit inside that, which is the
1155 // whole claim: the plate sits *over* the picture and must not need more
1156 // of it than there is.
1157 assert!(
1158 SUB_BOTTOM + 2. * SUB_LINE_H <= picture,
1159 "a two-line cue does not fit the smallest picture"
1160 );
1161 // The text sits on its line rather than being clipped by it.
1162 const {
1163 assert!(SUB_LINE_H >= SUB_TEXT);
1164 }
1165 // White on the plate, not chrome on chrome: a cue is read against the
1166 // film, and this is the one pair here that has to survive any picture.
1167 for id in crate::ui::theme::PaletteId::ALL {
1168 assert!(contrast(id.palette().SUB_FG, 0x000000) >= 7., "{id:?}");
1169 }
1170 // A subtitle lane is dragged onto, trimmed on and lifted from, so its row
1171 // is a target and binds `HIT_MIN` like every other lane's -- the whole
1172 // reason it is a lane and no longer a 16 px strip.
1173 const {
1174 assert!(LANE_H >= HIT_MIN);
1175 }
1176}
1177
1178/// The subtitle style file, round-tripped through a scratch config directory
1179/// -- the same corner-cut persistence as the theme and the keybindings, kept
1180/// to the same test the load/save pair earns: a save followed by a load reads
1181/// back what was written, a file that never existed leaves the defaults in
1182/// force, and a file that exists but says nothing readable does too rather
1183/// than crashing a startup on someone else's edit of the file.
1184#[test]
1185fn the_subtitle_style_file_round_trips_or_falls_back_to_defaults() {
1186 let _config_env = config_env_lock();
1187
1188 let dir = std::env::temp_dir().join(format!(
1189 "edith-subtitle-style-test-{}-{}",
1190 std::process::id(),
1191 std::time::SystemTime::now()
1192 .duration_since(std::time::UNIX_EPOCH)
1193 .unwrap()
1194 .as_nanos()
1195 ));
1196 std::fs::create_dir_all(&dir).unwrap();
1197 // The shared process environment is serialized across every config
1198 // round-trip test by `config_env_lock`.
1199 crate::keymap::set_test_config_home(Some(dir.clone()));
1200
1201 // Nothing written yet: the defaults, not a crash on a missing file.
1202 assert_eq!(load_subtitle_style(), SubStyle::default());
1203
1204 // A save, read back whole: family and size both.
1205 let iosevka = SubStyle {
1206 family: Some("Iosevka".to_string()),
1207 size: 22.,
1208 ..SubStyle::default()
1209 };
1210 save_subtitle_style(&iosevka).unwrap();
1211 assert_eq!(load_subtitle_style(), iosevka);
1212
1213 // The platform default (`None`) round-trips too, and is not a family
1214 // called "".
1215 let platform = SubStyle {
1216 size: 14.,
1217 ..SubStyle::default()
1218 };
1219 save_subtitle_style(&platform).unwrap();
1220 assert_eq!(load_subtitle_style(), platform);
1221
1222 // Every field the card can set reads back as set: outline, box and place
1223 // are not in the two-line file they grew out of, so each one has to
1224 // survive the trip on its own.
1225 let all = SubStyle {
1226 family: Some("Iosevka".to_string()),
1227 size: 26.,
1228 outline: SubOutline::Thick,
1229 boxed: false,
1230 place: SubPlace::Top,
1231 };
1232 save_subtitle_style(&all).unwrap();
1233 assert_eq!(load_subtitle_style(), all);
1234
1235 // A file present but unreadable as this format -- a stray edit, or bytes
1236 // from a future version -- leaves the defaults in force rather than
1237 // failing the window that opens over it.
1238 std::fs::write(subtitle_style_path(), "not a number\n9999\n").unwrap();
1239 assert_eq!(load_subtitle_style(), SubStyle::default());
1240
1241 // A two-line file from before the outline, box and place existed still
1242 // loads its family and size, with the look it always had for the rest.
1243 std::fs::write(subtitle_style_path(), "Iosevka\n22\n").unwrap();
1244 assert_eq!(load_subtitle_style(), iosevka);
1245
1246 // A line this build does not know keeps its default, and the lines after
1247 // it are still read: a value from a future version costs that one field.
1248 std::fs::write(subtitle_style_path(), "Iosevka\n22\nextra-bold\noff\ntop\n").unwrap();
1249 assert_eq!(
1250 load_subtitle_style(),
1251 SubStyle {
1252 boxed: false,
1253 place: SubPlace::Top,
1254 ..iosevka.clone()
1255 }
1256 );
1257
1258 crate::keymap::set_test_config_home(None);
1259 std::fs::remove_dir_all(&dir).ok();
1260}
1261
1262/// The subtitle card's pure rules: a slider position names a whole size inside
1263/// the range at both ends and between, the outline walks its three steps and
1264/// wraps, and each outline's copies sit where its width says they do.
1265#[test]
1266fn the_subtitle_card_sizes_outlines_and_offsets_are_bounded() {
1267 assert_eq!(sub_size_at(0.), SUB_SIZE_RANGE.0);
1268 assert_eq!(sub_size_at(1.), SUB_SIZE_RANGE.1);
1269 assert_eq!(sub_size_at(-3.), SUB_SIZE_RANGE.0);
1270 assert_eq!(sub_size_at(7.), SUB_SIZE_RANGE.1);
1271 assert_eq!(sub_size_at(0.5), 19.);
1272 assert_eq!(sub_size_at(0.52), 19.);
1273
1274 assert_eq!(SubOutline::None.step(1), SubOutline::Thin);
1275 assert_eq!(SubOutline::Thick.step(1), SubOutline::None);
1276 assert_eq!(SubOutline::None.step(-1), SubOutline::Thick);
1277 assert_eq!(SubOutline::Thin.step(-1), SubOutline::None);
1278
1279 assert!(SubOutline::None.offsets().is_empty());
1280 assert_eq!(SubOutline::Thin.offsets().len(), 4);
1281 assert_eq!(SubOutline::Thick.offsets().len(), 8);
1282 for outline in [SubOutline::Thin, SubOutline::Thick] {
1283 for &(dx, dy) in outline.offsets() {
1284 assert!(
1285 dx != 0. || dy != 0.,
1286 "a copy on the text itself draws nothing"
1287 );
1288 assert!(dx.abs() <= 2. && dy.abs() <= 2.);
1289 }
1290 }
1291}
1292
1293/// The auto-proxies default, round-tripped through a scratch config
1294/// directory the same way the subtitle style is above -- the door D1 wired
1295/// it through, so this is what the settings page header can now honestly
1296/// call the same claim it makes about Proxies: a project's own line always
1297/// beats this one once one is open ([`engine::edith::Document::auto_proxy`]),
1298/// but with nothing open (or nothing saved since the flip) this is what a
1299/// relaunch reads instead of the hardcoded Off.
1300#[test]
1301fn the_auto_proxies_default_round_trips_through_its_own_config_file_or_falls_back_to_off() {
1302 let _config_env = config_env_lock();
1303
1304 let dir = std::env::temp_dir().join(format!(
1305 "edith-auto-proxies-pref-test-{}-{}",
1306 std::process::id(),
1307 std::time::SystemTime::now()
1308 .duration_since(std::time::UNIX_EPOCH)
1309 .unwrap()
1310 .as_nanos()
1311 ));
1312 std::fs::create_dir_all(&dir).unwrap();
1313 // `config_env_lock` serializes every test that changes this process-wide
1314 // path.
1315 crate::keymap::set_test_config_home(Some(dir.clone()));
1316
1317 // Nothing written yet: Off, the default.
1318 assert!(!load_auto_proxies_pref(), "a missing file must read as Off");
1319
1320 save_auto_proxies_pref(false).unwrap();
1321 assert!(!load_auto_proxies_pref(), "off must round-trip");
1322
1323 save_auto_proxies_pref(true).unwrap();
1324 assert!(
1325 load_auto_proxies_pref(),
1326 "on must round-trip too, not just off"
1327 );
1328
1329 // Garbled bytes -- a stray edit, or a future dialect -- read as Off rather
1330 // than failing a startup on someone else's edit of the file.
1331 std::fs::write(auto_proxies_pref_path(), "not on or off\n").unwrap();
1332 assert!(
1333 !load_auto_proxies_pref(),
1334 "unreadable content must fall back to Off"
1335 );
1336
1337 crate::keymap::set_test_config_home(None);
1338 std::fs::remove_dir_all(&dir).ok();
1339}
1340
1341/// The cue's line height scales with its size, on the same ratio the defaults
1342/// draw at -- a bigger plate wants more room per line, not letters growing
1343/// inside an unchanged one.
1344#[test]
1345fn the_cue_line_height_scales_with_its_size() {
1346 assert_eq!(sub_line_h_for(SUB_TEXT), SUB_LINE_H);
1347 // Twice the size is twice the line height, on the same ratio.
1348 assert_eq!(sub_line_h_for(SUB_TEXT * 2.), SUB_LINE_H * 2.);
1349 // Always at least the text itself, across the whole size range: a line
1350 // shorter than its own text would clip it.
1351 for size in [SUB_SIZE_RANGE.0, SUB_TEXT, SUB_SIZE_RANGE.1] {
1352 assert!(sub_line_h_for(size) >= size);
1353 }
1354}
1355
1356/// The two doors subtitles arrive through, end to end on the fixtures: a
1357/// file beside the media and the tracks inside an mkv, what the overlay then
1358/// says at a given moment, and where the strip draws it.
1359#[test]
1360fn subtitles_arrive_beside_the_media_and_inside_it() {
1361 // Which door a path goes through is decided before anything is opened.
1362 // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has
1363 // no source in it to import, so the drop door has to send it where `+ S`
1364 // sends it. Its two siblings are media and must not come here -- a
1365 // `.mka` is a song this would stop importing.
1366 for name in [
1367 "subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS",
1368 ] {
1369 assert!(is_subtitle(Path::new(name)), "{name}");
1370 }
1371 for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] {
1372 assert!(!is_subtitle(Path::new(name)), "{name}");
1373 }
1374 // Every container the engine can walk for tracks inside it, Matroska
1375 // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it.
1376 // The Matroska half is the engine's own closed set, extension for
1377 // extension, so no file is walked here that it would refuse there.
1378 for name in [
1379 "film.MKV",
1380 "clip.webm",
1381 "clip.mp4",
1382 "a.m4v",
1383 "a.MOV",
1384 "song.mka",
1385 "s.mks",
1386 "f.MK3D",
1387 ] {
1388 assert!(carries_subtitles(Path::new(name)), "{name}");
1389 assert!(
1390 engine::demux::is_matroska(Path::new(name))
1391 || matches!(
1392 Path::new(name)
1393 .extension()
1394 .and_then(|e| e.to_str())
1395 .map(str::to_ascii_lowercase)
1396 .as_deref(),
1397 Some("mp4" | "m4v" | "mov")
1398 ),
1399 "{name} is walked by the app but not by the engine"
1400 );
1401 }
1402 for name in ["song.wav", "still.png", "notes.txt", "a"] {
1403 assert!(!carries_subtitles(Path::new(name)), "{name}");
1404 }
1405 // The three doors, on the one file that used to split them: what the
1406 // drop/argv door does with it ([`Player::take_import`] routes on
1407 // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and
1408 // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are
1409 // the same walk of the same bytes.
1410 let mks = asset("test_subs.mks");
1411 assert!(is_subtitle(&mks), "the drop door takes it as subtitles");
1412 let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it");
1413 let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it");
1414 assert!(!dropped.is_empty(), "and there are tracks in it");
1415 assert_eq!(
1416 dropped.iter().map(|t| &t.label).collect::<Vec<_>>(),
1417 plus_s.iter().map(|t| &t.label).collect::<Vec<_>>(),
1418 );
1419
1420 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1421 session.set_gain(0.0);
1422 // Beside the media: the drop door's own call, and the row it makes.
1423 let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
1424 .join("../engine/tests/data/test_subs.srt")
1425 .canonicalize()
1426 .expect("the subtitle fixture");
1427 assert_eq!(session.import_subtitles(&srt).expect("the .srt imports"), 1);
1428 let track = &session.subtitles()[0];
1429 assert_eq!(track.label, "test_subs.srt");
1430 assert_eq!(subtitle_detail(track), "3 cues");
1431 // Arriving is landing in the *list* and nowhere else: no lane is made for
1432 // it, so there is nothing over the picture yet -- the rule every other
1433 // medium follows here, and what `Player::subtitle_overlay` reads.
1434 assert!(
1435 session.subtitle_lanes().is_empty(),
1436 "an import places nothing: the palette is where a track lands"
1437 );
1438 // What the track itself says at a moment inside the first cue, and between
1439 // two of them -- the fixture's own timings (0.5-1.5 s, 2.0-3.25 s).
1440 let text = |t: f64| -> Vec<String> {
1441 cues_at(&track.cues, t)
1442 .into_iter()
1443 .map(|c| c.text.clone())
1444 .collect()
1445 };
1446 assert_eq!(text(0.7), ["first line"]);
1447 assert!(text(1.8).is_empty(), "between two cues the plate goes");
1448 assert_eq!(text(2.5), ["second line\nwith a break"]);
1449 // Where the strip puts that first cue: 0.5 s in at 60 px to the second
1450 // is 30 px along, and a second of cue is 60 px wide.
1451 let scale = Scale::default();
1452 assert_eq!(scale.pps, PPS_DEFAULT);
1453 assert_eq!(cue_box(scale, &track.cues[0]), (30., 60.));
1454 // Zoomed right out, a cue worth a fraction of a pixel is still a mark.
1455 let far = Scale {
1456 pps: 0.01,
1457 start: 0.,
1458 };
1459 assert_eq!(cue_box(far, &track.cues[0]).1, SUB_CUE_MIN_W);
1460 // ...and scrolled past, its left edge is negative, exactly as a clip
1461 // box's is: the bed clips it.
1462 let scrolled = Scale {
1463 pps: PPS_DEFAULT,
1464 start: 1.,
1465 };
1466 assert_eq!(cue_box(scrolled, &track.cues[0]).0, -30.);
1467
1468 // Inside the media: the tracks of an mkv, taken by the same call every
1469 // open and import door makes. Two of them in the fixture, named by what
1470 // the file says rather than by number.
1471 let notice =
1472 subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries two");
1473 assert!(notice.contains('2'), "{notice}");
1474 assert_eq!(session.subtitles().len(), 3);
1475 assert_eq!(session.subtitles()[1].label, "eng");
1476 assert_eq!(session.subtitles()[2].label, "fra — Signs");
1477 assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues");
1478 // The same file twice adds nothing and says nothing.
1479 assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None);
1480 // An mp4 is walked too (it can carry `tx3g`); this one holds none, so
1481 // the notice grows no tail.
1482 assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None);
1483
1484 // A track that could not be read says why, where its cue count would
1485 // be: what the greyed library row prints, and the whole difference
1486 // between "this film has no subtitles" and "these four are pictures".
1487 let refused = engine::subtitle::SubtitleTrack {
1488 path: PathBuf::from("/a/remux.mkv"),
1489 track: Some(1),
1490 // Neither field, like `SubtitleTrack::refused` leaves them: what is
1491 // refused is never written, and the row keeps the label it was
1492 // refused under.
1493 language: String::new(),
1494 name: String::new(),
1495 label: "eng".into(),
1496 cues: Vec::new(),
1497 bitmap: false,
1498 refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()),
1499 };
1500 assert!(subtitle_detail(&refused).contains("pictures"));
1501 assert!(cues_at(&refused.cues, 1.).is_empty());
1502
1503 // ...and what an embedded track carried through a *cut* maps to: the timeline's
1504 // own clock, asked of the engine through the very map an export writes
1505 // the file with (`PlaybackSession::timeline_cues`), so the preview and
1506 // the file cannot drift apart. The numbers are the export's own
1507 // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_
1508 // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves
1509 // three seconds, which clips the second cue and takes the third away
1510 // altogether -- while the track itself still holds all three, which is
1511 // exactly why the drawing may not read them straight.
1512 let lanes = session.lanes();
1513 session
1514 .cut_regions(&[(15, 60)], &lanes)
1515 .expect("cut 0.5s..2.5s out");
1516 assert_eq!(session.timeline_duration(), 3.0);
1517 assert_eq!(
1518 session.subtitles()[0].cues.len(),
1519 3,
1520 "the track is untouched"
1521 );
1522 let mapped = session.timeline_cues(0);
1523 assert_eq!(
1524 mapped
1525 .iter()
1526 .map(|c| (c.start_us, c.end_us))
1527 .collect::<Vec<_>>(),
1528 vec![(500_000, 1_500_000), (2_000_000, 3_000_000)]
1529 );
1530 // The export's own two lines, at the same moments as above.
1531 let drawn = |t: f64| -> Vec<String> {
1532 cues_at(&mapped, t)
1533 .into_iter()
1534 .map(|c| c.text.clone())
1535 .collect()
1536 };
1537 assert_eq!(drawn(0.7), ["first line"]);
1538 assert_eq!(drawn(2.5), ["second line\nwith a break"]);
1539 assert!(
1540 drawn(4.2).is_empty(),
1541 "a cue past the cut end is drawn where the file writes none"
1542 );
1543 // ...and the strip's: the second cue is one second wide now, not 1.25.
1544 assert_eq!(cue_box(scale, &mapped[1]), (120., 60.));
1545
1546 // The last mile, what the plate over the picture actually reads
1547 // (`Player::subtitle_overlay` -> `PlaybackSession::sub_lane_cues`): a lane
1548 // added and still empty draws nothing, and the palette row reaches the
1549 // screen the moment it is *placed* on it -- shifted by where it sits, the
1550 // way a clip is.
1551 let lane = session.add_lane(LaneKind::Subtitle);
1552 assert!(
1553 session.sub_lane_cues(lane).is_empty(),
1554 "an empty subtitle lane draws nothing"
1555 );
1556 session
1557 .place_sub(
1558 lane,
1559 0,
1560 SubClip {
1561 start: 0,
1562 frames: 90,
1563 track: 0,
1564 in_us: 0,
1565 out_us: 5_000_000,
1566 link: None,
1567 },
1568 )
1569 .expect("the palette row goes down on the lane");
1570 let placed = session.sub_lane_cues(lane);
1571 let shown = |t: f64| -> Vec<String> {
1572 cues_at(&placed, t)
1573 .into_iter()
1574 .map(|c| c.text.clone())
1575 .collect()
1576 };
1577 // The placement holds five seconds of the track in a three-second box,
1578 // so the words cross the plate by the placement's own proportion: the
1579 // cue times compress with it (first line [0.5, 1.5) -> [0.3, 0.9),
1580 // second [2, 3.25) -> [1.2, 1.95)) -- a unity placement would keep the
1581 // file's own times, to the microsecond.
1582 assert_eq!(shown(0.7), ["first line"]);
1583 assert!(shown(0.95).is_empty(), "between two cues the plate goes");
1584 assert_eq!(shown(1.5), ["second line\nwith a break"]);
1585}
1586
1587/// One lane over the picture and never two ([`Player::active_sub_lane`]): which
1588/// one, at every moment a stack of subtitle lanes goes through -- none, one,
1589/// three, a pick, and the pick's lane going away under it.
1590#[test]
1591fn exactly_one_subtitle_lane_is_shown_whatever_the_pick_and_whatever_is_left() {
1592 let sub = |ord| Lane::new(LaneKind::Subtitle, ord);
1593 let (s1, s2, s3) = (sub(0), sub(1), sub(2));
1594 // Nowhere for words to be: no lane, nothing shown -- and a pick left over
1595 // from a timeline that has been closed does not resurrect one.
1596 assert_eq!(active_lane(None, &[]), None);
1597 assert_eq!(active_lane(Some(s2), &[]), None);
1598 // One lane is shown by being the only one: nobody has to pick anything,
1599 // which is what the single-lane timeline always did.
1600 assert_eq!(active_lane(None, &[s1]), Some(s1));
1601 // Three, unpicked: the first, so adding lanes never blanks the picture.
1602 assert_eq!(active_lane(None, &[s1, s2, s3]), Some(s1));
1603 // ...and picked: that one alone, however many are there.
1604 assert_eq!(active_lane(Some(s3), &[s1, s2, s3]), Some(s3));
1605 // The picked lane taken off the timeline -- a removal, or the undo of the
1606 // add that made it: the first lane left is shown, never nothing.
1607 assert_eq!(active_lane(Some(s3), &[s1, s2]), Some(s1));
1608 // A pick that is not a subtitle lane at all cannot name one either.
1609 assert_eq!(active_lane(Some(Lane::V1), &[s1, s2]), Some(s1));
1610}
1611
1612/// A library preview's whole point ([`Player::open_preview`],
1613/// [`Player::close_preview`]): the timeline's own session is untouched by
1614/// one showing over it. `Player` cannot be built here -- it takes a gpui
1615/// `Context`, which this test binary has no `TestAppContext` to hand it
1616/// (see the crate's other tests for the same limit) -- so this exercises
1617/// the two sessions `open_preview`/`close_preview` juggle directly: seeking
1618/// and playing one, exactly as a preview session's own life does, leaves
1619/// the other's position and clock exactly where they were.
1620#[test]
1621fn a_second_session_playing_never_moves_the_first() {
1622 let mut timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1623 timeline.seek(0.5);
1624 let before = timeline.now();
1625 let before_playing = timeline.is_playing();
1626
1627 // Stands in for the preview session `open_preview` opens over it.
1628 let mut preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1629 preview.seek(1.0);
1630 preview.play();
1631
1632 assert_eq!(
1633 timeline.now(),
1634 before,
1635 "the preview's seek moved the wrong session"
1636 );
1637 assert_eq!(
1638 timeline.is_playing(),
1639 before_playing,
1640 "the preview's play moved the wrong session"
1641 );
1642}
1643
1644/// The frozen-preview regression: `render` used to call `tick` on
1645/// `self.session` unconditionally, so a preview session's clock -- the one
1646/// [`Player::pump`] actually reads while previewing -- was never advanced
1647/// and the picture sat on frame 0 forever. The fix routes `tick` through
1648/// [`Player::active_session_mut`], the same preview-first precedence
1649/// `pump`/`transport` already use. This proves `tick` is what a session
1650/// needs to keep its own clock honest, and that ticking one session leaves
1651/// an untouched sibling exactly where it was -- so routing it through
1652/// whichever session is active cannot disturb the other one.
1653#[test]
1654fn ticking_the_preview_session_never_moves_the_timeline() {
1655 let mut timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1656 timeline.seek(0.5);
1657 let before = timeline.now();
1658
1659 let mut preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1660 preview.play();
1661 // Stands in for what `render` now does every frame while a preview is
1662 // showing: only the active session -- the preview -- gets ticked.
1663 preview.tick();
1664
1665 assert_eq!(
1666 timeline.now(),
1667 before,
1668 "ticking the preview moved the timeline's clock"
1669 );
1670}
1671
1672/// The monitoring level is the *window's*, and a preview closing must not hand
1673/// the timeline back the level it had before the preview opened: muting during
1674/// a preview and pressing `esc` used to leave the timeline playing at full
1675/// volume with the control still reading "muted" -- the shown level and the
1676/// heard level disagreed and nothing said so.
1677///
1678/// What is driven is the real push, [`push_gain`] -- the function
1679/// [`apply_volume`](crate::player::transport::Player::apply_volume) is nothing
1680/// but a call to, over the same two session slots a `Player` holds -- and the
1681/// answer is read back out of the *device* ([`PlaybackSession::gain`]), not
1682/// out of the window. `Player` itself cannot be built here (it takes a gpui
1683/// `Context` this binary has no `TestAppContext` to build; the sibling preview
1684/// tests say the same), so the door that calls the push is pinned by the scan
1685/// below rather than executed.
1686#[test]
1687fn a_preview_close_leaves_the_timeline_at_the_level_the_window_shows() {
1688 let timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1689 // The control: an untouched session is at full volume, so a level read back
1690 // as 1.0 is a real answer and not a default this test could pass on.
1691 assert_eq!(
1692 timeline.gain(),
1693 Some(1.0),
1694 "a fresh session is not at full volume"
1695 );
1696
1697 // Stands in for `open_preview`: a second session arrives, and the window is
1698 // muted while it is the one on screen.
1699 let preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1700 let muted = 0.0;
1701 push_gain(muted, [Some(&timeline), Some(&preview)]);
1702
1703 // The preview goes away -- `close_preview` takes it and pushes at what is
1704 // left. The session that takes the picture must be the session heard at
1705 // the level the control shows.
1706 drop(preview);
1707 push_gain(muted, [Some(&timeline), None]);
1708 assert_eq!(
1709 timeline.gain(),
1710 Some(muted),
1711 "closing a preview handed the timeline back a level the window is not showing"
1712 );
1713
1714 // The other half of the regression, and the half a single-session test can
1715 // never see: a push that reached only the *active* session (the preview)
1716 // left the timeline exactly where it was, which is the reported bug. The
1717 // pre-fix shape is therefore the control that makes the assertion above
1718 // mean something.
1719 let control = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1720 let other = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1721 push_gain(muted, [Some(&other), None]);
1722 assert_eq!(
1723 control.gain(),
1724 Some(1.0),
1725 "a session outside the push followed it, so the read above proves nothing"
1726 );
1727 assert_eq!(
1728 other.gain(),
1729 Some(muted),
1730 "the pushed session ignored the level"
1731 );
1732}
1733
1734/// The wiring the round trip above cannot build a `Player` for: the level
1735/// reaches *both* session slots, and both doors that install or drop a session
1736/// push it. A push at the active session alone is the regression, and it is
1737/// invisible to any test that only ever holds one session.
1738#[test]
1739fn the_window_level_is_pushed_at_every_session_and_on_every_swap() {
1740 let apply = fn_body("apply_volume");
1741 assert!(
1742 apply.contains("self.session.as_ref()") && apply.contains("self.preview_session.as_ref()"),
1743 "the level is pushed at one session only, so a preview closing hands the \
1744 timeline back the level from before the preview opened"
1745 );
1746 assert!(
1747 !apply.contains("self.active_session()"),
1748 "the push still goes through the active session, which is the one-session \
1749 rule this replaced"
1750 );
1751 for door in ["open_preview", "close_preview"] {
1752 assert!(
1753 fn_body(door).contains("self.apply_volume();"),
1754 "{door} swaps the session on screen without telling the new one what \
1755 level the window is showing"
1756 );
1757 }
1758}
1759
1760/// [`bgra_to_rgba`] and [`save_screenshot`]'s own PNG write, round-tripped: a
1761/// synthetic 2x2 frame -- one pixel per corner, alpha and channel order all
1762/// distinct -- decodes back to the same pixels a viewer would see, in RGBA.
1763#[test]
1764fn a_screenshot_frame_round_trips_through_its_png() {
1765 // BGRA, gpui's own layout: red top-left, green top-right, blue
1766 // bottom-left, and a half-alpha white bottom-right.
1767 #[rustfmt::skip]
1768 let bgra: Vec<u8> = vec![
1769 0, 0, 255, 255, 0, 255, 0, 255,
1770 255, 0, 0, 255, 255, 255, 255, 128,
1771 ];
1772 let rgba = bgra_to_rgba(&bgra);
1773 assert_eq!(
1774 rgba[0..4],
1775 [255, 0, 0, 255],
1776 "red survives the channel swap"
1777 );
1778 assert_eq!(rgba[4..8], [0, 255, 0, 255], "green is unmoved by the swap");
1779 assert_eq!(rgba[8..12], [0, 0, 255, 255], "blue swaps into place");
1780 assert_eq!(rgba[12..16], [255, 255, 255, 128], "alpha is untouched");
1781
1782 let dir = std::env::temp_dir().join(format!("edith-screenshot-test-{}", std::process::id()));
1783 std::fs::create_dir_all(&dir).expect("scratch dir");
1784 let path = dir.join("roundtrip.png");
1785 // Written by the screenshot's own encoder and read back by `image`, an
1786 // independent decoder, so the round trip crosses both crates.
1787 let png = ec_image::png_encode::encode_rgba8(2, 2, &rgba).expect("2x2 rgba png");
1788 std::fs::write(&path, png).expect("png write");
1789 let decoded = image::open(&path).expect("png read").to_rgba8();
1790 assert_eq!(
1791 decoded.into_raw(),
1792 rgba,
1793 "the PNG round-trips the pixels exactly"
1794 );
1795 let _ = std::fs::remove_dir_all(&dir);
1796}
1797
1798/// [`screenshot_path`]'s no-clobber rule: the same stem and timecode taken
1799/// twice in a row lands on `-2`, and a third time on `-3` -- a screenshot
1800/// never overwrites the one before it, unlike an export's own path.
1801#[test]
1802fn a_repeated_screenshot_name_gets_a_numeric_suffix() {
1803 let dir = std::env::temp_dir().join(format!("edith-screenshot-suffix-{}", std::process::id()));
1804 std::fs::create_dir_all(&dir).expect("scratch dir");
1805
1806 let first = screenshot_path(&dir, "A Film", "00-01-02");
1807 assert_eq!(first, dir.join("A Film-00-01-02.png"));
1808 std::fs::write(&first, b"stand-in for a PNG").expect("write the first");
1809
1810 let second = screenshot_path(&dir, "A Film", "00-01-02");
1811 assert_eq!(second, dir.join("A Film-00-01-02-2.png"));
1812 std::fs::write(&second, b"stand-in for a PNG").expect("write the second");
1813
1814 let third = screenshot_path(&dir, "A Film", "00-01-02");
1815 assert_eq!(third, dir.join("A Film-00-01-02-3.png"));
1816
1817 // A different timecode never collides with either of the above.
1818 let elsewhere = screenshot_path(&dir, "A Film", "00-01-03");
1819 assert_eq!(elsewhere, dir.join("A Film-00-01-03.png"));
1820
1821 let _ = std::fs::remove_dir_all(&dir);
1822}
1823
1824/// A first import lands on an empty timeline and fits it; a later one only
1825/// joins the library, and a Media row's double-click adds at the playhead
1826/// rather than previewing. Read from the sources because this binary has no
1827/// `TestAppContext` to drive the window (see `darkroom_source_rows_keep_...`).
1828#[test]
1829fn the_first_import_lands_and_fits_and_a_row_double_click_adds_at_the_playhead() {
1830 let library = src_text("player/library.rs");
1831 let take = &library[library.find("fn take_import(").expect("take_import")..];
1832 for needle in [
1833 "self.insert_source(path, 0, None, None, cx);",
1834 "self.zoom_fit(cx);",
1835 ] {
1836 assert!(
1837 take.contains(needle),
1838 "the first import lost `{needle}`: an empty timeline must take the file"
1839 );
1840 }
1841 let dock = src_text("ui/dock_stance.rs");
1842 let row = &dock[dock.find("fn source_gestures(").expect("Darkroom source gestures")..];
1843 assert!(
1844 row.contains("this.open_preview(&click_path, stream, cx);"),
1845 "a Media row's double-click opens the source viewer"
1846 );
1847}
1848
1849/// The time estimate is always "about", in seconds under a minute and a half
1850/// and in minutes after, and a faster machine writes the same film sooner.
1851#[test]
1852fn the_write_time_is_about_and_follows_the_pace() {
1853 use crate::export_ui::time_words;
1854 assert_eq!(time_words(60., Some(1.)), "about 60 s");
1855 assert_eq!(time_words(600., Some(1.)), "about 10 min");
1856 assert_eq!(time_words(600., Some(4.)), "about 2 min 30 s");
1857 assert_eq!(time_words(100., Some(1.)), "about 1 min 40 s");
1858 // Never a fake "0 s", and no number at all before a pace was measured.
1859 assert_eq!(time_words(0., Some(1.)), "about 1 s");
1860 assert_eq!(time_words(60., None), "estimating\u{2026}");
1861}
1862
1863/// The playback plate draws a non-plain caption style with the engine's own
1864/// burn function, so the word being spoken moves with the playhead: two frames
1865/// inside one karaoke cue are two different pictures, a held pose is the same
1866/// key (no redrawing), and the default style is not routed through it at all.
1867#[test]
1868fn the_plate_draws_the_animated_caption_and_it_changes_inside_one_cue() {
1869 use engine::captionanim::{CaptionAnim, CaptionStyle};
1870 use engine::subtitle::Cue;
1871 let fps = 25.0;
1872 let cue = Cue {
1873 start_us: 1_000_000,
1874 end_us: 3_000_000,
1875 text: "one two three four".to_string(),
1876 image: None,
1877 karaoke: Vec::new(),
1878 // Uneven on purpose: "three" owns most of the cue.
1879 words: vec![
1880 (1_000_000, 1_200_000, "one".into()),
1881 (1_200_000, 1_400_000, "two".into()),
1882 (1_400_000, 2_800_000, "three".into()),
1883 (2_800_000, 3_000_000, "four".into()),
1884 ],
1885 };
1886 let cues = [cue];
1887 let karaoke = engine::text::TextStyle {
1888 caption: CaptionStyle { anim: CaptionAnim::Karaoke, ..CaptionStyle::default() },
1889 ..engine::text::TextStyle::default()
1890 };
1891 let draw = |style: &engine::text::TextStyle, secs: f64| {
1892 let frame = crate::subs::frame_at(secs, fps);
1893 let (key, blocks) = crate::subs::animated_caption_key(style, &cues, frame, fps)?;
1894 let (w, h, px) = crate::subs::animated_caption_bitmap(style, &blocks, (1280, 720))?;
1895 assert_eq!((w, h), (960, 540), "the canvas keeps the project's shape");
1896 assert!(px.as_chunks::<4>().0.iter().any(|p| p[3] > 0), "the caption drew something");
1897 Some((key, px))
1898 };
1899 let early = draw(&karaoke, 1.1).expect("a cue is up at 1.1 s");
1900 let late = draw(&karaoke, 2.0).expect("a cue is up at 2.0 s");
1901 assert_ne!(early.0, late.0, "the word being spoken changed, so did the key");
1902 assert_ne!(early.1, late.1, "and so did the picture");
1903 let held = draw(&karaoke, 2.1).expect("up");
1904 assert_eq!(late.0, held.0, "the same word is the same key: a held pose is not redrawn");
1905 assert_eq!(late.1, held.1);
1906 assert!(crate::subs::cues_at(&cues, 3.5).is_empty(), "nothing is handed over between cues");
1907}