forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

importing.rs496 lines, 22.4 KiBHistoryRawDownload
1//! Bringing a file in: the library's tabs, the import and scan state, the stages.
2
3use crate::*;
4
5/// The library's three categories, in the order the giants list them: the
6/// pictures, the sound, and the words. A file is in exactly one of them, so a
7/// tab is a question with an answer rather than a filter with a guess.
8#[derive(Clone, Copy, PartialEq, Eq, Debug)]
9pub(crate) enum LibraryTab {
10 Media,
11 Audio,
12 Text,
13}
14
15pub(crate) const LIBRARY_TABS: [LibraryTab; 3] = [LibraryTab::Media, LibraryTab::Audio, LibraryTab::Text];
16
17impl LibraryTab {
18 pub(crate) fn label(self) -> &'static str {
19 match self {
20 LibraryTab::Media => "Media",
21 LibraryTab::Audio => "Audio",
22 LibraryTab::Text => "Text",
23 }
24 }
25
26 /// Whether a source belongs on this tab. Subtitles are not sources at all
27 /// -- they are the [`Player::subtitle_section`] under the list -- so the
28 /// Text tab holds no rows of its own and says so.
29 pub(crate) fn holds(self, path: &Path) -> bool {
30 match self {
31 LibraryTab::Media => !engine::is_audio(path),
32 LibraryTab::Audio => engine::is_audio(path),
33 LibraryTab::Text => false,
34 }
35 }
36
37 /// What an empty tab says instead of being a blank column.
38 pub(crate) fn empty(self) -> &'static str {
39 match self {
40 LibraryTab::Media => "No video or stills yet — Import, or drop a file on the window",
41 LibraryTab::Audio => "No sound yet — Import, or drop a file on the window",
42 LibraryTab::Text => {
43 "No subtitles yet — Add subtitles from a file, or drop an .srt on the window"
44 }
45 }
46 }
47}
48
49/// What is known about a source's audio. Three states and not two, because a
50/// file whose peaks have not come back yet must not be drawn as one that has no
51/// audio at all: the first shows a bed, the second shows nothing.
52#[derive(Clone)]
53pub(crate) enum Wave {
54 /// Asked for; the decode is running on a background thread.
55 Loading,
56 /// The file has no audio track. An answer, not a miss.
57 Silent,
58 /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]:
59 /// "this file's sound could not be read" and "this file has no sound" look
60 /// the same on a lane, and the first is a bug report waiting to happen.
61 Failed,
62 Peaks(Arc<Vec<(f32, f32)>>),
63}
64
65/// The bench's own version of [`Wave`] for the picture instead of the sound: one
66/// representative decoded frame per file, kept and reused across every clip cut
67/// from it (DESIGN.md §5's "real thumbnails across video clips", §12 step 5 --
68/// this is the frame, not the ink; the ink comes from [`crate::source_tint`]
69/// until real extraction lands). Audio-only files never enter this map (see
70/// `cache_media`'s filter), so `Silent` has no counterpart here.
71#[derive(Clone)]
72pub(crate) enum Thumb {
73 /// Asked for; the decode is running on a background thread.
74 Loading,
75 /// The decode failed or the file turned out to carry no picture after all.
76 Failed,
77 Ready(Arc<gpui::RenderImage>),
78}
79
80/// What a source's stand-in is up to ([`engine::proxy`]). Kept per file and
81/// filled like every other library fact -- presence means "asked", so a repaint
82/// mid-encode cannot start a second one.
83pub(crate) enum Proxy {
84 /// The header is being read to find out whether this file wants one. Its
85 /// own state because it is what makes "how many are in flight" a number:
86 /// the answer comes back on a worker, and until it does this file may still
87 /// turn into an encode.
88 Asked,
89 /// A file this machine cuts at speed as it is: no stand-in, and none
90 /// wanted ([`engine::proxy::wanted`]).
91 Native,
92 /// Being made, in the background, while the film keeps playing.
93 Making(engine::proxy::Job),
94 /// Stopped by hand ([`Player::cancel_proxy`]) and not yet gone: the worker
95 /// gives up at its next frame and deletes the half-written file itself, and
96 /// the job is held until it does. Kept as a state rather than dropped
97 /// because the encode may still *beat* the cancel -- a stand-in that is
98 /// already written is a file in the cache and is reported as one.
99 Cancelling(engine::proxy::Job),
100 /// Stopped, and the worker has gone. Not [`Self::Failed`]: nothing went
101 /// wrong, somebody asked for it -- and it stays in the map so no repaint
102 /// starts the encode that was just stopped over again.
103 Cancelled,
104 /// There is one in the cache. What the switch actually plays.
105 Ready,
106 /// It could not be made: the film itself is what plays, and the row says
107 /// so rather than leaving a bar that never fills.
108 Failed,
109}
110
111impl Proxy {
112 /// What the library row says about it, or nothing at all for a file that
113 /// never wanted one -- a row per source is not the place to announce that
114 /// nothing is happening.
115 pub(crate) fn detail(&self) -> String {
116 match self {
117 Self::Asked | Self::Native => String::new(),
118 // Rounded down: a bar that says 100% while the encoder is still
119 // writing is the one number a progress line must never show.
120 Self::Making(job) => format!("proxy {}%", (job.progress() * 100.) as u32),
121 // Its own word while the worker is still winding down: "no proxy"
122 // the instant the × is clicked would be a claim about a file that
123 // is at that moment still being written.
124 Self::Cancelling(_) => "proxy stopping…".to_string(),
125 Self::Cancelled => "no proxy — stopped".to_string(),
126 Self::Ready => "proxy".to_string(),
127 Self::Failed => "no proxy".to_string(),
128 }
129 }
130}
131
132/// The import a worker is reading, as the line above the panel shows it. No
133/// fraction anywhere: neither read reports how far into the file it has come,
134/// so what is honest is the file's name, the stage, and two clocks -- one that
135/// proves the window is answering, one that says the stage has not moved.
136pub(crate) struct Import {
137 pub(crate) path: PathBuf,
138 /// When the worker started, for the elapsed clock.
139 pub(crate) started: Instant,
140 /// Written by the worker between its two reads, read here every repaint.
141 pub(crate) stage: Arc<std::sync::atomic::AtomicU8>,
142 /// The stage the line last saw and when it last changed. The pair is the
143 /// whole stall detector: a stage older than [`IMPORT_STALL`] is what the
144 /// honest wording is for.
145 pub(crate) seen: ImportStage,
146 pub(crate) since: Instant,
147 /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at
148 /// the landing: what the worker read is dropped instead of joining the
149 /// timeline.
150 ///
151 /// ...and the read with it: the worker installs this as its thread's cancel
152 /// ([`engine::demux::with_cancel`]) and every Matroska cluster walk under it
153 /// -- the header index and the subtitle pass, the twenty seconds of a cold
154 /// 24 GB remux -- gives up at the next element.
155 ///
156 /// corner-cut: an mp4's header is one read inside `mp4::Mp4Reader`, which
157 /// has no flag to poll, so a cancelled mp4 import still finishes its own
158 /// header before the worker returns. Ceiling: the disk stays busy for that
159 /// read, though nothing waits on it. Upgrade path is our own `moov` parse,
160 /// which is a demuxer rewrite rather than a cancel.
161 pub(crate) cancelled: Arc<std::sync::atomic::AtomicBool>,
162}
163
164impl Import {
165 /// Reads the worker's stage and keeps the stall clock: it restarts when the
166 /// stage actually changes and at no other time, which is what makes "has
167 /// not moved in five seconds" a fact rather than a guess about the elapsed
168 /// clock. Hands back how long the current stage has stood, so the line has
169 /// one place to ask.
170 pub(crate) fn poll(&mut self) -> f32 {
171 let stage = ImportStage::from_u8(self.stage.load(std::sync::atomic::Ordering::Relaxed));
172 if stage != self.seen {
173 self.seen = stage;
174 self.since = Instant::now();
175 }
176 self.since.elapsed().as_secs_f32()
177 }
178}
179
180/// What a scan is *of*: the source, which of its audio streams, and the clip's
181/// own `[in, out)` source frames. The range is part of the name because it is
182/// part of the read -- a clip cut in half is a different, shorter decode than
183/// the whole take was, and levels read for one are not the other's.
184pub(crate) type ScanKey = (PathBuf, usize, u32, u32);
185
186/// The silence scan a worker is running, as the card shows it. Same two clocks
187/// as an [`Import`] and for the same reason -- one proves the window answers,
188/// one says the read has stopped moving -- over a progress that *can* move:
189/// a decode knows how far into the sound it has come, so the card says so.
190pub(crate) struct SilenceScan {
191 /// Source, stream and source range being scanned, which is the cache key
192 /// the levels land under and what tells a second open of the same clip from
193 /// a new one.
194 pub(crate) key: ScanKey,
195 /// When the worker started, for the elapsed clock.
196 pub(crate) started: Instant,
197 /// Written by the worker, read here every repaint. The cancel flag in it is
198 /// this side's only word to a scan already running.
199 pub(crate) progress: Arc<engine::silence::Progress>,
200 /// The tenths-of-a-second mark the line last saw and when it last changed:
201 /// the stall detector, exactly [`Import::poll`]'s.
202 pub(crate) seen: u64,
203 pub(crate) since: Instant,
204}
205
206impl SilenceScan {
207 /// Reads the worker's mark and keeps the stall clock, restarting it only
208 /// when the mark actually moves -- [`Import::poll`]'s contract, over a
209 /// number instead of a stage.
210 pub(crate) fn poll(&mut self) -> f32 {
211 let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed);
212 if scanned != self.seen {
213 self.seen = scanned;
214 self.since = Instant::now();
215 }
216 self.since.elapsed().as_secs_f32()
217 }
218}
219
220/// How long a stage may sit without moving before the import line stops
221/// reading like a progress line and says outright that the wait is the file's,
222/// not the window's. Five seconds: a 25 GB remux spends eleven in its header
223/// alone, and a person watching a still line for that long has already decided
224/// the editor hung.
225pub(crate) const IMPORT_STALL: f32 = 5.;
226
227/// Which of an import's two reads the worker is inside. Travels as one atomic,
228/// the way an export's progress does ([`engine::ExportHandle`]) -- there is no
229/// fraction to send, because neither read reports where in the file it is.
230#[derive(Clone, Copy, PartialEq, Eq, Debug)]
231pub(crate) enum ImportStage {
232 /// The container header: the sample tables, the cue index, the frame count.
233 /// Eleven seconds on a cold 29 GB remux, a hundred and fifty milliseconds
234 /// once the pages are warm -- the whole reason this runs off the UI thread.
235 Header,
236 /// The subtitle tracks inside a Matroska, which is a walk over the file's
237 /// blocks rather than a header read (~200 ms on a two-hour film).
238 Subtitles,
239}
240
241impl ImportStage {
242 /// The atomic the worker writes; `u8` because that is what an
243 /// [`AtomicU8`](std::sync::atomic::AtomicU8) carries.
244 pub(crate) fn from_u8(n: u8) -> Self {
245 match n {
246 0 => Self::Header,
247 _ => Self::Subtitles,
248 }
249 }
250
251 /// What the line calls this stage.
252 pub(crate) fn what(self) -> &'static str {
253 match self {
254 Self::Header => "reading the header",
255 Self::Subtitles => "reading the subtitle tracks",
256 }
257 }
258}
259
260/// argv sorted into the file that becomes the timeline and the queue every
261/// named file is read through, in the order they were named. The whole of what
262/// a launch does before the window is on screen -- and it touches no disk,
263/// which is the point: the header walk happens on a worker with the window
264/// already up ([`Player::take_import`]).
265pub(crate) fn launch_queue(
266 args: impl Iterator<Item = PathBuf>,
267) -> (Option<PathBuf>, std::collections::VecDeque<PathBuf>) {
268 let queue: std::collections::VecDeque<PathBuf> = args.collect();
269 (queue.front().cloned(), queue)
270}
271
272/// What a queued file turns into. Every file goes through one queue -- argv's
273/// first file, argv's extras, a drop, the Import button -- and this is the fork
274/// its worker is started on.
275#[derive(PartialEq, Eq, Debug, Clone, Copy)]
276pub(crate) enum Landing {
277 /// The media argv named: it becomes the timeline, and the canvas, the fps,
278 /// the title and the export path come from it.
279 Open,
280 /// A `.edith` argv named: a whole timeline restored, not a source.
281 Project,
282 /// Everything else: a row in the library, the timeline untouched.
283 Import,
284}
285
286/// Which of the three a queued file is (`landing` above is the drag's).
287/// `opening` is the one path argv named and is cleared as it lands, so a second
288/// arrival of the same *media* path -- a drop of the film that is already open
289/// -- is an import, which is what a drop has always been.
290///
291/// A `.edith` is never an import, whichever door it came through: it is a whole
292/// timeline and there is nothing to add it to. Argv's, a dropped one and the
293/// Import button's are one landing, so the seconds its open costs are the
294/// worker's for all three ([`open_ahead`]) and the line above the panel names it
295/// while it runs.
296pub(crate) fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing {
297 match (is_project(path), opening == Some(path)) {
298 (true, _) => Landing::Project,
299 (false, true) => Landing::Open,
300 (false, false) => Landing::Import,
301 }
302}
303
304/// The whole of what an import shows while it runs: which file, which stage,
305/// the clock that proves the window is still answering, and what is behind it
306/// in the queue.
307///
308/// `since` is how long the *stage* has stood still, which is the only movement
309/// an unmeasurable read has: past [`IMPORT_STALL`] the line says so in words,
310/// because a bar that cannot move and a bar that has stopped look identical.
311///
312/// `opening` is the file argv named, which is read through the same queue and
313/// says so in the same words -- except that it is being *opened*, and a line
314/// that called it an import would be describing the wrong thing to the one
315/// person who typed the name.
316pub(crate) fn import_line(
317 name: &str,
318 stage: ImportStage,
319 elapsed: f32,
320 since: f32,
321 waiting: usize,
322 opening: bool,
323) -> String {
324 let tail = match waiting {
325 0 => String::new(),
326 n => format!(" · {n} more waiting"),
327 };
328 let what = stage.what();
329 let verb = match opening {
330 true => "OPENING",
331 false => "IMPORTING",
332 };
333 match since >= IMPORT_STALL {
334 true => format!(
335 "{verb} {name} · still {what} — a big file is minutes of reading, and the window is \
336 not frozen · {} elapsed{tail}",
337 clock(elapsed)
338 ),
339 false => format!("{verb} {name} · {what} · {} elapsed{tail}", clock(elapsed)),
340 }
341}
342
343/// What opening the silence card on a source costs.
344#[derive(PartialEq, Eq, Debug)]
345pub(crate) enum ScanPlan {
346 /// Its levels are already read: the marks are arithmetic on this frame.
347 Marks,
348 /// Nothing read: a worker, and a card that says so meanwhile.
349 Start,
350 /// A worker is already reading this very source -- the other half of a take
351 /// names the same file, and a second card on it waits for the first read
352 /// rather than throwing away the minute already spent.
353 Wait,
354}
355
356/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
357/// of the cache policy, and the reason a second film does not cost the first
358/// one its levels: what is cached is asked per source, never "the last one".
359pub(crate) fn scan_plan(cached: bool, running: Option<&ScanKey>, key: &ScanKey) -> ScanPlan {
360 match (cached, running) {
361 (true, _) => ScanPlan::Marks,
362 (false, Some(at)) if at == key => ScanPlan::Wait,
363 _ => ScanPlan::Start,
364 }
365}
366
367/// The half-open source seconds a [`ScanKey`]'s frames name, at the project's
368/// rate -- what [`engine::silence::levels`] is asked to read, and the same
369/// arithmetic playback puts a clip's `in_frame` through. A rate that is not a
370/// rate reads the whole file rather than an empty window: a scan of nothing is
371/// worse than a scan of too much.
372pub(crate) fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) {
373 match fps.is_finite() && fps > 0. {
374 true => (f64::from(key.2) / fps, f64::from(key.3) / fps),
375 false => (0., f64::INFINITY),
376 }
377}
378
379/// The [`ScanKey`] a background scan lands its whole-file levels under: every
380/// frame the source has, so one entry answers for every clip cut from it. A
381/// sentinel `out_frame` rather than a fourth map, because [`ScanKey`] is
382/// already what [`Player::silence_levels`] is keyed by -- a clip can never
383/// itself claim `u32::MAX` as its own `out_frame`, so the two never collide.
384pub(crate) fn full_scan_key(path: &Path, stream: usize) -> ScanKey {
385 (path.to_path_buf(), stream, 0, u32::MAX)
386}
387
388/// The clip's own stretch of a whole-source scan, in the same dBFS windows
389/// [`engine::silence::levels`] would have decoded for it directly: window `k`
390/// of both is the same [`engine::silence::WINDOWS_PER_SEC`]th of a second from
391/// the start of the file, so slicing costs no decode and reads the same
392/// numbers the on-demand scan would have. Empty past the end of what the
393/// background read has landed so far -- a scan still running answers with
394/// what it has, same as [`SilenceScan`]'s own cancel does.
395pub(crate) fn slice_whole_levels(whole: &[f32], fps: f64, in_frame: u32, out_frame: u32) -> Vec<f32> {
396 if !(fps.is_finite() && fps > 0.) {
397 return Vec::new();
398 }
399 let window = f64::from(engine::silence::WINDOWS_PER_SEC);
400 let start = ((f64::from(in_frame) / fps) * window) as usize;
401 let end = (((f64::from(out_frame) / fps) * window).ceil() as usize).min(whole.len());
402 match start < end {
403 true => whole[start..end].to_vec(),
404 false => Vec::new(),
405 }
406}
407
408/// Whether the card may draw `key`'s marks as arithmetic rather than start a
409/// worker for it: its own exact read, or -- new since the scan moved to
410/// import -- the whole-source background scan its file is cut from
411/// ([`Player::cache_media`]). One function so `Player::open_silence`'s plan
412/// and `Player::scan_silences`' lookup share the one contract for what
413/// "cached" means, instead of two copies that could drift.
414pub(crate) fn silence_cached(levels: &std::collections::HashMap<ScanKey, Arc<Vec<f32>>>, key: &ScanKey) -> bool {
415 levels.contains_key(key) || levels.contains_key(&full_scan_key(&key.0, key.1))
416}
417
418/// What the silence card says while its worker reads. Unlike an import this
419/// one *has* a fraction -- a decode knows how far into the sound it has come --
420/// so the line is where it is up to, out of what the header claims the track is
421/// (`total` of 0 for a header that does not say, drawn as nothing rather than
422/// as a guess). Both in seconds.
423///
424/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds
425/// without the mark moving, a line that cannot move and a line that has stopped
426/// look identical, and only one of them is worth words.
427pub(crate) fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String {
428 let far = match total > 0. {
429 true => format!("{} of ~{} scanned", clock(scanned), clock(total)),
430 false => format!("{} scanned", clock(scanned)),
431 };
432 match since >= IMPORT_STALL {
433 true => format!(
434 "SCANNING · still reading the sound — a big film is minutes of decoding, and the \
435 window is not frozen · {far} · {} elapsed",
436 clock(elapsed)
437 ),
438 false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)),
439 }
440}
441
442/// How often a progress mark is worth keeping, how far back the rate is
443/// measured, and the least span that may answer at all. An export crosses
444/// hardware and software segments that run at different speeds, so the
445/// estimate is a window's average and never the instant's.
446pub(crate) const ETA_SAMPLE: f32 = 0.5;
447pub(crate) const ETA_WINDOW: f32 = 8.;
448pub(crate) const ETA_SPAN: f32 = 1.5;
449
450/// Records where the export has got to and forgets what has fallen out of the
451/// window. One mark per `ETA_SAMPLE`, a window's worth kept: a bounded list
452/// whichever way the encode goes.
453pub(crate) fn note_progress(marks: &mut Vec<(f32, f32)>, elapsed: f32, progress: f32) {
454 if marks.last().is_none_or(|&(t, _)| elapsed - t >= ETA_SAMPLE) {
455 marks.push((elapsed, progress));
456 }
457 while marks.len() > 2 && marks[0].0 < elapsed - ETA_WINDOW {
458 marks.remove(0);
459 }
460}
461
462/// Seconds left at the window's rate, or `None` while nothing measurable has
463/// happened yet -- which the line says as "estimating…" rather than as a
464/// number it would have to take back.
465pub(crate) fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option<f32> {
466 // A finished pass is not a guess: it is over.
467 if progress >= 1. {
468 return Some(0.);
469 }
470 if progress <= 0. || elapsed < ETA_SPAN {
471 return None;
472 }
473 // Two rates, averaged. The window's follows the encode across a
474 // hardware-to-software handover; the whole run's is what keeps a window
475 // that is all stall from throwing the number minutes out and back. Neither
476 // alone reads well: raw window rate spikes eightfold on either edge of a
477 // stall, and the run average alone never notices a segment change.
478 let overall = progress / elapsed;
479 // Never below zero, whatever the marks say. A bar that went *backwards*
480 // between two marks -- an export written again from the start after its
481 // hardware encoder died -- made this negative, which cancelled the run's
482 // own rate and left an answer that read "~0:00 left" over six minutes of
483 // software encoding. The bar is monotone at the source now
484 // (`engine::export`'s `fetch_max`), and a rate the other way is still not
485 // an estimate: a window that has gone nowhere leans on the whole run's
486 // rate, which is exactly what a stall does.
487 let recent = marks
488 .first()
489 .filter(|&&(t, _)| elapsed - t >= ETA_SPAN)
490 .map_or(overall, |&(t, p)| ((progress - p) / (elapsed - t)).max(0.));
491 // Both rates at once can only be zero where nothing has happened at all,
492 // which the guards above already answer with "estimating…" -- said in
493 // arithmetic as well, because the alternative is an infinite division
494 // printed as a clock.
495 Some(2. * (1. - progress) / (recent + overall)).filter(|left| left.is_finite())
496}