forge
Explore
Log in

Don't you dare go Hollow

The container walk goes to the worker, not the render thread

Browse files at this commit

0e88697bc99959a689e4f423636417d6b715c612Ahmet Kaan GümüşParent: 1501d34
  • perf
    • the container walk goes to the worker, not the render thread
Show full message
🚀 perf(import): the container walk goes to the worker, not the render thread

The Import door read the file twice: once on a worker to warm the page
cache, and once on the UI thread to actually parse it. The second one is
what a person sees -- 2.5-6 s of frozen window opening a 24 GB 4K HEVC
remux, and 0.8-8.9 s importing one beside a timeline that is already up.
The subtitle half of this door was split across the hop a while ago
(`parse_subtitles` walks, `add_subtitle_tracks` pushes); this is the
container half, and it is the same split.

The engine grows the two doors the front-end needed: `probe_import` --
the header, the decoder this machine would open it with, and the audio
check, all with no session in reach, so a worker can run it -- and
`import_probed`, which registers what came back and touches no disk. The
gate they are decided against (`import_gate`) is two clones off the
timeline, so the UI thread hands it over and goes on painting. A timeline
that moved while the worker read is noticed rather than trusted: a stale
probe falls back to the slow door and lands the same row.

A file arriving at a window with no timeline to import into is opened
whole on the worker instead (`open_whole`), which is where the 2.5-6 s
went, and every `.edith` -- dropped, picked or named on the command line
-- now goes through the one queue as well, so its open is a worker's too
and the line above the panel names it while it runs.

Measured on a real-library 4K HEVC remux (24 GB): the
header walk is 21.4 s cold and 429 ms warm, and probing the timeline's
own first source is another 1-4 s. None of it is the render thread's any
more.

...and the line that says so grows a Cancel, because a read that long
needs a way out. The read in flight is not stopped -- a demuxer walk
polls nothing -- so the window is given back at the click, the file does
not land, the queue behind it is dropped, and the notice says exactly
that rather than promising the disk went quiet.
crates/app/src/main.rsmodified+306 -124
@@ -364,6 +364,17 @@ struct Import {
364 /// honest wording is for.364 /// honest wording is for.
365 seen: ImportStage,365 seen: ImportStage,
366 since: Instant,366 since: Instant,
367+ /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at
368+ /// the landing: what the worker read is dropped instead of joining the
369+ /// timeline.
370+ ///
371+ /// ponytail: the *read* is not stopped -- a demuxer walk polls nothing, so
372+ /// the worker finishes into a result nobody takes, and the window is given
373+ /// back at the click either way. Ceiling: a cancelled cold 24 GB import
374+ /// still costs the disk its twenty seconds. Upgrade: a flag
375+ /// `engine::demux::Demuxer::open` polls between clusters, which is where an
376+ /// export's own cancel already lives ([`engine::ExportHandle::cancel`]).
377+ cancelled: Arc<std::sync::atomic::AtomicBool>,
367 }378 }
368 379
369 impl Import {380 impl Import {
@@ -4117,16 +4128,23 @@ impl Player {
4117 return;4128 return;
4118 };4129 };
4119 let stage = Arc::new(std::sync::atomic::AtomicU8::new(ImportStage::Header as u8));4130 let stage = Arc::new(std::sync::atomic::AtomicU8::new(ImportStage::Header as u8));
4131+ let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
4120 // The fork is made here, once, and carried to the landing: an import is4132 // The fork is made here, once, and carried to the landing: an import is
4121- // *read* on the worker and opened again warm, while the file argv named4133+ // *probed* on the worker and registered from what came back, while the
4122- // is *opened* on the worker and handed over whole. Both leave the UI4134+ // file argv named -- and a file arriving at a window with no timeline to
4123- // thread free for the twelve seconds a cold 25 GB header walk takes;4135+ // import into -- is *opened* on the worker and handed over whole. None
4124- // opening the timeline outright is what keeps it from paying the walk4136+ // of the three leaves the UI thread anything to read: a cold 24 GB
4125- // twice on a warm one.4137+ // header walk is twenty seconds, and the window keeps painting through
4138+ // all of them.
4126 let what = arrival(self.opening.as_deref(), &path);4139 let what = arrival(self.opening.as_deref(), &path);
4140+ // The timeline the file will be checked against, taken here because the
4141+ // worker cannot reach the session: two clones and no disk
4142+ // ([`PlaybackSession::import_gate`]). `None` is a window with nothing to
4143+ // import into, which is the fork that opens the file outright.
4144+ let gate = self.session.as_ref().map(PlaybackSession::import_gate);
4127 let read = cx.background_executor().spawn({4145 let read = cx.background_executor().spawn({
4128 let (path, stage) = (path.clone(), Arc::clone(&stage));4146 let (path, stage) = (path.clone(), Arc::clone(&stage));
4129- async move { open_ahead(what, &path, &stage) }4147+ async move { open_ahead(what, &path, &stage, gate) }
4130 });4148 });
4131 let now = Instant::now();4149 let now = Instant::now();
4132 self.importing = Some(Import {4150 self.importing = Some(Import {
@@ -4135,11 +4153,18 @@ impl Player {
4135 stage,4153 stage,
4136 seen: ImportStage::Header,4154 seen: ImportStage::Header,
4137 since: now,4155 since: now,
4156+ cancelled: Arc::clone(&cancelled),
4138 });4157 });
4139 cx.spawn(async move |this, cx| {4158 cx.spawn(async move |this, cx| {
4140 let landed = read.await;4159 let landed = read.await;
4141 this.update(cx, |this, cx| {4160 this.update(cx, |this, cx| {
4142 this.importing = None;4161 this.importing = None;
4162+ // Cancelled while it read: the window was given back at the
4163+ // click and said so then, so what the worker carried is dropped
4164+ // without a second word ([`Player::cancel_import`]).
4165+ if cancelled.load(std::sync::atomic::Ordering::Relaxed) {
4166+ return;
4167+ }
4143 this.take_import(&path, landed, cx);4168 this.take_import(&path, landed, cx);
4144 // The next one is started by the repaint this notified, which4169 // The next one is started by the repaint this notified, which
4145 // is also what starts the files argv named ([`poll_import`]).4170 // is also what starts the files argv named ([`poll_import`]).
@@ -4167,6 +4192,37 @@ impl Player {
4167 }4192 }
4168 }4193 }
4169 4194
4195+ /// The Cancel beside the import line: the window is given back at once and
4196+ /// the file does not land. Everything queued behind it goes too -- a person
4197+ /// who has stopped an import of six dropped files has stopped the six, and
4198+ /// leaving five to start themselves would be the same wait under another
4199+ /// name.
4200+ ///
4201+ /// The read in flight is *not* stopped, for the reason [`Import::cancelled`]
4202+ /// gives, and the notice says as much rather than promising the disk went
4203+ /// quiet.
4204+ fn cancel_import(&mut self, cx: &mut Context<Self>) {
4205+ let Some(import) = self.importing.take() else {
4206+ return;
4207+ };
4208+ import
4209+ .cancelled
4210+ .store(true, std::sync::atomic::Ordering::Relaxed);
4211+ let waiting = self.imports.len();
4212+ self.imports.clear();
4213+ let tail = match waiting {
4214+ 0 => String::new(),
4215+ n => format!(" — {n} more dropped from the queue"),
4216+ };
4217+ let text = format!(
4218+ "IMPORT CANCELLED: {}{tail} — the read already running finishes unheeded",
4219+ file_name(&import.path)
4220+ );
4221+ eprintln!("{text}");
4222+ self.notice = Some(text.into());
4223+ cx.notify();
4224+ }
4225+
4170 /// Takes a read-ahead file into the library and nowhere else: the timeline4226 /// Takes a read-ahead file into the library and nowhere else: the timeline
4171 /// is not touched, and the row is dragged onto a lane when it is wanted4227 /// is not touched, and the row is dragged onto a lane when it is wanted
4172 /// there. Nothing moves, so nothing reseeks; a refusal is shown as the4228 /// there. Nothing moves, so nothing reseeks; a refusal is shown as the
@@ -4184,19 +4240,24 @@ impl Player {
4184 // All that is left here is to hang everything derived from it off the4240 // All that is left here is to hang everything derived from it off the
4185 // window -- the clock, the title, where an export and a save go -- and4241 // window -- the clock, the title, where an export and a save go -- and
4186 // that is arithmetic, not a read.4242 // that is arithmetic, not a read.
4187- let subs = match landed {4243+ let (subs, probe) = match landed {
4188- Landed::Read(subs) => subs,4244+ Landed::Read(subs, probe) => (subs, probe),
4189 what => {4245 what => {
4190- self.opening = None;4246+ // Only when *this* is the file argv named: a project dropped
4247+ // while that one is still being read must not make it land as
4248+ // an import.
4249+ if self.opening.as_deref() == Some(path) {
4250+ self.opening = None;
4251+ }
4191 match what {4252 match what {
4192 Landed::Project(opened) => self.install_project(path, opened, cx),4253 Landed::Project(opened) => self.install_project(path, opened, cx),
4193- Landed::Media(opened) => {4254+ Landed::Media(opened, place) => {
4194- let text = self.install_media(path, opened, true);4255+ let text = self.install_media(path, opened, place);
4195 eprintln!("{text}");4256 eprintln!("{text}");
4196 self.notice = Some(text.into());4257 self.notice = Some(text.into());
4197 cx.notify();4258 cx.notify();
4198 }4259 }
4199- Landed::Read(_) => unreachable!("matched above"),4260+ Landed::Read(..) => unreachable!("matched above"),
4200 }4261 }
4201 // The line a launch has always printed, now printed when the4262 // The line a launch has always printed, now printed when the
4202 // file actually arrives: it is the mark that says the timeline4263 // file actually arrives: it is the mark that says the timeline
@@ -4227,7 +4288,21 @@ impl Player {
4227 self.take_subtitles(path, subs, cx);4288 self.take_subtitles(path, subs, cx);
4228 return;4289 return;
4229 }4290 }
4230- let text = match self.session.as_mut().map(|session| session.import(path)) {4291+ // The container was read on the worker and what came back is registered
4292+ // here ([`engine::PlaybackSession::import_probed`]): no header walk, no
4293+ // decoder open, no probe of the timeline's own first source -- the three
4294+ // reads that used to be spent on this thread. A song and a still fork
4295+ // before the demuxer and pay their own small read
4296+ // ([`engine::PlaybackSession::import`]); a window whose timeline went
4297+ // away while the worker read falls to the slow door below, which is the
4298+ // one that can still open one.
4299+ let registered = match (self.session.as_mut(), probe) {
4300+ (Some(session), Some(Ok(probe))) => Some(session.import_probed(path, probe)),
4301+ (Some(_), Some(Err(refused))) => Some(Err(refused)),
4302+ (Some(session), None) => Some(session.import(path)),
4303+ (None, _) => None,
4304+ };
4305+ let text = match registered {
4231 Some(Ok(_)) => {4306 Some(Ok(_)) => {
4232 // The file's own subtitle tracks with it, exactly as an open4307 // The file's own subtitle tracks with it, exactly as an open
4233 // takes them: an import is the other door the same file arrives4308 // takes them: an import is the other door the same file arrives
@@ -4323,9 +4398,9 @@ impl Player {
4323 cx.spawn(async move |this, cx| {4398 cx.spawn(async move |this, cx| {
4324 let picked = picked.await;4399 let picked = picked.await;
4325 this.update(cx, |this, cx| match picked {4400 this.update(cx, |this, cx| match picked {
4326- // The same fork the drop handler makes: a project replaces the4401+ // One queue, and the fork is made when its worker starts
4327- // timeline, media joins the library.4402+ // ([`arrival`]): a project replaces the timeline, media joins
4328- Ok(Some(path)) if is_project(&path) => this.load_project(&path, cx),4403+ // the library, and neither is read on this thread.
4329 Ok(Some(path)) => this.import(&path, cx),4404 Ok(Some(path)) => this.import(&path, cx),
4330 // Cancelled: the user already knows what happened.4405 // Cancelled: the user already knows what happened.
4331 Ok(None) => {}4406 Ok(None) => {}
@@ -4513,18 +4588,13 @@ impl Player {
4513 cx.notify();4588 cx.notify();
4514 }4589 }
4515 4590
4516- /// Swaps the whole timeline for one restored from a `.edith`. Like an4591+ /// Swaps the whole timeline for one restored from a `.edith`, for
4517- /// import this arrives by drop and so checks the export guard for itself.4592+ /// [`Player::install_media`]'s reason: the open is a worker's -- a project
4518- /// The new session is built before anything is replaced, so a refusal is4593+ /// naming a 24 GB film opens that film, which is the same twenty seconds
4519- /// shown as the engine worded it and leaves what is playing alone.4594+ /// ([`arrival`] sends every `.edith` through the one queue) -- and this is
4520- fn load_project(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {4595+ /// what is left once it lands. Nothing is replaced until the new session is
4521- let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());4596+ /// in hand, so a refusal is shown as the engine worded it and leaves what is
4522- self.install_project(path, opened, cx);4597+ /// playing alone.
4523- }
4524-
4525- /// The second half of it, for [`Player::install_media`]'s reason: a
4526- /// `.edith` named on the command line is opened on a worker and only
4527- /// installed here.
4528 fn install_project(4598 fn install_project(
4529 &mut self,4599 &mut self,
4530 path: &std::path::Path,4600 path: &std::path::Path,
@@ -5539,12 +5609,11 @@ impl Render for Player {
5539 return;5609 return;
5540 }5610 }
5541 for path in paths.paths() {5611 for path in paths.paths() {
5542- // A project replaces the timeline, media joins the library.5612+ // One queue for all of them, in arrival order: the fork --
5543- if is_project(path) {5613+ // a project replaces the timeline, media joins the library
5544- this.load_project(path, cx);5614+ // -- is made when each one's worker starts ([`arrival`]),
5545- } else {5615+ // and neither is read on this thread.
5546- this.import(path, cx);5616+ this.import(path, cx);
5547- }
5548 }5617 }
5549 }))5618 }))
5550 // A drop event carries no path of its own -- gpui only tells the5619 // A drop event carries no path of its own -- gpui only tells the
@@ -5764,7 +5833,7 @@ impl Render for Player {
5764 // the picture nothing the rest of the time. The import's line sits5833 // the picture nothing the rest of the time. The import's line sits
5765 // over the notice's: a notice is about something that has already5834 // over the notice's: a notice is about something that has already
5766 // happened, and this is about something still happening.5835 // happened, and this is about something still happening.
5767- .children(self.import_bar())5836+ .children(self.import_bar(cx))
5768 // The same slot and the same reason: work still going on, said out5837 // The same slot and the same reason: work still going on, said out
5769 // loud because a still picture is the only other evidence of it.5838 // loud because a still picture is the only other evidence of it.
5770 .children(self.seek_bar())5839 .children(self.seek_bar())
@@ -7181,7 +7250,11 @@ impl Player {
7181 /// where in the file it is, so a fill would have to invent the one number7250 /// where in the file it is, so a fill would have to invent the one number
7182 /// this cannot know. What it does say truthfully is "something is still7251 /// this cannot know. What it does say truthfully is "something is still
7183 /// running", which is exactly the question a frozen-looking window raises.7252 /// running", which is exactly the question a frozen-looking window raises.
7184- fn import_bar(&self) -> Option<impl IntoElement> {7253+ ///
7254+ /// ...and beside them the way out. A read that may be twenty seconds of a
7255+ /// cold 24 GB film needs one, and the only honest place for it is the line
7256+ /// that says the read is happening ([`Player::cancel_import`]).
7257+ fn import_bar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
7185 let import = self.importing.as_ref()?;7258 let import = self.importing.as_ref()?;
7186 let elapsed = import.started.elapsed().as_secs_f32();7259 let elapsed = import.started.elapsed().as_secs_f32();
7187 let line = import_line(7260 let line = import_line(
@@ -7206,7 +7279,23 @@ impl Player {
7206 .px(px(12.))7279 .px(px(12.))
7207 .py(px(6.))7280 .py(px(6.))
7208 .bg(rgb(SURFACE))7281 .bg(rgb(SURFACE))
7209- .child(div().flex_1().min_w(px(0.)).child(line))7282+ .child(
7283+ div()
7284+ .flex()
7285+ .items_center()
7286+ .gap(px(8.))
7287+ .child(div().flex_1().min_w(px(0.)).child(line))
7288+ .child(control(
7289+ "cancel-import",
7290+ None,
7291+ "Cancel",
7292+ "stops this file and anything queued behind it; the read already \
7293+ running finishes unheeded"
7294+ .to_string(),
7295+ true,
7296+ cx.listener(|this, _: &ClickEvent, _, cx| this.cancel_import(cx)),
7297+ )),
7298+ )
7210 .child(7299 .child(
7211 div()7300 div()
7212 .relative()7301 .relative()
@@ -10723,17 +10812,31 @@ fn carries_subtitles(path: &std::path::Path) -> bool {
10723 /// started. An import is *read* and thrown away; the file argv named is opened10812 /// started. An import is *read* and thrown away; the file argv named is opened
10724 /// outright, because nothing else is going to open it afterwards.10813 /// outright, because nothing else is going to open it afterwards.
10725 enum Landed {10814 enum Landed {
10726- /// An import: pages warmed, and the subtitle tracks the walk found *kept* --10815+ /// An import into a timeline that is up: the container probed and the
10727- /// the walk is the expensive half and the worker is where it belongs, so10816+ /// subtitle tracks walked, both *kept* -- they are the expensive halves and
10728- /// [`Player::take_import`] is left with a push ([`subtitle_tail`]).10817+ /// the worker is where they belong, so [`Player::take_import`] is left with
10729- Read(Subs),10818+ /// two pushes ([`engine::PlaybackSession::import_probed`],
10730- /// The media argv named, with the tail its subtitle tracks earn: a whole10819+ /// [`subtitle_tail`]).
10731- /// timeline, ready to be hung off the window, or the engine's refusal.10820+ Read(Subs, Probe),
10732- Media(Result<(PlaybackSession, String), String>),10821+ /// A whole timeline the worker opened, with the tail its subtitle tracks
10733- /// The `.edith` argv named, restored.10822+ /// earn, ready to be hung off the window -- or the engine's refusal. `true`
10823+ /// is the media argv named, which *becomes* the timeline; `false` is a file
10824+ /// arriving at a window that had none, which fills the library and leaves
10825+ /// the lanes empty for a drag ([`Player::install_media`]).
10826+ Media(Result<(PlaybackSession, String), String>, bool),
10827+ /// A `.edith`, restored: argv's, and the one a drop or the Import button
10828+ /// brought ([`arrival`]).
10734 Project(Result<PlaybackSession, String>),10829 Project(Result<PlaybackSession, String>),
10735 }10830 }
10736 10831
10832+/// What the container walk found, for [`Player::take_import`] to register, or
10833+/// the engine's refusal in the words it would have used on the UI thread.
10834+///
10835+/// `None` for the doors that never reach a demuxer: a song, a still and a
10836+/// subtitle file, whose own small reads stay where they were
10837+/// ([`engine::PlaybackSession::import`]).
10838+type Probe = Option<engine::Result<engine::ImportProbe>>;
10839+
10737 /// A media file opened as a session, with the subtitle tracks it carries inside10840 /// A media file opened as a session, with the subtitle tracks it carries inside
10738 /// it taken in the same breath -- the two reads a file costs, in the one place10841 /// it taken in the same breath -- the two reads a file costs, in the one place
10739 /// both doors ([`Player::open_media`] and the worker below) go through.10842 /// both doors ([`Player::open_media`] and the worker below) go through.
@@ -10762,68 +10865,92 @@ fn open_ahead(
10762 what: Landing,10865 what: Landing,
10763 path: &std::path::Path,10866 path: &std::path::Path,
10764 stage: &std::sync::atomic::AtomicU8,10867 stage: &std::sync::atomic::AtomicU8,
10868+ gate: Option<engine::ImportGate>,
10765 ) -> Landed {10869 ) -> Landed {
10766- use std::sync::atomic::Ordering::Relaxed;
10767 match what {10870 match what {
10768- Landing::Import => Landed::Read(read_ahead(path, stage)),10871+ Landing::Import => read_ahead(path, stage, gate),
10769 Landing::Project => {10872 Landing::Project => {
10770 let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());10873 let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());
10771 Landed::Project(opened)10874 Landed::Project(opened)
10772 }10875 }
10773- Landing::Open => {10876+ Landing::Open => open_whole(path, true, stage),
10774- let opened = PlaybackSession::open(path).map_err(|e| e.to_string());
10775- // The same two stages a read reports, because they are the same two
10776- // reads: the container, and then the tracks inside it.
10777- stage.store(ImportStage::Subtitles as u8, Relaxed);
10778- Landed::Media(opened.map(|mut session| {
10779- let subs = subtitle_notice(&mut session, path).unwrap_or_default();
10780- (session, subs)
10781- }))
10782- }
10783 }10877 }
10784 }10878 }
10785 10879
10786-/// Reads, off the UI thread, exactly what the import that follows is about to10880+/// A whole timeline, opened here and handed over: the file argv named (`place`,
10787-/// read. The container's header is read for the page cache and thrown away: a10881+/// which *is* the timeline) and a file arriving at a window with no timeline to
10788-/// cold header walk of a 29 GB remux is 11 s and a warm one is 150 ms10882+/// import into, which fills the library instead. One function because they are
10789-/// (measured on a real 2160p h265 remux), so this call is the eleven10883+/// one read -- the engine's two doors differ by which lanes come up empty
10790-/// seconds and [`Player::take_import`] is the hundred and fifty milliseconds.10884+/// ([`engine::PlaybackSession::open_library`]), not by what they walk.
10791-/// The window keeps painting through the eleven.10885+fn open_whole(path: &std::path::Path, place: bool, stage: &std::sync::atomic::AtomicU8) -> Landed {
10792-///10886+ use std::sync::atomic::Ordering::Relaxed;
10793-/// Header errors are dropped on purpose: a file that cannot be read is refused10887+ let opened = match place {
10794-/// by the engine a moment later, in the engine's own words, and a refusal read10888+ true => PlaybackSession::open(path),
10795-/// twice is a refusal worded twice. The *subtitle* refusal is carried back10889+ false => PlaybackSession::open_library(path),
10796-/// instead of dropped, for exactly that reason -- nothing walks those cues a10890+ };
10797-/// second time to re-word it.10891+ // The same two stages a read reports, because they are the same two
10892+ // reads: the container, and then the tracks inside it.
10893+ stage.store(ImportStage::Subtitles as u8, Relaxed);
10894+ Landed::Media(
10895+ opened.map_err(|e| e.to_string()).map(|mut session| {
10896+ let subs = subtitle_notice(&mut session, path).unwrap_or_default();
10897+ (session, subs)
10898+ }),
10899+ place,
10900+ )
10901+}
10902+
10903+/// Reads, off the UI thread, everything the import that follows would have read
10904+/// -- and hands all of it over. Nothing here is a warm-up any more: the
10905+/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the
10906+/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came
10907+/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms
10908+/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue
10909+/// walk -- all of it here, and the window keeps painting through it.
10798 ///10910 ///
10799-/// `stage` is what the line above the panel is naming while this runs.10911+/// `gate` is the timeline the file is checked against
10912+/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started
10913+/// because a worker cannot reach the session. `None` is a window with no
10914+/// timeline to import into: then there is nothing to check against and nothing
10915+/// to register, so the file is *opened* here instead, whole
10916+/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread,
10917+/// rather than on the one that draws.
10800 ///10918 ///
10801-/// The subtitle half is not thrown away: it is *the* answer, handed back for10919+/// The header error is carried back now rather than dropped: it is the engine's
10802-/// [`Player::take_import`] to push ([`subtitle_tail`]) rather than walked a10920+/// own refusal, from the only walk anybody makes, so it is worded once and shown
10803-/// second time on the render thread -- 234 ms of a warmed 25 GB remux and 1.3 s10921+/// at the landing. The subtitle refusal travels beside it for the same reason.
10804-/// of a cold 3 GB one, which is what a frozen window is made of.
10805 ///10922 ///
10806-/// ponytail: only the subtitle half is handed over. The container's own header10923+/// `stage` is what the line above the panel is naming while this runs.
10807-/// is still merely *warmed* here, so [`PlaybackSession::import`] and10924+fn read_ahead(
10808-/// [`open_session`] walk it again on the UI thread -- 2.8 s of that same 25 GB10925+ path: &std::path::Path,
10809-/// file. Ceiling: the media walk, not the subtitle one. The upgrade is the10926+ stage: &std::sync::atomic::AtomicU8,
10810-/// engine door this comment has always named: one that takes the header this10927+ gate: Option<engine::ImportGate>,
10811-/// already parsed, the way [`PlaybackSession::add_subtitle_tracks`] takes the10928+) -> Landed {
10812-/// cues this already read.
10813-fn read_ahead(path: &std::path::Path, stage: &std::sync::atomic::AtomicU8) -> Subs {
10814 use std::sync::atomic::Ordering::Relaxed;10929 use std::sync::atomic::Ordering::Relaxed;
10815 stage.store(ImportStage::Header as u8, Relaxed);10930 stage.store(ImportStage::Header as u8, Relaxed);
10816- // The three doors an import goes through, each warmed by the call the10931+ // Nothing to import into, and nothing a subtitle file needs opened: the
10817- // engine will make: a song is measured by its duration, a still by its10932+ // first opens the library itself, here; the second has no container at all.
10818- // header, and everything else by the container's.10933+ let Some(gate) = gate else {
10819- if engine::is_audio(path) {10934+ return match is_subtitle(path) {
10935+ true => Landed::Read(walk_subtitles(path), None),
10936+ false => open_whole(path, false, stage),
10937+ };
10938+ };
10939+ // The three doors an import goes through: a song is measured by its
10940+ // duration and a still by its header -- both the engine's own reads, warmed
10941+ // here and paid again at the landing, which is a header apiece -- and
10942+ // everything else is the container walk, which is handed over whole.
10943+ let probe = if engine::is_audio(path) {
10820 engine::AudioSession::duration_secs(path).ok();10944 engine::AudioSession::duration_secs(path).ok();
10821- } else if !engine::is_image(path) && !is_subtitle(path) {10945+ None
10822- engine::demux::Demuxer::open(path).ok();10946+ } else if engine::is_image(path) || is_subtitle(path) {
10823- }10947+ None
10948+ } else {
10949+ Some(PlaybackSession::probe_import(gate, path))
10950+ };
10824 stage.store(ImportStage::Subtitles as u8, Relaxed);10951 stage.store(ImportStage::Subtitles as u8, Relaxed);
10825 // ...and the tracks inside it, kept.10952 // ...and the tracks inside it, kept.
10826- walk_subtitles(path)10953+ Landed::Read(walk_subtitles(path), probe)
10827 }10954 }
10828 10955
10829 /// Every subtitle track a file carries, cues and all -- the walk that costs, in10956 /// Every subtitle track a file carries, cues and all -- the walk that costs, in
@@ -14051,13 +14178,19 @@ enum Landing {
14051 14178
14052 /// Which of the three a queued file is (`landing` above is the drag's).14179 /// Which of the three a queued file is (`landing` above is the drag's).
14053 /// `opening` is the one path argv named and is cleared as it lands, so a second14180 /// `opening` is the one path argv named and is cleared as it lands, so a second
14054-/// arrival of the same path -- a drop of the film that is already open -- is an14181+/// arrival of the same *media* path -- a drop of the film that is already open
14055-/// import, which is what a drop has always been.14182+/// -- is an import, which is what a drop has always been.
14183+///
14184+/// A `.edith` is never an import, whichever door it came through: it is a whole
14185+/// timeline and there is nothing to add it to. Argv's, a dropped one and the
14186+/// Import button's are one landing, so the seconds its open costs are the
14187+/// worker's for all three ([`open_ahead`]) and the line above the panel names it
14188+/// while it runs.
14056 fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing {14189 fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing {
14057- match opening == Some(path) {14190+ match (is_project(path), opening == Some(path)) {
14058- false => Landing::Import,14191+ (true, _) => Landing::Project,
14059- true if is_project(path) => Landing::Project,14192+ (false, true) => Landing::Open,
14060- true => Landing::Open,14193+ (false, false) => Landing::Import,
14061 }14194 }
14062 }14195 }
14063 14196
@@ -17873,6 +18006,7 @@ mod tests {
17873 seen: ImportStage::Header,18006 seen: ImportStage::Header,
17874 // As if the header had been running for those nine seconds.18007 // As if the header had been running for those nine seconds.
17875 since: started,18008 since: started,
18009+ cancelled: Arc::default(),
17876 };18010 };
17877 // Nine seconds inside one stage: past the wait a person tolerates, so18011 // Nine seconds inside one stage: past the wait a person tolerates, so
17878 // the line stops pretending it is a progress line.18012 // the line stops pretending it is a progress line.
@@ -17944,9 +18078,11 @@ mod tests {
17944 // Cleared as it lands: a drop of the film already on the timeline is an18078 // Cleared as it lands: a drop of the film already on the timeline is an
17945 // import, which is what a drop has always been.18079 // import, which is what a drop has always been.
17946 assert_eq!(arrival(None, &film), Landing::Import);18080 assert_eq!(arrival(None, &film), Landing::Import);
17947- // A window opened empty has no named file at all, and everything that18081+ // ...except a `.edith`, which is a whole timeline and has nothing to be
17948- // arrives at it is an import.18082+ // imported into: dropped or picked, it lands where argv's does, and its
17949- assert_eq!(arrival(None, &project), Landing::Import);18083+ // open is the worker's like every other.
18084+ assert_eq!(arrival(None, &project), Landing::Project);
18085+ assert_eq!(arrival(Some(&film), &project), Landing::Project);
17950 }18086 }
17951 18087
17952 /// What the window says while the file argv named is being read: the file's18088 /// What the window says while the file argv named is being read: the file's
@@ -18128,11 +18264,25 @@ mod tests {
18128 assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);18264 assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
18129 }18265 }
18130 18266
18131- /// The read-ahead is a *cache warmer* and nothing else: whatever it did or18267+ /// The two halves a worker hands back for an import, unwrapped: every import
18132- /// failed to do, the import that follows lands exactly the rows, lengths18268+ /// lands as a [`Landed::Read`], and a test that has to say so at four call
18133- /// and refusals it landed before there was a worker at all.18269+ /// sites is saying it once here.
18270+ fn read_parts(
18271+ path: &std::path::Path,
18272+ stage: &std::sync::atomic::AtomicU8,
18273+ gate: Option<engine::ImportGate>,
18274+ ) -> (Subs, crate::Probe) {
18275+ match read_ahead(path, stage, gate) {
18276+ crate::Landed::Read(subs, probe) => (subs, probe),
18277+ _ => panic!("an import into a timeline that is up lands as a read"),
18278+ }
18279+ }
18280+
18281+ /// The import door's split, which is what keeps the render thread out of a
18282+ /// header walk: what the worker probed and what the landing registers add up
18283+ /// to exactly the rows, lengths and refusals the in-place import lands.
18134 #[test]18284 #[test]
18135- fn reading_ahead_changes_nothing_about_what_an_import_lands() {18285+ fn probing_ahead_lands_exactly_what_importing_in_place_lands() {
18136 use std::sync::atomic::AtomicU8;18286 use std::sync::atomic::AtomicU8;
18137 let stage = AtomicU8::new(ImportStage::Header as u8);18287 let stage = AtomicU8::new(ImportStage::Header as u8);
18138 let plain = {18288 let plain = {
@@ -18145,49 +18295,76 @@ mod tests {
18145 session.timeline_duration(),18295 session.timeline_duration(),
18146 )18296 )
18147 };18297 };
18148- let warmed = {18298+ let split = {
18149 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18299 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18150 session.set_gain(0.0);18300 session.set_gain(0.0);
18151- let subs = read_ahead(&asset("test_av2.mp4"), &stage).expect("an mp4 is readable");18301+ let (subs, probe) =
18302+ read_parts(&asset("test_av2.mp4"), &stage, Some(session.import_gate()));
18152 // This mp4 is walked now (an mp4 can carry `tx3g`) and has no18303 // This mp4 is walked now (an mp4 can carry `tx3g`) and has no
18153 // subtitle track in it, so the worker hands over an empty list --18304 // subtitle track in it, so the worker hands over an empty list --
18154 // the same thing the import lands with.18305 // the same thing the import lands with.
18155- assert!(subs.is_empty());18306+ assert!(subs.expect("an mp4 is readable").is_empty());
18156- session.import(&asset("test_av2.mp4")).expect("av2 matches");18307+ let probe = probe
18308+ .expect("a container is probed on the worker")
18309+ .expect("av2 matches");
18310+ session
18311+ .import_probed(&asset("test_av2.mp4"), probe)
18312+ .expect("av2 matches");
18157 (18313 (
18158 session.sources().to_vec(),18314 session.sources().to_vec(),
18159 session.file_frames(&asset("test_av2.mp4")),18315 session.file_frames(&asset("test_av2.mp4")),
18160 session.timeline_duration(),18316 session.timeline_duration(),
18161 )18317 )
18162 };18318 };
18163- assert_eq!(plain, warmed);18319+ assert_eq!(plain, split);
18164 // ...and it leaves the stage where the line can read it: a worker that18320 // ...and it leaves the stage where the line can read it: a worker that
18165 // never announced its second read would show one that never ends.18321 // never announced its second read would show one that never ends.
18166 assert_eq!(18322 assert_eq!(
18167 ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)),18323 ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)),
18168 ImportStage::Subtitles18324 ImportStage::Subtitles
18169 );18325 );
18170- // A refusal is still the engine's refusal, warmed or not: a file of18326+ // A refusal is the engine's refusal, and now it is *the* refusal: the
18171- // another rate is no more importable for having been read first.18327+ // walk happens once, on the worker, so what the probe says is what the
18172- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18328+ // notice shows -- worded exactly as importing in place worded it.
18173- session.set_gain(0.0);
18174- drop(read_ahead(&asset("test_25fps.mp4"), &stage));
18175- let warmed = session.import(&asset("test_25fps.mp4"));
18176 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");18329 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18177 session.set_gain(0.0);18330 session.set_gain(0.0);
18331+ let (_, probe) = read_parts(&asset("test_25fps.mp4"), &stage, Some(session.import_gate()));
18332+ let on_the_worker = probe
18333+ .expect("a container is probed")
18334+ .map(|_| ())
18335+ .map_err(|e| e.to_string());
18178 assert_eq!(18336 assert_eq!(
18179- warmed.map_err(|e| e.to_string()),18337+ on_the_worker,
18180 session18338 session
18181 .import(&asset("test_25fps.mp4"))18339 .import(&asset("test_25fps.mp4"))
18340+ .map(|_| ())
18182 .map_err(|e| e.to_string())18341 .map_err(|e| e.to_string())
18183 );18342 );
18184- // A path nothing can read is the worker's business to survive, not to18343+ // A timeline that moved while the worker read is not one the probe was
18185- // report: the engine says so a moment later, in its own words. The18344+ // decided against, so the probe is not trusted -- the import is simply
18186- // subtitle half *is* carried back, because nothing walks it again to18345+ // taken the slow way and lands the same row.
18187- // re-word it -- and it is a refusal, not a panic.18346+ let mut moved = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18347+ moved.set_gain(0.0);
18348+ let (_, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(moved.import_gate()));
18349+ moved.import(&asset("test_still.png")).expect("a still joins");
18350+ let stale = probe.expect("a container is probed").expect("av2 matches");
18351+ assert_eq!(
18352+ moved.import_probed(&asset("test_av2.mp4"), stale).ok(),
18353+ Some(2),
18354+ "a stale probe still lands the file, by the door that re-reads it"
18355+ );
18356+ // A path nothing can read is refused by the worker now, in the engine's
18357+ // own words: nothing walks it a second time to re-word it, and neither
18358+ // half is a panic.
18359+ let (subs, probe) = read_parts(
18360+ std::path::Path::new("/no/such/film.mkv"),
18361+ &stage,
18362+ Some(session.import_gate()),
18363+ );
18364+ assert!(subs.is_err(), "the cue walk comes back as a refusal");
18188 assert!(18365 assert!(
18189- read_ahead(std::path::Path::new("/no/such/film.mkv"), &stage).is_err(),18366+ probe.expect("a container is probed").is_err(),
18190- "an unreadable mkv comes back as the engine's refusal"18367+ "and so does the container walk"
18191 );18368 );
18192 }18369 }
18193 18370
@@ -18206,12 +18383,14 @@ mod tests {
18206 let said = subtitle_notice(&mut in_place, &film);18383 let said = subtitle_notice(&mut in_place, &film);
18207 let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open");18384 let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open");
18208 split.set_gain(0.0);18385 split.set_gain(0.0);
18209- let walked = read_ahead(&film, &stage).expect("the mkv is readable");18386+ let (walked, _) = read_parts(&film, &stage, Some(split.import_gate()));
18387+ let walked = walked.expect("the mkv is readable");
18210 assert_eq!(subtitle_tail(&mut split, Ok(walked)), said);18388 assert_eq!(subtitle_tail(&mut split, Ok(walked)), said);
18211 assert_eq!(split.subtitles().len(), in_place.subtitles().len());18389 assert_eq!(split.subtitles().len(), in_place.subtitles().len());
18212 // The same file twice is still one row, and still says so: the dedupe18390 // The same file twice is still one row, and still says so: the dedupe
18213 // lives in the push, which is the half that stayed here.18391 // lives in the push, which is the half that stayed here.
18214- let again = read_ahead(&film, &stage).expect("the mkv is readable");18392+ let (again, _) = read_parts(&film, &stage, Some(split.import_gate()));
18393+ let again = again.expect("the mkv is readable");
18215 assert_eq!(subtitle_tail(&mut split, Ok(again)), None);18394 assert_eq!(subtitle_tail(&mut split, Ok(again)), None);
18216 // A standalone `.srt` is walked by the same worker: an import of one is18395 // A standalone `.srt` is walked by the same worker: an import of one is
18217 // not a door that reads on the render thread either.18396 // not a door that reads on the render thread either.
@@ -18220,7 +18399,10 @@ mod tests {
18220 .canonicalize()18399 .canonicalize()
18221 .expect("the subtitle fixture");18400 .expect("the subtitle fixture");
18222 assert_eq!(18401 assert_eq!(
18223- read_ahead(&srt, &stage).expect("the srt is readable").len(),18402+ read_parts(&srt, &stage, Some(split.import_gate()))
18403+ .0
18404+ .expect("the srt is readable")
18405+ .len(),
18224 118406 1
18225 );18407 );
18226 // ...and a refusal is worded as a tail, never as a failed import.18408 // ...and a refusal is worded as a tail, never as a failed import.
crates/engine/src/lib.rsmodified+1 -1
@@ -33,7 +33,7 @@ pub use decode::{DecodeSession, Frame, image_size};
33 pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate};33 pub use demux::{Codec, MediaBitrate, VideoMeta, probe_bitrate};
34 pub use export::ExportHandle;34 pub use export::ExportHandle;
35 pub use mux::{AudioParams, Mp4Muxer, VideoParams};35 pub use mux::{AudioParams, Mp4Muxer, VideoParams};
36-pub use playback::PlaybackSession;36+pub use playback::{ImportGate, ImportProbe, PlaybackSession};
37 pub use project::{Clip, Project, Rate, Speed};37 pub use project::{Clip, Project, Rate, Speed};
38 38
39 /// Whether a path names a standalone audio file -- a source with no picture,39 /// Whether a path names a standalone audio file -- a source with no picture,
crates/engine/src/playback.rsmodified+88 -4
@@ -318,6 +318,28 @@ enum Dirty {
318 Both,318 Both,
319 }319 }
320 320
321+/// What an import is held to, off a timeline that is already up: the sources
322+/// its sound has to agree with and the meta its rate is read against. Owned and
323+/// `Send`, so the check itself can run on a worker with no session in reach --
324+/// which is the whole point ([`PlaybackSession::probe_import`]).
325+#[derive(Clone, Debug, PartialEq)]
326+pub struct ImportGate {
327+ sources: Vec<Source>,
328+ timeline: VideoMeta,
329+}
330+
331+/// A file read and accepted, waiting to be registered: what
332+/// [`PlaybackSession::probe_import`] found and
333+/// [`PlaybackSession::import_probed`] pushes. Carries the gate it was decided
334+/// against, so a timeline that moved under it can be noticed rather than
335+/// trusted.
336+#[derive(Clone, Debug)]
337+pub struct ImportProbe {
338+ gate: ImportGate,
339+ meta: VideoMeta,
340+ rate: Rate,
341+}
342+
321 impl PlaybackSession {343 impl PlaybackSession {
322 /// Opens `path` and starts both decode workers. Only video failure is fatal:344 /// Opens `path` and starts both decode workers. Only video failure is fatal:
323 /// a file we cannot hear is still a file we can watch.345 /// a file we cannot hear is still a file we can watch.
@@ -2085,21 +2107,83 @@ impl PlaybackSession {
2085 if crate::is_image(path) {2107 if crate::is_image(path) {
2086 return self.import_image(path);2108 return self.import_image(path);
2087 }2109 }
2110+ // Both halves on this thread, which is what a caller with nothing else
2111+ // to do wants; a front-end splits them across a worker instead
2112+ // ([`probe_import`](Self::probe_import)).
2113+ let probe = Self::probe_import(self.import_gate(), path)?;
2114+ Ok(self.take_probe(path, probe))
2115+ }
2116+
2117+ /// Everything an import is *checked against*, taken off this timeline in
2118+ /// one owned piece: the sources its audio must agree with and the meta its
2119+ /// rate is read against. Costs two clones and touches no disk, so the
2120+ /// thread holding the session can hand it to a worker and go on painting.
2121+ pub fn import_gate(&self) -> ImportGate {
2122+ ImportGate {
2123+ sources: self.project.sources().to_vec(),
2124+ timeline: self.meta,
2125+ }
2126+ }
2127+
2128+ /// The reading half of [`import`](Self::import), with no session in it: the
2129+ /// container's header, the decoder this machine would open it with, and the
2130+ /// audio check against the gate -- every read an import pays.
2131+ ///
2132+ /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
2133+ /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
2134+ /// timeline's own first source. So a front-end runs *this* on its background
2135+ /// executor and hands what comes back to
2136+ /// [`import_probed`](Self::import_probed), which costs a push -- the same
2137+ /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
2138+ /// reason.
2139+ ///
2140+ /// The container fork only: a song and a still fork before the demuxer
2141+ /// ([`import`](Self::import)) and pay a header read of their own.
2142+ ///
2143+ /// The `Err` is the refusal [`import`](Self::import) would have given, in
2144+ /// the same words -- nothing is refused twice and nothing is worded twice.
2145+ pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
2088 let (meta, _) = Demuxer::open(path)?;2146 let (meta, _) = Demuxer::open(path)?;
2089- let first = self.first_audio()?;2147+ let first = first_audio_of(&gate.sources)?;
2090 // Stream 0: an import brings a file in on its first audio track, and2148 // Stream 0: an import brings a file in on its first audio track, and
2091 // [`place_stream_at`](Self::place_stream_at) is how any other one of2149 // [`place_stream_at`](Self::place_stream_at) is how any other one of
2092 // its streams reaches the timeline afterwards.2150 // its streams reaches the timeline afterwards.
2093 // ...and the rate it will be read at comes back from the check that2151 // ...and the rate it will be read at comes back from the check that
2094 // accepted it, so the number the refusal was decided on is the number2152 // accepted it, so the number the refusal was decided on is the number
2095 // the file is played by.2153 // the file is played by.
2096- let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;2154+ let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
2155+ Ok(ImportProbe { gate, meta, rate })
2156+ }
2157+
2158+ /// Registers a file already read by [`probe_import`](Self::probe_import).
2159+ /// The whole of what an import costs the thread that calls it: a source
2160+ /// entry and its length, no open, no seek, no decode -- which is why the
2161+ /// probe is a separate door.
2162+ ///
2163+ /// The timeline may have moved while the worker read: a source removed or a
2164+ /// file opened is a different set of things the probe was checked against,
2165+ /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
2166+ /// imported the slow way rather than trusted. Same answer either way, so no
2167+ /// caller has to know which arm it took.
2168+ pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
2169+ match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
2170+ true => Ok(self.take_probe(path, probe)),
2171+ false => self.import(path),
2172+ }
2173+ }
2174+
2175+ /// The push both import doors end at.
2176+ fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
2097 let source = self.project.import(path, 0);2177 let source = self.project.import(path, 0);
2098 // Its length *on this timeline*: a file shot slower than the timeline2178 // Its length *on this timeline*: a file shot slower than the timeline
2099 // runs covers more frames than it holds, which is the whole of what2179 // runs covers more frames than it holds, which is the whole of what
2100 // placing it at another rate means ([`Rate`]).2180 // placing it at another rate means ([`Rate`]).
2101- self.note_frames(source, rate.timeline_at(meta.frame_count), rate);2181+ self.note_frames(
2102- Ok(source)2182+ source,
2183+ probe.rate.timeline_at(probe.meta.frame_count),
2184+ probe.rate,
2185+ );
2186+ source
2103 }2187 }
2104 2188
2105 /// The same registration for a standalone audio file: a song has no2189 /// The same registration for a standalone audio file: a song has no