forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

subs.rs1093 lines, 47.9 KiBHistoryRawDownload
1//! Subtitles: what is parsed, what is listed and what is drawn.
2
3use crate::*;
4
5/// One press of the size stepper, and how far it may be pushed: below
6/// [`SUB_SIZE_RANGE`].0 a plate is unreadable, above its top it eats the
7/// smallest picture the layout floor promises ([`the_subtitle_plate_and_lanes_fit_the_smallest_window`]).
8pub(crate) const SUB_SIZE_STEP: f32 = 1.;
9pub(crate) const SUB_SIZE_RANGE: (f32, f32) = (10., 28.);
10
11/// The cue's line height at `size`, on the ratio the defaults draw at
12/// ([`SUB_LINE_H`] over [`SUB_TEXT`]): a bigger cue wants a taller line, not
13/// just bigger letters on the old one.
14pub(crate) fn sub_line_h_for(size: f32) -> f32 {
15 size * SUB_LINE_H / SUB_TEXT
16}
17
18/// Where the subtitle style survives: beside the keybindings and the theme,
19/// same corner-cut persistence -- a torn write costs the style and nothing
20/// else, and [`load_subtitle_style`] falls back to the defaults on one.
21pub(crate) fn subtitle_style_path() -> PathBuf {
22 crate::keymap::Keymap::config_path().with_file_name("subtitle-style")
23}
24
25/// The outline a cue's text is drawn with. gpui has no text stroke, so an
26/// outline is copies of the text behind it, each one offset by a step of
27/// [`Self::offsets`].
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub(crate) enum SubOutline {
30 #[default]
31 None,
32 Thin,
33 Thick,
34}
35
36impl SubOutline {
37 /// Where the copies sit, in px off the text: the four diagonals for thin,
38 /// the eight around it for thick.
39 pub(crate) fn offsets(self) -> &'static [(f32, f32)] {
40 match self {
41 Self::None => &[],
42 Self::Thin => &[(-1., -1.), (1., -1.), (-1., 1.), (1., 1.)],
43 Self::Thick => &[
44 (-2., 0.),
45 (2., 0.),
46 (0., -2.),
47 (0., 2.),
48 (-2., -2.),
49 (2., -2.),
50 (-2., 2.),
51 (2., 2.),
52 ],
53 }
54 }
55
56 /// The next outline `dir` steps along None, Thin, Thick, wrapping at the
57 /// ends: the keyboard walks the chips the way a stepper walks a size.
58 pub(crate) fn step(self, dir: i32) -> Self {
59 const ALL: [SubOutline; 3] = [SubOutline::None, SubOutline::Thin, SubOutline::Thick];
60 let at = ALL.iter().position(|o| *o == self).unwrap_or(0) as i32;
61 ALL[(at + dir).rem_euclid(ALL.len() as i32) as usize]
62 }
63
64 fn word(self) -> &'static str {
65 match self {
66 Self::None => "none",
67 Self::Thin => "thin",
68 Self::Thick => "thick",
69 }
70 }
71
72 fn parse(word: &str) -> Option<Self> {
73 [Self::None, Self::Thin, Self::Thick]
74 .into_iter()
75 .find(|o| o.word() == word)
76 }
77}
78
79/// Where the cue plate sits: over the bottom of the picture, the default, or
80/// over its top -- for a picture whose bottom is someone else's lower third.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub(crate) enum SubPlace {
83 #[default]
84 Bottom,
85 Top,
86}
87
88impl SubPlace {
89 fn word(self) -> &'static str {
90 match self {
91 Self::Bottom => "bottom",
92 Self::Top => "top",
93 }
94 }
95
96 fn parse(word: &str) -> Option<Self> {
97 [Self::Bottom, Self::Top]
98 .into_iter()
99 .find(|p| p.word() == word)
100 }
101}
102
103/// Everything the cue plate is drawn with, the app-wide look the subtitle
104/// style card edits. The defaults are the look the plate always had.
105#[derive(Clone, Debug, PartialEq)]
106pub(crate) struct SubStyle {
107 /// `None` is the platform's own choice, and calls no font at all.
108 pub(crate) family: Option<String>,
109 pub(crate) size: f32,
110 pub(crate) outline: SubOutline,
111 /// The dark box behind the text.
112 pub(crate) boxed: bool,
113 pub(crate) place: SubPlace,
114}
115
116impl Default for SubStyle {
117 fn default() -> Self {
118 Self {
119 family: None,
120 size: SUB_TEXT,
121 outline: SubOutline::None,
122 boxed: true,
123 place: SubPlace::Bottom,
124 }
125 }
126}
127
128/// The card's rows in the order the arrow keys walk them. Row 0 is the size
129/// slider, the three chip rows follow it, then the platform default, then one
130/// row per family in `Player::subtitle_fonts`, from [`SUB_ROW_FIRST_FAMILY`].
131pub(crate) const SUB_ROW_SIZE: usize = 0;
132pub(crate) const SUB_ROW_OUTLINE: usize = 1;
133pub(crate) const SUB_ROW_BOX: usize = 2;
134pub(crate) const SUB_ROW_PLACE: usize = 3;
135/// The caption animation rows edit the project's caption style (what a burn draws), not the
136/// app-wide plate: the animation, the highlight colour, the highlight box, capitals and the
137/// words on screen at once.
138pub(crate) const SUB_ROW_ANIM: usize = 4;
139pub(crate) const SUB_ROW_HIGHLIGHT: usize = 5;
140pub(crate) const SUB_ROW_HL_BOX: usize = 6;
141pub(crate) const SUB_ROW_UPPERCASE: usize = 7;
142pub(crate) const SUB_ROW_WORDS: usize = 8;
143pub(crate) const SUB_ROW_DEFAULT: usize = 9;
144pub(crate) const SUB_ROW_FIRST_FAMILY: usize = 10;
145
146/// The highlight colours the card offers, by name.
147pub(crate) const HIGHLIGHT_SWATCHES: [(&str, [u8; 3]); 6] = [
148 ("Yellow", [255, 214, 0]),
149 ("Green", [57, 224, 100]),
150 ("Cyan", [0, 214, 255]),
151 ("Pink", [255, 64, 160]),
152 ("Red", [255, 64, 48]),
153 ("White", [255, 255, 255]),
154];
155
156/// The size a slider position names: the range's own span, whole pixels, so
157/// a drag lands on the sizes the stepper and the file both use.
158pub(crate) fn sub_size_at(along: f32) -> f32 {
159 let (lo, hi) = SUB_SIZE_RANGE;
160 (lo + along.clamp(0., 1.) * (hi - lo)).round().clamp(lo, hi)
161}
162
163/// Lines: the family (empty for the system default), the size, then the
164/// outline, the box (`on` or `off`) and the place. A file older than the
165/// outline, box and place has only the first two, and a line this build does
166/// not know keeps its default -- so an old style still loads, and a new one
167/// loads in an old build as the size it always was.
168/// Anything unreadable, missing or out of range leaves the defaults in
169/// force -- a subtitle style file is not the user's work, so a bad one is
170/// worth no message at startup, exactly as [`ui::theme::load`].
171pub(crate) fn load_subtitle_style() -> SubStyle {
172 let defaults = SubStyle::default();
173 let Ok(text) = std::fs::read_to_string(subtitle_style_path()) else {
174 return defaults;
175 };
176 let mut lines = text.lines();
177 let family = lines.next().filter(|l| !l.is_empty()).map(str::to_string);
178 // A size this format could not have written means the file is not this
179 // format at all -- the family line is then noise too, not a font.
180 let Some(size) = lines
181 .next()
182 .and_then(|l| l.trim().parse::<f32>().ok())
183 .filter(|s| (SUB_SIZE_RANGE.0..=SUB_SIZE_RANGE.1).contains(s))
184 else {
185 return defaults;
186 };
187 let outline = lines
188 .next()
189 .and_then(|l| SubOutline::parse(l.trim()))
190 .unwrap_or(defaults.outline);
191 let boxed = lines.next().is_none_or(|l| l.trim() != "off");
192 let place = lines
193 .next()
194 .and_then(|l| SubPlace::parse(l.trim()))
195 .unwrap_or(defaults.place);
196 SubStyle {
197 family,
198 size,
199 outline,
200 boxed,
201 place,
202 }
203}
204
205/// Writes the style whole, the way [`ui::theme::save`] writes the palette.
206pub(crate) fn save_subtitle_style(style: &SubStyle) -> std::io::Result<()> {
207 let path = subtitle_style_path();
208 if let Some(dir) = path.parent() {
209 std::fs::create_dir_all(dir)?;
210 }
211 let boxed = if style.boxed { "on" } else { "off" };
212 std::fs::write(
213 path,
214 format!(
215 "{}\n{}\n{}\n{boxed}\n{}\n",
216 style.family.as_deref().unwrap_or(""),
217 style.size,
218 style.outline.word(),
219 style.place.word(),
220 ),
221 )
222}
223
224/// Whether a dropped or named path is a subtitle file rather than media: the
225/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s
226/// reason -- the import door has to know which of the engine's two doors a file
227/// goes through before anything is opened.
228///
229/// `.mks` is one of them, and it is the only Matroska extension that is: it is
230/// the *subtitles alone*, so there is no source in it to import and a drop of
231/// one used to be refused for having no video track -- while `+ S` on the same
232/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska).
233/// The other two are media and stay media: `.mka` is the sound alone, which
234/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both
235/// may *carry* subtitles, which is [`carries_subtitles`] and not this.
236pub(crate) fn is_subtitle(path: &std::path::Path) -> bool {
237 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
238 matches!(
239 e.to_ascii_lowercase().as_str(),
240 "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks"
241 )
242 })
243}
244
245/// Whether a media path is a container that can carry subtitle tracks *inside*
246/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list
247/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g`
248/// alike). Named for what it gates and not for one of the two families, because
249/// an mp4 answers `true` here now.
250///
251/// Matroska's set is the standard's own and closed by it
252/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to
253/// the two that carry a film: a `.mk3d` opened as media has its tracks walked
254/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix
255/// wider than the engine's would be a file taken here and refused deeper down.
256pub(crate) fn carries_subtitles(path: &std::path::Path) -> bool {
257 path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
258 matches!(
259 e.to_ascii_lowercase().as_str(),
260 "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov" | "ts" | "m2ts" | "mts" | "m2t"
261 )
262 })
263}
264
265/// What a worker hands back, which is the fork [`arrival`] made when it was
266/// started. An import is *read* and thrown away; the file argv named is opened
267/// outright, because nothing else is going to open it afterwards.
268pub(crate) enum Landed {
269 /// An import into a timeline that is up: the container probed and the
270 /// subtitle tracks walked, both *kept* -- they are the expensive halves and
271 /// the worker is where they belong, so [`Player::take_import`] is left with
272 /// two pushes ([`engine::PlaybackSession::import_probed`],
273 /// [`subtitle_tail`]).
274 Read(Subs, Probe),
275 /// A whole timeline the worker opened, with the tail its subtitle tracks
276 /// earn, ready to be hung off the window -- or the engine's refusal. `true`
277 /// is the media argv named, which *becomes* the timeline; `false` is a file
278 /// arriving at a window that had none, which fills the library and leaves
279 /// the lanes empty for a drag ([`Player::install_media`]).
280 Media(Result<(PlaybackSession, String), String>, bool),
281 /// A `.edith`, restored: argv's, and the one a drop or the Import button
282 /// brought ([`arrival`]).
283 Project(Result<PlaybackSession, String>),
284}
285
286/// What the container walk found, for [`Player::take_import`] to register, or
287/// the engine's refusal in the words it would have used on the UI thread.
288///
289/// `None` for the doors that never reach a demuxer: a song, a still and a
290/// subtitle file, whose own small reads stay where they were
291/// ([`engine::PlaybackSession::import`]).
292pub(crate) type Probe = Option<engine::Result<engine::ImportProbe>>;
293
294/// A media file opened as a session, with the subtitle tracks it carries inside
295/// it taken in the same breath -- the two reads a file costs, in the one place
296/// both doors ([`Player::open_media`] and the worker below) go through.
297///
298/// `place` is which door: a file *opened* is the timeline, one *imported* into
299/// an empty window fills the library and leaves the lanes empty for a drag.
300pub(crate) fn open_session(
301 path: &std::path::Path,
302 place: bool,
303 subs: Subs,
304) -> Result<(PlaybackSession, String), String> {
305 let opened = match place {
306 true => PlaybackSession::open(path),
307 false => PlaybackSession::open_library(path),
308 };
309 let mut session = opened.map_err(|e| e.to_string())?;
310 let tail = subtitle_tail(&mut session, subs).unwrap_or_default();
311 Ok((session, tail))
312}
313
314/// The whole of what a queued file costs, off the UI thread. An import only
315/// needs its pages warmed ([`read_ahead`]); the file argv named is *opened*
316/// here instead, and that is the difference between a warm launch paying for
317/// one header walk and paying for two -- the window is up either way.
318pub(crate) fn open_ahead(
319 what: Landing,
320 path: &std::path::Path,
321 stage: &std::sync::atomic::AtomicU8,
322 gate: Option<engine::ImportGate>,
323) -> Landed {
324 match what {
325 Landing::Import => read_ahead(path, stage, gate),
326 Landing::Project => {
327 let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());
328 Landed::Project(opened)
329 }
330 Landing::Open => open_whole(path, true, stage),
331 }
332}
333
334/// A whole timeline, opened here and handed over: the file argv named (`place`,
335/// which *is* the timeline) and a file arriving at a window with no timeline to
336/// import into, which fills the library instead. One function because they are
337/// one read -- the engine's two doors differ by which lanes come up empty
338/// ([`engine::PlaybackSession::open_library`]), not by what they walk.
339pub(crate) fn open_whole(
340 path: &std::path::Path,
341 place: bool,
342 stage: &std::sync::atomic::AtomicU8,
343) -> Landed {
344 use std::sync::atomic::Ordering::Relaxed;
345 let opened = match place {
346 true => PlaybackSession::open(path),
347 false => PlaybackSession::open_library(path),
348 };
349 // The same two stages a read reports, because they are the same two
350 // reads: the container, and then the tracks inside it.
351 stage.store(ImportStage::Subtitles as u8, Relaxed);
352 Landed::Media(
353 opened.map_err(|e| e.to_string()).map(|mut session| {
354 let subs = subtitle_notice(&mut session, path).unwrap_or_default();
355 (session, subs)
356 }),
357 place,
358 )
359}
360
361/// Reads, off the UI thread, everything the import that follows would have read
362/// -- and hands all of it over. Nothing here is a warm-up any more: the
363/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the
364/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came
365/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms
366/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue
367/// walk -- all of it here, and the window keeps painting through it.
368///
369/// `gate` is the timeline the file is checked against
370/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started
371/// because a worker cannot reach the session. `None` is a window with no
372/// timeline to import into: then there is nothing to check against and nothing
373/// to register, so the file is *opened* here instead, whole
374/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread,
375/// rather than on the one that draws.
376///
377/// The header error is carried back now rather than dropped: it is the engine's
378/// own refusal, from the only walk anybody makes, so it is worded once and shown
379/// at the landing. The subtitle refusal travels beside it for the same reason.
380///
381/// `stage` is what the line above the panel is naming while this runs.
382pub(crate) fn read_ahead(
383 path: &std::path::Path,
384 stage: &std::sync::atomic::AtomicU8,
385 gate: Option<engine::ImportGate>,
386) -> Landed {
387 use std::sync::atomic::Ordering::Relaxed;
388 stage.store(ImportStage::Header as u8, Relaxed);
389 // Nothing to import into, and nothing a subtitle file needs opened: the
390 // first opens the library itself, here; the second has no container at all.
391 let Some(gate) = gate else {
392 return match is_subtitle(path) {
393 true => Landed::Read(walk_subtitles(path), None),
394 false => open_whole(path, false, stage),
395 };
396 };
397 // The three doors an import goes through: a song is measured by its
398 // duration and a still by its header -- both the engine's own reads, warmed
399 // here and paid again at the landing, which is a header apiece -- and
400 // everything else is the container walk, which is handed over whole.
401 let probe = if engine::is_audio(path) {
402 engine::AudioSession::duration_secs(path).ok();
403 None
404 } else if engine::is_image(path) || is_subtitle(path) {
405 None
406 } else {
407 Some(PlaybackSession::probe_import(gate, path))
408 };
409 stage.store(ImportStage::Subtitles as u8, Relaxed);
410 // ...and the tracks inside it, kept.
411 Landed::Read(walk_subtitles(path), probe)
412}
413
414/// The toast's own words for a standalone audio import -- rate, channel
415/// count and rounded length -- appended after every other tail, so an
416/// audio-only file's IMPORTED line reads the numbers a properties card would
417/// otherwise take a click to open. `has_video` is the caller's probed answer
418/// ([`Player::has_video`], or the import's own `NoVideoTrack` refusal): a
419/// film's toast is unchanged, an audio-only container gets the numbers the
420/// same as a song, and a song whose own small header read comes back empty
421/// stays plain.
422pub(crate) fn audio_import_tail(path: &std::path::Path, has_video: bool) -> String {
423 if has_video {
424 return String::new();
425 }
426 let probe = engine::AudioSession::probe(path, 0).ok().flatten();
427 let secs = engine::AudioSession::duration_secs(path).ok().flatten();
428 match (probe, secs) {
429 (Some(p), Some(secs)) => {
430 format!(
431 " — {} Hz, {} ch, {}s",
432 p.sample_rate,
433 p.channels,
434 secs.round() as u64
435 )
436 }
437 _ => String::new(),
438 }
439}
440
441/// Every subtitle track a file carries, cues and all -- the walk that costs, in
442/// the one place every door that pays it goes through. `Ok` and empty for a file
443/// with none to read, which is what a file that is neither a container we can
444/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer
445/// `add_subtitle_tracks` gives it, and nothing is opened to find that out.
446///
447/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`]
448/// is an associated fn): no borrow crosses the await, so this runs whole on a
449/// worker while the window keeps painting.
450pub(crate) fn walk_subtitles(path: &std::path::Path) -> Subs {
451 match carries_subtitles(path) || is_subtitle(path) {
452 true => PlaybackSession::parse_subtitles(path),
453 false => Ok(Vec::new()),
454 }
455}
456
457/// The subtitle tracks a media file carries, taken into the session as it is
458/// opened, and the tail the notice grows for them: an mkv or an mp4 with
459/// subtitles in it arrives with its subtitles, because a track nobody imported
460/// is a track nobody knows is there. Every other container answers `None`
461/// without being read.
462///
463/// A refusal is a tail too, never a failure of the open: the picture and the
464/// sound of a film whose subtitle tracks cannot be walked are still the film.
465///
466/// Both halves at once, which only a *worker* may do: the walk reads the whole
467/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour
468/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which
469/// this runs on the worker ([`open_ahead`]), never the render thread; an
470/// import splits the two halves across the hop instead ([`read_ahead`] walks,
471/// [`subtitle_tail`] pushes).
472pub(crate) fn subtitle_notice(
473 session: &mut PlaybackSession,
474 path: &std::path::Path,
475) -> Option<String> {
476 subtitle_tail(session, walk_subtitles(path))
477}
478
479/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever
480/// thread paid for it to the timeline. `Send` all the way down (`sendable()`,
481/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's.
482pub(crate) type Subs = engine::Result<Vec<engine::subtitle::SubtitleTrack>>;
483
484/// The tail a file's own subtitle tracks earn on the notice that names it, and
485/// the push that puts them on the timeline -- the second half of the walk, the
486/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no
487/// decode). Every door that arrives with a *file* words it here, once: the file
488/// argv named, an import, and an import into an empty window cannot say the same
489/// thing differently, whichever thread read the cues.
490///
491/// A count and nothing else (DESIGN §8: the room never explains itself in
492/// prose). The tracks land in a *list* beside the media, not over the picture
493/// ([`Player::subtitle_overlay`] shows one once it is on a subtitle lane) --
494/// where they went is the list's own geography to say, not this line's.
495///
496/// `None` for a file that gave none and for one whose tracks are on the timeline
497/// already -- an import that adds nothing says nothing about subtitles. A
498/// refusal is a tail too, never a failure of the import: the picture and the
499/// sound of a film whose subtitle tracks cannot be walked are still the film.
500pub(crate) fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option<String> {
501 match subs {
502 Ok(tracks) => match session.add_subtitle_tracks(tracks) {
503 0 => None,
504 n => Some(format!(" · {}", count_noun(n, "subtitle track", "subtitle tracks"))),
505 },
506 Err(e) => Some(format!(" — subtitles unread: {e}")),
507 }
508}
509
510/// What the subtitles toggle says it just did ([`Player::toggle_subtitles`]),
511/// worded off the lanes: `placed` is every caption on every subtitle lane
512/// ([`Player::placed_captions`]), because that -- and never the palette row the
513/// list marks -- is what the toggle covers and uncovers.
514///
515/// Nothing placed is its own sentence: "Subtitles shown — 0 caption(s)" over an
516/// unchanged picture reads as a broken toggle, so it says the move that would
517/// put words there instead.
518pub(crate) fn subtitle_toggle_notice(on: bool, placed: usize) -> String {
519 match (on, placed) {
520 (true, 0) => "Subtitles shown — nothing placed yet".to_string(),
521 (true, n) => format!("Subtitles shown — {} on the timeline", count_noun(n, "caption", "captions")),
522 (false, n) => format!("Subtitles hidden — {} still placed", count_noun(n, "caption", "captions")),
523 }
524}
525
526/// The push both deliberate add-subtitles doors end on -- `+ S` and its key
527/// ([`Player::add_subtitles`]) and a dropped or argv'd subtitle file
528/// ([`Player::take_subtitles`]) -- so the two cannot come to word the same file
529/// differently.
530///
531/// The walk having found *nothing* is a refusal and not a count: a container
532/// with no subtitle track in it and a file whose tracks are all on the timeline
533/// already both push zero rows, and they are opposite answers -- one says look
534/// somewhere else, the other says you already have them. The engine's own door
535/// draws the same line in the same words
536/// ([`PlaybackSession::no_subtitles_in`], asked here because this route splits
537/// the walk from the push to keep the walk off the render thread).
538///
539/// The file itself joins nothing either way: no library row, no lane, no clip.
540/// Subtitles are a list the timeline carries, and this is the only thing that
541/// touches it.
542pub(crate) fn pushed(
543 session: &mut PlaybackSession,
544 path: &std::path::Path,
545 tracks: Vec<engine::subtitle::SubtitleTrack>,
546) -> engine::Result<usize> {
547 match tracks.is_empty() {
548 true => Err(PlaybackSession::no_subtitles_in(path)),
549 false => Ok(session.add_subtitle_tracks(tracks)),
550 }
551}
552
553/// What a subtitle row says under its name: how many cues it holds and whether
554/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which
555/// is the difference between a track an export writes into the file and one it
556/// can only draw -- or, for a track that could not be read, the engine's own
557/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track
558/// dropped from the list would say the film has no subtitles at all.
559pub(crate) fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String {
560 match (&track.refused, track.is_bitmap()) {
561 (Some(why), _) => why.clone(),
562 (None, true) => format!("{} cues — pictures", track.cues.len()),
563 (None, false) => format!("{} cues", track.cues.len()),
564 }
565}
566
567/// What the export card's Subtitles row says: the engine's own words for the
568/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked
569/// about `picks`) and, beside them, the rows it is carrying nothing of.
570///
571/// `picks` is [`Player::export_subs`] -- every track with a cue left in the
572/// exported range -- so a track sitting in the list with eighty-three cues
573/// nowhere near a trimmed timeline never reaches the engine at all, and the card
574/// said nothing about it while the list went on showing it. Which tracks have
575/// cues *here* is this side's answer and nobody else's, so this side words it.
576///
577/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more
578/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten
579/// lines and pushed the Destination row under the fold of the card. The names
580/// are still one row each in the Subtitles list, with the cue count and the
581/// reason under them ([`subtitle_detail`]) -- more than this line ever said.
582///
583/// The counted split follows the engine's own order of reasons (`refused`, then
584/// pictures, then no cues), with the last asked of the timeline instead of the
585/// track.
586///
587/// corner-cut: that split reads the same public fields the list rows read
588/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the
589/// engine's decision, so a *new* reason to drop a track would be counted here as
590/// embedded until this follows it -- the named line, which is the engine's
591/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out
592/// of `planned_subtitles` as data rather than as one sentence, which is an
593/// engine change.
594#[allow(dead_code)] // read by `Player::subtitle_line`, which Settings shows
595pub(crate) fn subtitle_plan(
596 plan: String,
597 tracks: &[engine::subtitle::SubtitleTrack],
598 picks: &[usize],
599) -> String {
600 let mut parts: Vec<String> = Vec::new();
601 // "none" is the engine's word for having nothing to say and would read as a
602 // verdict on the tracks named after it. Anything else is the sentence the
603 // export is actually planned from -- the lanes' own, wherever the timeline
604 // places words ([`engine::export::planned_subtitles`]) -- and it is kept
605 // whatever the palette picks are: dropping it on an empty pick list is how a
606 // card showing "S1 eng — past the last picture" said nothing at all.
607 if plan != "none" {
608 parts.push(plan.clone());
609 }
610 parts.extend(
611 tracks
612 .iter()
613 .enumerate()
614 .filter(|(i, track)| !picks.contains(i) && !spoken_for(&plan, track))
615 // Not "no cues here": a row the export leaves out is a row nothing
616 // on the timeline placed, and what puts that right is the drag --
617 // the same sentence the import notice ends with.
618 .map(|(_, track)| format!("{} — in the palette, on no track", track.label)),
619 );
620 let named = parts.join("; ");
621 if named.chars().count() <= SUB_PLAN_CHARS {
622 return match named.is_empty() {
623 true => "none".to_string(),
624 false => named,
625 };
626 }
627 let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0);
628 for (i, track) in tracks.iter().enumerate() {
629 match (
630 track.refused.is_some(),
631 track.is_bitmap(),
632 picks.contains(&i) || spoken_for(&plan, track),
633 ) {
634 (true, _, _) => unread += 1,
635 (_, true, _) => pictures += 1,
636 (_, _, false) => off += 1,
637 _ => embedded += 1,
638 }
639 }
640 let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())];
641 counted.extend(
642 [
643 (pictures, "pictures"),
644 (unread, "unread"),
645 (off, "in the palette, on no track"),
646 ]
647 .into_iter()
648 .filter(|(n, _)| *n > 0)
649 .map(|(n, why)| format!("{n} {why}")),
650 );
651 counted.join("; ")
652}
653
654/// Whether the engine's sentence already speaks for this row: with words placed
655/// on lanes, every clause of it names the palette row its lane shows
656/// ([`engine::export::planned_subtitles`]) -- and a line that embeds a track and
657/// then says the same track is on no track is a line contradicting itself.
658///
659/// corner-cut: the match is the label found in the sentence, because the engine
660/// hands back one string and not the rows it spoke for. Ceiling: two rows whose
661/// labels are one a prefix of the other ("eng", "eng 2") -- with the longer one
662/// placed, the shorter loses its clause; it never gains a wrong one. Upgrade
663/// path: `planned_subtitles` handing its clauses back as data, the same upgrade
664/// [`subtitle_plan`]'s own note names.
665fn spoken_for(plan: &str, track: &engine::subtitle::SubtitleTrack) -> bool {
666 !track.label.is_empty() && plan.contains(track.label.as_str())
667}
668
669/// Every subtitle track one file gave, kept together. Plain data, planned
670/// before anything is drawn -- the grouping is the branchy part and it is the
671/// same answer whatever a styling puts around it.
672///
673/// [`Player::subtitle_section`] draws one block per group of these, and
674/// [`sub_pick_name`] names the pick out of the same answer -- so what a heading
675/// says and what a row a person clicked says cannot disagree.
676#[derive(Debug, PartialEq)]
677pub(crate) struct SubGroup {
678 /// What the group is called: the file without its extension, which is what
679 /// a person named the film even when the subtitles came out of a remux.
680 pub(crate) name: String,
681 /// What the swatch is asked by ([`file_tint`]) -- the file, so a subtitle
682 /// row and the media rows of the same file wear one colour. `None` from
683 /// that lookup for a standalone `.srt`, which is nobody's stream.
684 pub(crate) path: PathBuf,
685 pub(crate) rows: Vec<SubRow>,
686}
687
688/// One subtitle track, as a row shows it.
689#[derive(Debug, PartialEq)]
690pub(crate) struct SubRow {
691 /// Which track of the session's list this row is: the *flat* index into the
692 /// add-order Vec `PlaybackSession::subtitles` hands back, which is what a
693 /// click sets `sub_track` to and what a caption placed on a subtitle lane
694 /// names, so it is what a save writes into the `.edith` for that caption.
695 /// Grouping moves rows around on screen and never touches this number.
696 pub(crate) track: usize,
697 /// Which of *this file's* tracks it is, counted from 1 -- the numbering
698 /// [`row_name`] gives audio streams, for the same reason: two tracks off one
699 /// remux that both say "eng" are told apart by nothing else.
700 pub(crate) number: usize,
701 pub(crate) label: String,
702 /// The row's second line ([`subtitle_detail`]).
703 pub(crate) detail: String,
704 /// Why it cannot be shown, for a track that cannot: the only thing that
705 /// greys a row out. Listed all the same -- a picker that hides them is a
706 /// picker that lies.
707 pub(crate) refused: Option<String>,
708 /// Pictures rather than lines ([`engine::subtitle::SubtitleTrack::bitmap`]).
709 pub(crate) bitmap: bool,
710}
711
712/// What a subtitle row is called, off the two fields the container really
713/// stated rather than out of the flattened
714/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export
715/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the
716/// display string back apart is the very heuristic that sent every French track
717/// out as English: `lang_human` on a whole "und — Signs" matches nothing and
718/// names a language nobody speaks.
719///
720/// The three shapes a track arrives in, all three of them real: a standalone
721/// file states no language and is its own name, an embedded one states a
722/// language and sometimes a title beside it, and a refused one states neither
723/// and keeps the label it was refused under (`SubtitleTrack::refused`).
724pub(crate) fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String {
725 match (sub.language.as_str(), sub.name.as_str()) {
726 ("", "") => sub.label.clone(),
727 ("", name) => name.to_string(),
728 // A track whose only name is the tag for "nobody said" says that in
729 // words rather than showing the tag itself.
730 (lang, "") => lang_human(lang).to_string(),
731 // ...and one that says "nobody said" *and* gives a title is the title:
732 // "unknown language — Signs" pads it with a word the file never said.
733 ("und", name) => name.to_string(),
734 (lang, name) => format!("{lang} — {name}"),
735 }
736}
737
738/// The subtitle list as rows under the file each came out of: one group per
739/// distinct path, in the order the files first appear, and each file's tracks
740/// in the order they were added. Two remuxes' tracks arriving interleaved --
741/// which is what importing a second film does -- still read as two films.
742pub(crate) fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec<SubGroup> {
743 let mut groups: Vec<SubGroup> = Vec::new();
744 for (track, sub) in tracks.iter().enumerate() {
745 let group = match groups.iter().position(|g| g.path == sub.path) {
746 Some(i) => &mut groups[i],
747 None => {
748 groups.push(SubGroup {
749 name: sub
750 .path
751 .file_stem()
752 .map_or_else(|| file_name(&sub.path), |s| s.to_string_lossy().into()),
753 path: sub.path.clone(),
754 rows: Vec::new(),
755 });
756 groups.last_mut().expect("just pushed")
757 }
758 };
759 group.rows.push(SubRow {
760 track,
761 number: group.rows.len() + 1,
762 label: sub_title(sub),
763 detail: subtitle_detail(sub),
764 refused: sub.refused.clone(),
765 bitmap: sub.is_bitmap(),
766 });
767 }
768 groups
769}
770
771/// How the picked track is named wherever the pick is echoed -- the strip
772/// header, the section heading, the toggle's own notice. What the track is
773/// *and* which file it came out of: two remuxes each carrying an "eng" track
774/// give the same word twice, and the file is the only thing that tells them
775/// apart. A file that gave several of them numbers them within itself, the way
776/// [`row_name`] numbers audio streams, since "eng" twice off one remux is the
777/// same problem one file down.
778///
779/// Goes through [`subtitle_rows`], so the name a header says and the row a
780/// person clicked cannot disagree -- and the label is humanised there, so an
781/// "und" track is named in words here without being passed through
782/// [`lang_human`] twice.
783///
784/// `None` for an index no track answers to, which is the silence
785/// [`Player::subtitle_track`] gives at the same moment.
786/// Where the picked subtitle row lands once `removed` has been taken off a list
787/// that is `left` long afterwards. The pick follows the list: the same *track*
788/// while it is still there -- every index past the one that went moves down
789/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty
790/// place when the picked one is what went, and the last row when that was the
791/// last. Zero on an emptied list, which is the index the section is not drawn at
792/// all.
793///
794/// Its own function because the pick is read as "which row" everywhere it is
795/// echoed -- the dock highlights the picked row by comparing it
796/// (`dock_stance`'s `track == player.sub_track`), and the section heading and
797/// its notices name it -- so left where it was it would highlight one track and
798/// name another the moment a row above it went. The plate over the picture is
799/// not on that list: it is drawn from the *placements* on the shown lane
800/// ([`Player::active_sub_lane`], and the session's own `sub_lane_cues`). What an export
801/// writes is not this pick either -- it is worked out from the cues on the
802/// timeline each time ([`Player::export_subs`]).
803pub(crate) fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize {
804 let picked = match removed < picked {
805 true => picked - 1,
806 false => picked,
807 };
808 picked.min(left.saturating_sub(1))
809}
810
811/// What a palette row *is*, apart from where it sits: the file it came out of,
812/// which track of it, and the two words a row shows. Cloned out of the palette
813/// once per history step -- a path and three short strings, against a palette
814/// whose cues are the whole film's subtitles. Not [`SubRow`], which is a row as
815/// the column *draws* it.
816#[derive(Clone, Debug, PartialEq, Eq)]
817pub(crate) struct SubPickKey {
818 path: PathBuf,
819 track: Option<u64>,
820 language: String,
821 label: String,
822}
823
824impl SubPickKey {
825 /// The row `track` of this palette names, `None` for an index no track
826 /// answers to -- the same silence [`sub_pick_name`] gives.
827 pub(crate) fn of(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option<Self> {
828 let track = tracks.get(track)?;
829 Some(Self {
830 path: track.path.clone(),
831 track: track.track,
832 language: track.language.clone(),
833 label: track.label.clone(),
834 })
835 }
836
837 /// Whether `track` is this row: the four fields a palette would have had to
838 /// change for a pick left where it was to name a different track.
839 fn is(&self, track: &engine::subtitle::SubtitleTrack) -> bool {
840 track.path == self.path
841 && track.track == self.track
842 && track.language == self.language
843 && track.label == self.label
844 }
845}
846
847/// Where the pick lands once a *restored* palette is back in place: the row
848/// that was picked, found by what it is rather than by where it sat.
849///
850/// A history step moves rows without saying which one moved -- an undo of a
851/// removal puts a column back above the pick as often as below it -- so an
852/// index left where it was names a different track, which is the desync
853/// [`sub_pick_after_removal`] prevents at the door where the row that moved is
854/// known. That door's arithmetic is this map's one-row-moved case.
855///
856/// A row the restored palette does not have (it went again, or the pick named
857/// nothing) falls back to the old index clamped into the new list -- that same
858/// door's own fallback, and the zero the section is not drawn at all for an
859/// emptied palette.
860pub(crate) fn sub_pick_after_restore(
861 picked: usize,
862 before: Option<&SubPickKey>,
863 after: &[engine::subtitle::SubtitleTrack],
864) -> usize {
865 before
866 .and_then(|was| after.iter().position(|track| was.is(track)))
867 .unwrap_or_else(|| picked.min(after.len().saturating_sub(1)))
868}
869
870pub(crate) fn sub_pick_name(
871 tracks: &[engine::subtitle::SubtitleTrack],
872 track: usize,
873) -> Option<String> {
874 subtitle_rows(tracks).into_iter().find_map(|group| {
875 let row = group.rows.iter().find(|row| row.track == track)?;
876 let track = match group.rows.len() > 1 {
877 false => row.label.clone(),
878 true => format!("{} {}", row.label, row.number),
879 };
880 // A standalone `.srt` is already named after its own file: "sub.srt —
881 // sub" says the one thing twice, and the film is only worth naming
882 // where it is not in the label yet.
883 Some(match row.label.starts_with(&group.name) {
884 true => track,
885 false => format!("{track} — {}", group.name),
886 })
887 })
888}
889
890/// Where a cue is drawn on the bed: left edge and width in pixels, through the
891/// same [`Scale`] every clip box goes through -- so a cue and the take it is
892/// spoken over line up at every zoom, which is the only reason the strip is
893/// worth drawing. Microseconds are the cue's unit and seconds are the scale's,
894/// and this is the one place they meet.
895///
896/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a
897/// fraction of a pixel, and a mark that rounds away reads as a track with
898/// nothing in it.
899#[cfg(test)]
900pub(crate) fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) {
901 span_box(scale, cue.start_us, cue.end_us)
902}
903
904/// [`cue_box`] for a stretch of the timeline's own clock, in microseconds: how a cue block of a
905/// lane is placed ([`engine::project::CueSpan`]).
906pub(crate) fn span_box(scale: Scale, start_us: i64, end_us: i64) -> (f32, f32) {
907 let (start, end) = (start_us as f64 / 1e6, end_us as f64 / 1e6);
908 (
909 scale.px_at(start),
910 scale.width_px(end - start).max(SUB_CUE_MIN_W),
911 )
912}
913
914/// Which subtitle lane draws over the picture, out of the pick somebody made
915/// and the lanes there are *now* ([`Player::active_sub_lane`]): the picked one
916/// while it is still on the timeline, and the first lane otherwise -- which is
917/// the whole of "one lane needs no picking", "the first lane added draws" and
918/// "a removed lane's pick promotes its neighbour rather than showing nothing".
919///
920/// `None` only with no subtitle lane at all, which is a timeline with nowhere
921/// for words to be.
922///
923/// A pick against the live list rather than a pointer kept in step with it: a
924/// [`Lane`] is a position among its kind, so an add, a removal, a reorder and
925/// every undo of those move what a stored handle names -- and each of them is
926/// answered here, at the read, by a list that is never stale.
927pub(crate) fn active_lane(picked: Option<Lane>, lanes: &[Lane]) -> Option<Lane> {
928 picked
929 .filter(|lane| lanes.contains(lane))
930 .or_else(|| lanes.first().copied())
931}
932
933/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue
934/// itself is: one that ends exactly where the next begins hands over rather than
935/// overlapping it for a frame, and several that genuinely overlap all come back
936/// -- a sign and a line of dialogue are two cues at one moment.
937pub(crate) fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> {
938 let us = (at * 1e6) as i64;
939 cues.iter()
940 .filter(|cue| cue.start_us <= us && us < cue.end_us)
941 .collect()
942}
943
944/// How long a failed waveform decode is left alone before the next repaint asks
945/// again: long enough that sixty repaints a second do not become sixty decodes,
946/// short enough that a file which arrived mid-copy has its envelope a moment
947/// after it lands. The engine memoizes no failure for the same reason
948/// ([`engine::waveform`]): the reason one failed may have gone away.
949pub(crate) const WAVE_RETRY: std::time::Duration = std::time::Duration::from_secs(5);
950
951/// The sources a repaint has not asked about yet, as of `now`. A key that is
952/// already there means "asked", whatever state it is in -- which is what stops
953/// a decode already running from being started again by the next of sixty
954/// repaints a second -- with one exception: a [`Wave::Failed`] older than
955/// [`WAVE_RETRY`] is asked again, because a decode that failed once is not an
956/// answer about the file, only about the moment it was tried. A file with no
957/// audio (`Wave::Silent`) is an answer like any other and is never re-asked.
958pub(crate) fn unseen_sources(
959 sources: &[Source],
960 waves: &HashMap<(PathBuf, usize), Wave>,
961 now: std::time::Instant,
962) -> Vec<(PathBuf, usize)> {
963 sources
964 .iter()
965 .filter(|s| !engine::generate::is_generated(&s.path))
966 .map(|s| (s.path.clone(), s.audio_stream))
967 .filter(|key| match waves.get(key) {
968 None => true,
969 Some(Wave::Failed(at)) => now.duration_since(*at) >= WAVE_RETRY,
970 Some(_) => false,
971 })
972 .collect()
973}
974
975/// The same, for the per-file caches: one entry per *file*, however many of its
976/// streams the timeline plays. Generic in the value, because the stream probe
977/// and the still's own size are both asked once per file and answered by
978/// presence in a map.
979pub(crate) fn unseen_paths<V>(sources: &[Source], seen: &HashMap<PathBuf, V>) -> Vec<PathBuf> {
980 let mut out: Vec<PathBuf> = Vec::new();
981 for s in sources {
982 if !seen.contains_key(&s.path) && !out.contains(&s.path) {
983 out.push(s.path.clone());
984 }
985 }
986 out
987}
988
989/// The films a repaint may start a stand-in for ([`engine::proxy`]): the unseen
990/// ones while this project makes them by itself, and **none at all** while it
991/// does not -- until the Proxies switch is thrown, which is the ask, since
992/// nothing else offers to make one.
993///
994/// A film left out here stays out of the map it was checked against, which is
995/// what brings it back the moment either switch says yes: an import made while
996/// both were off is not a film that missed its turn.
997pub(crate) fn proxies_to_start<V>(
998 auto: bool,
999 cut_on_them: bool,
1000 sources: &[Source],
1001 seen: &HashMap<PathBuf, V>,
1002) -> Vec<PathBuf> {
1003 match auto || cut_on_them {
1004 true => unseen_paths(sources, seen),
1005 false => Vec::new(),
1006 }
1007}
1008
1009/// Which timeline frame the playhead is on, by the rule the engine's own edits
1010/// use (playback.rs `secs_to_frame`): the frame that has started, with the
1011/// epsilon that keeps a clock sitting exactly on a boundary from reading as the
1012/// frame before it. Only ever a hint here -- what an edit does is still the
1013/// engine's answer, taken from the same seconds.
1014pub(crate) fn frame_at(secs: f64, fps: f64) -> u32 {
1015 (secs * fps + 1e-6).floor().max(0.) as u32
1016}
1017
1018/// The tallest the engine-drawn caption bitmap is: the text scales with the
1019/// frame's height, so a 540-line canvas draws the same picture as a 4K one at a
1020/// fraction of the shaping and upload cost, and the plate scales it to fit.
1021const CAPTION_CANVAS_H: u32 = 540;
1022
1023/// The animated caption at timeline frame `frame`, drawn by the engine's own
1024/// burn function ([`engine::captionanim::plan`] into
1025/// [`engine::text::overlay_blocks`], what an export paints too) as a straight
1026/// alpha BGRA bitmap the size of the (scaled) project canvas.
1027///
1028/// `cues` are the ones on screen, on the timeline's clock. Returns the key of
1029/// what was drawn -- its words and every word's pose, so two frames that look
1030/// alike share a key and a held cue is drawn once -- and the bitmap; `None`
1031/// where nothing is on screen. The key is computed *before* any text is shaped,
1032/// so a caller that already holds that key never pays for the drawing.
1033pub(crate) fn animated_caption_key(
1034 style: &engine::text::TextStyle,
1035 cues: &[engine::subtitle::Cue],
1036 frame: u32,
1037 fps: f64,
1038) -> Option<(u64, Vec<engine::text::Block>)> {
1039 let on: Vec<usize> = (0..cues.len()).collect();
1040 let blocks = engine::captionanim::plan(style, cues, &on, frame, fps);
1041 // The family is not in the blocks, so it is part of the key: a new face draws a new picture.
1042 use std::hash::{Hash, Hasher};
1043 let mut key = engine::captionanim::blocks_key(&blocks);
1044 if let Some(family) = &style.family {
1045 let mut h = std::collections::hash_map::DefaultHasher::new();
1046 (key, family).hash(&mut h);
1047 key = h.finish();
1048 }
1049 (!blocks.is_empty()).then_some((key, blocks))
1050}
1051
1052/// The bitmap for `blocks` ([`animated_caption_key`]) on a canvas of the
1053/// project's shape, and its size. Straight alpha, BGRA: the text is composed
1054/// over black and over white, and the difference of the two is the coverage.
1055pub(crate) fn animated_caption_bitmap(
1056 style: &engine::text::TextStyle,
1057 blocks: &[engine::text::Block],
1058 resolution: (u32, u32),
1059) -> Option<(u32, u32, Vec<u8>)> {
1060 let (rw, rh) = resolution;
1061 if rw == 0 || rh == 0 {
1062 return None;
1063 }
1064 let h = rh.min(CAPTION_CANVAS_H);
1065 let w = ((u64::from(rw) * u64::from(h) / u64::from(rh)) as u32).max(1);
1066 let overlay = engine::text::overlay_blocks(style, w, h, blocks);
1067 if overlay.is_blank() {
1068 return None;
1069 }
1070 let n = (w * h) as usize * 4;
1071 let mut black = vec![0u8; n];
1072 let mut white = vec![255u8; n];
1073 overlay.blend_bgra(&mut black);
1074 overlay.blend_bgra(&mut white);
1075 let mut out = vec![0u8; n];
1076 for ((o, b), wh) in out
1077 .as_chunks_mut::<4>()
1078 .0
1079 .iter_mut()
1080 .zip(black.as_chunks::<4>().0)
1081 .zip(white.as_chunks::<4>().0)
1082 {
1083 let alpha = (0..3).map(|c| 255 - (wh[c] - b[c].min(wh[c]))).max().unwrap_or(0);
1084 if alpha == 0 {
1085 continue;
1086 }
1087 for c in 0..3 {
1088 o[c] = ((u32::from(b[c]) * 255 + u32::from(alpha) / 2) / u32::from(alpha)).min(255) as u8;
1089 }
1090 o[3] = alpha;
1091 }
1092 Some((w, h, out))
1093}