forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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