diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index 5885505..34b027f 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -645,6 +645,13 @@ pub(crate) fn export_settings( // caller that writes a file; the rest of them are asking about the // bitrate and the format. subtitles: Vec::new(), + // Neither is a delivery setting: both belong to the stand-ins + // [`engine::proxy`] writes -- every frame a key frame costs bits + // nobody delivering wants, and a file kept in its source's colour + // space is one for this editor to read back rather than to hand + // anybody. + intra_only: false, + keep_source_colour: false, } } diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index f73d9e1..25f4196 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -62,6 +62,43 @@ pub(crate) enum Wave { Peaks(Arc>), } +/// What a source's stand-in is up to ([`engine::proxy`]). Kept per file and +/// filled like every other library fact -- presence means "asked", so a repaint +/// mid-encode cannot start a second one. +pub(crate) enum Proxy { + /// The header is being read to find out whether this file wants one. Its + /// own state because it is what makes "how many are in flight" a number: + /// the answer comes back on a worker, and until it does this file may still + /// turn into an encode. + Asked, + /// A file this machine cuts at speed as it is: no stand-in, and none + /// wanted ([`engine::proxy::wanted`]). + Native, + /// Being made, in the background, while the film keeps playing. + Making(engine::proxy::Job), + /// There is one in the cache. What the switch actually plays. + Ready, + /// It could not be made: the film itself is what plays, and the row says + /// so rather than leaving a bar that never fills. + Failed, +} + +impl Proxy { + /// What the library row says about it, or nothing at all for a file that + /// never wanted one -- a row per source is not the place to announce that + /// nothing is happening. + pub(crate) fn detail(&self) -> String { + match self { + Self::Asked | Self::Native => String::new(), + // Rounded down: a bar that says 100% while the encoder is still + // writing is the one number a progress line must never show. + Self::Making(job) => format!("proxy {}%", (job.progress() * 100.) as u32), + Self::Ready => "proxy".to_string(), + Self::Failed => "no proxy".to_string(), + } + } +} + /// The import a worker is reading, as the line above the panel shows it. No /// fraction anywhere: neither read reports how far into the file it has come, /// so what is honest is the file's name, the stage, and two clocks -- one that diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 19f55c9..96726e4 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -110,6 +110,11 @@ actions! { Mix, ToggleSnap, ToggleSubtitles, + /// Cut on the stand-ins or on the films themselves + /// ([`engine::proxy`]): what the picture is decoded from, and nothing + /// else -- the sound and every export stay the film's whichever way it + /// is set. + ToggleProxies, /// The window's own colours, which belong to the person looking at them and /// not to the project: a list of the palettes, opened here and from the /// toolbar's Theme button. It was a build feature once, which made it a @@ -173,6 +178,7 @@ impl ActionId { ActionId::Mix => "Mix: track volumes and the limiter…", ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)", ActionId::ToggleSubtitles => "Subtitles on / off over the picture", + ActionId::ToggleProxies => "Proxies on / off for the picture", ActionId::Theme => "Theme: the window's colours…", ActionId::CancelExport => "Cancel export", ActionId::ShowActions => "All actions and their keys…", @@ -227,6 +233,7 @@ impl ActionId { ActionId::Mix => "mix", ActionId::ToggleSnap => "toggle-snap", ActionId::ToggleSubtitles => "toggle-subtitles", + ActionId::ToggleProxies => "toggle-proxies", ActionId::Theme => "theme", ActionId::CancelExport => "cancel-export", ActionId::ShowActions => "show-actions", @@ -279,6 +286,10 @@ impl ActionId { | ActionId::ZoomOut | ActionId::ZoomFit | ActionId::ToggleSubtitles + // ...and which file the picture is decoded from, which changes + // nothing that is saved and nothing that is exported: a stand-in + // is what one watches while cutting, not what one delivers. + | ActionId::ToggleProxies // ...and what the whole window is painted in: it edits nothing at // all, it is what one is looking *with*. | ActionId::Theme => Category::View, @@ -811,6 +822,11 @@ impl Keymap { // the rest of the things one *looks* at, and nowhere near the // two keys that delete. b(ActionId::ToggleSubtitles, "t", false), + // The stand-ins take ctrl+p, the p of the word: the unshifted + // one is the fit policy, and a ctrl chord is right for a switch + // thrown once for a whole session rather than one wanted under + // a hand -- the theme takes ctrl+h for that reason. + b(ActionId::ToggleProxies, "p", true), // The theme takes ctrl+h -- the h of the word, since "t" is the // subtitles and ctrl+t takes one off -- and a ctrl chord because // it is a preference set once, not a stroke wanted under a hand @@ -1085,7 +1101,8 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 49); + assert_eq!(k.entries().len(), 50); + assert_eq!(k.lookup("p", true), Some(ActionId::ToggleProxies)); assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions)); assert_eq!(k.lookup("h", true), Some(ActionId::Theme)); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs index 8c3dc71..f013058 100644 --- a/crates/app/src/layout.rs +++ b/crates/app/src/layout.rs @@ -38,6 +38,11 @@ pub(crate) const LABEL_MIN_W: f32 = 36.; /// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade /// is a second, finer pass over the visible span only, cached like `waves` is. pub(crate) const WAVE_BPS: u32 = 40; +/// How many stand-ins ([`engine::proxy`]) may be in flight at once. Two, not +/// one per core: each is a whole film through a decoder and an encoder, and the +/// hardware seat they queue on is a single one -- more of them at once is the +/// same work done later, with the editor slower while it happens. +pub(crate) const PROXIES_AT_ONCE: usize = 2; /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, /// and a path with a point per pixel is a path per repaint. pub(crate) const WAVE_COL: f32 = 2.; diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 0c1d004..afd0d8b 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -149,6 +149,12 @@ struct Player { /// the key is inserted the moment the decode is *started*: presence means /// "asked", so a repaint mid-decode cannot ask again. waves: HashMap<(PathBuf, usize), Wave>, + /// What each source's stand-in is up to ([`engine::proxy`]), filled like + /// `waves`: presence means "asked", so the encode is started once per file + /// however many times the library is drawn. The switch that decides whether + /// they are *played* is the session's own -- it is the project's and is + /// saved with it, where this map is this window's view of the cache. + proxies: HashMap, /// Which audio streams each imported file has, as its header describes /// them: one library row per entry. Keyed and filled like `waves` -- /// presence means "asked" -- and an empty list is a silent file, which is @@ -602,6 +608,7 @@ fn main() { selected_asset: None, library_tab: LibraryTab::Media, waves: HashMap::new(), + proxies: HashMap::new(), streams: HashMap::new(), bitrates: HashMap::new(), sizes: HashMap::new(), diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 4032130..9a76f90 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -87,6 +87,7 @@ impl Player { ActionId::Mix => self.open_mix(None, cx), ActionId::ToggleSnap => self.toggle_snap(cx), ActionId::ToggleSubtitles => self.toggle_subtitles(cx), + ActionId::ToggleProxies => self.toggle_proxies(cx), // The keyboard's door to the same list the toolbar button opens. // At the window's corner, since a stroke names no place -- and // [`menu_at`] keeps it on screen from there. diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 278cc75..2f25f37 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -111,6 +111,51 @@ impl Player { }) .detach(); } + // A stand-in for every film this machine cannot cut at speed, started + // the moment the file arrives and made while the editor keeps running + // ([`engine::proxy`]). Off the render thread for the reason the sync + // walk above is -- the decision reads the same header -- and the encode + // itself is the engine's own worker, so what comes back here is a + // handle to poll and not a wait. + for path in unseen_paths(session.sources(), &self.proxies) { + // Two at a time, and the rest at the next repaint: a stand-in is a + // whole film re-encoded, and a library of ten dropped at once would + // otherwise start ten encodes fighting over the one hardware seat. + // The unstarted ones simply stay out of the map, which is what + // brings them back here ([`unseen_paths`]). + if self.in_flight_proxies() >= PROXIES_AT_ONCE { + break; + } + self.proxies.insert(path.clone(), Proxy::Asked); + let started = cx.background_executor().spawn({ + let path = path.clone(); + async move { engine::proxy::generate_if_wanted(&path) } + }); + cx.spawn(async move |this, cx| { + let started = started.await; + this.update(cx, |this, cx| { + let state = match started { + Ok(Some(job)) => Proxy::Making(job), + // A film that needs none keeps the state it was + // inserted with, which is what it is. + Ok(None) => Proxy::Native, + Err(e) => { + let text = format!( + "NO PROXY for {} — {e} — the film itself is what plays", + file_name(&path) + ); + eprintln!("{text}"); + this.notify_user(text.into()); + Proxy::Failed + } + }; + this.proxies.insert(path, state); + cx.notify(); + }) + .ok(); + }) + .detach(); + } for key in unseen_sources(session.sources(), &self.waves) { self.waves.insert(key.clone(), Wave::Loading); let decoded = cx.background_executor().spawn({ diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index c40c901..c1e245d 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -296,6 +296,117 @@ impl Player { /// ...and starts whatever is queued behind it, which is the one place the /// files argv named can begin: they are put in the queue before there is a /// context to spawn a worker from. + /// Takes each finished stand-in's verdict, once. Sampled here rather than + /// while drawing, for [`Player::poll_export`]'s reason -- and it is the one + /// place a proxy job's outcome is read, so "ready" on a row and the file in + /// the cache are the same fact. + /// + /// Nothing waits for it: until a proxy is ready the film itself is what + /// plays, switch or no switch ([`engine::PlaybackSession::picture_path`]), + /// so a failure costs a line and no more. + pub(crate) fn poll_proxies(&mut self, cx: &mut Context) { + let done: Vec<(PathBuf, engine::Result)> = self + .proxies + .iter() + .filter_map(|(path, state)| match state { + Proxy::Making(job) => Some((path.clone(), job.outcome()?)), + _ => None, + }) + .collect(); + for (path, outcome) in done { + let text = match &outcome { + Ok(_) => format!( + "PROXY READY for {} — Proxies on cuts on it", + file_name(&path) + ), + Err(e) => format!( + "PROXY FAILED for {} — {e} — the film itself is what plays", + file_name(&path) + ), + }; + eprintln!("{text}"); + self.notify_user(text.into()); + let state = match outcome { + Ok(_) => Proxy::Ready, + Err(_) => Proxy::Failed, + }; + self.proxies.insert(path, state); + cx.notify(); + } + } + + /// What the Proxies button says after the state: how far the stand-ins + /// have got, since "on" with nothing made yet and "on" with the whole + /// library standing in are two different things to be looking at. Empty + /// where no film here wants one, which is the ordinary case. + pub(crate) fn proxy_tail(&self) -> String { + let making = self.proxies.values().filter_map(|p| match p { + Proxy::Making(job) => Some(job.progress()), + _ => None, + }); + // The one furthest along would read as done while three others sit at + // nothing: the *least* finished is what the button reports. + match making.fold(f32::INFINITY, f32::min) { + least if least.is_finite() => format!(" · {}%", (least * 100.) as u32), + _ => String::new(), + } + } + + /// Whether any stand-in is still being made -- what keeps the frame loop + /// alive while one is, so its percentage moves on screen. + pub(crate) fn making_proxies(&self) -> bool { + self.proxies + .values() + .any(|p| matches!(p, Proxy::Making(_))) + } + + /// How many films are between "shall we?" and "done": the number the start + /// of another is held against ([`PROXIES_AT_ONCE`]). A header being read + /// counts, because the answer may be an encode. + pub(crate) fn in_flight_proxies(&self) -> usize { + self.proxies + .values() + .filter(|p| matches!(p, Proxy::Asked | Proxy::Making(_))) + .count() + } + + /// Cuts on the stand-ins, or on the films themselves. The picture and only + /// the picture: the sound is the film's either way, and so is every frame + /// an export writes. + pub(crate) fn toggle_proxies(&mut self, cx: &mut Context) { + let Some(session) = &mut self.session else { + return; + }; + let on = !session.proxies(); + session.set_proxies(on); + // What is really under the switch, said in the same breath: a project + // whose films have no stand-in yet would otherwise read as a switch + // that does nothing. + let ready = self + .proxies + .values() + .filter(|p| matches!(p, Proxy::Ready)) + .count(); + let making = self + .proxies + .values() + .filter(|p| matches!(p, Proxy::Making(_))) + .count(); + let text = match (on, ready, making) { + (false, ..) => "PROXIES OFF — the films themselves are what play".to_string(), + (true, 0, 0) => { + "PROXIES ON — no film here has one, so the films themselves play".to_string() + } + (true, 0, n) => format!("PROXIES ON — {n} still being made; the films play until then"), + (true, n, 0) => format!("PROXIES ON — cutting on {n}"), + (true, n, m) => format!("PROXIES ON — cutting on {n}, {m} still being made"), + }; + eprintln!("{text}"); + self.notify_user(text.into()); + self.reset_after_reseek(); + cx.notify(); + } + pub(crate) fn poll_import(&mut self, cx: &mut Context) { match &mut self.importing { Some(import) => { diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index c8209ef..f73fd24 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -23,6 +23,7 @@ impl Render for Player { self.poll_export(); self.poll_import(cx); self.poll_silence(); + self.poll_proxies(cx); // Every way a source can arrive -- argv, an import, a project load -- // has been through a repaint by the time its clips are drawn, so this // is the one place that has to notice a new one. @@ -57,6 +58,10 @@ impl Render for Player { // the screen on a repaint, and a still line is the very thing this // card was rewritten to disprove. || self.silence_scan.is_some() + // ...and a stand-in being made: its percentage on the library row + // only reaches the screen on a repaint, and a bar that never moves + // is exactly what a person reads as a hung encode. + || self.making_proxies() { window.request_animation_frame(); } diff --git a/crates/app/src/ui/inspector.rs b/crates/app/src/ui/inspector.rs index cb60d1b..c25c9ea 100644 --- a/crates/app/src/ui/inspector.rs +++ b/crates/app/src/ui/inspector.rs @@ -284,6 +284,24 @@ impl Player { this.open_picker(Pick::Tone, event.position(), cx) }), )) + // Its own rect and a label that *is* the state, the rule + // the snap toggle writes down: a button that resized itself + // on every press made the row shuffle under the pointer. + .child(self.action_control( + "proxies", + TONE_SLOT_W, + BG_RAISED(), + None, + match self.session.as_ref().map(PlaybackSession::proxies) { + Some(true) => format!("Proxies on{}", self.proxy_tail()), + Some(false) => format!("Proxies off{}", self.proxy_tail()), + None => "Proxies".to_string(), + }, + "cuts on small stand-ins of the big films; the sound and every export \ + stay the film's own", + ActionId::ToggleProxies, + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_proxies(cx)), + )) .child(self.action_control( "inspect-mix", 0., diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs index 343b0e1..1e7fd82 100644 --- a/crates/app/src/ui/library.rs +++ b/crates/app/src/ui/library.rs @@ -112,6 +112,16 @@ impl Player { &timecode(f64::from(row.frames) / self.fps, self.fps), ), }; + // ...and what this file's stand-in is up to, after its length: a + // percentage while one is being made, the word while there is one, + // and nothing at all for a film that wants none ([`Proxy::detail`]). + let under = join_detail( + &under, + &self + .proxies + .get(&row.path) + .map_or_else(String::new, Proxy::detail), + ); let usable = row.unusable.is_none(); let (path, stream) = (row.path.clone(), row.stream); let dragged = (path.clone(), stream); diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index d378321..eada5cf 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -178,18 +178,45 @@ impl Job { /// back through [`Job::outcome`], so a caller has two places to look and not /// twenty. pub fn generate(source: &Path) -> crate::Result { + Ok(started(source, |_| true)?.expect("nothing was filtered out")) +} + +/// The same, for a file that is worth standing in for and nobody else +/// ([`wanted`]) -- `Ok(None)` is a film this machine already cuts at speed. +/// +/// The header is read *once* for both questions: on a Matroska that read is the +/// cluster walk, so asking `wanted` and then `generate` separately would pay +/// for it twice. +pub fn generate_if_wanted(source: &Path) -> crate::Result> { + started(source, wanted) +} + +/// Both doors: the cache is looked at, the header is read once, and `only_if` +/// decides off that header whether there is anything to do. +fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result> { let out = path_for(source).ok_or("no cache directory to keep a proxy in")?; if out.is_file() { - return Ok(Job { out, handle: None }); + return Ok(Some(Job { out, handle: None })); } // The source's own header: its rate and length are the proxy's (a stand-in // that ran at another rate or stopped early would put every cut on another // frame), and only its picture size changes. let (meta, _) = Demuxer::open(source)?; + if !only_if(&meta) { + return Ok(None); + } let (width, height) = size_for(&meta); if let Some(dir) = out.parent() { std::fs::create_dir_all(dir)?; } + // What a killed editor left behind: the export worker deletes its own part + // file when it is cancelled or fails, but nothing can delete it for a + // process that was killed -- and a proxy of a feature film is hundreds of + // megabytes of cache nothing would ever look at again. The key is the same, + // so this is that same film's own leftover and not somebody else's. + let mut part = out.clone().into_os_string(); + part.push(".part"); + let _ = std::fs::remove_file(PathBuf::from(part)); // One video lane, one clip, the whole file -- and *no* audio lane, which is // what makes the proxy picture-only: the export walk codes the lanes it is // given and there is no sound among them. @@ -232,10 +259,10 @@ pub fn generate(source: &Path) -> crate::Result { ..Default::default() }, ); - Ok(Job { + Ok(Some(Job { out, handle: Some(handle), - }) + })) } #[cfg(test)]