diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs index 367bbf8..d7e6700 100644 --- a/crates/app/src/layout.rs +++ b/crates/app/src/layout.rs @@ -73,6 +73,10 @@ pub(crate) const ROW_H: f32 = 32.; /// The tint swatch down the left of a row: the same colour that source's clips /// wear in the lanes, which is the whole of the panel<->timeline association. pub(crate) const SWATCH_W: f32 = 4.; +/// How far the encode has come, drawn under the stop square on a library row. +/// Inside a `HIT_MIN` cell with a little air each side, so the bar never reaches +/// the edge of the target it belongs to. +pub(crate) const PROXY_BAR_W: f32 = HIT_MIN - 10.; pub(crate) const CONTROL_H: f32 = 28.; /// The volume slider beside its button: a hundred steps across it, so a pixel /// is finer than a step and the drag reads as continuous. diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 939a83d..2305026 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -124,6 +124,11 @@ impl Player { // stand-in through here at the next repaint, which is the only door // there is. Left unseen meanwhile, so nothing is missed by having been // imported while the switch was off. + // Gathered here and started at the bottom of this function: the list is + // read off the session, and starting one takes the whole player + // ([`Player::start_proxy_for`], which the row's switch calls too), so + // the two cannot be the same statement. + let mut starting: Vec = Vec::new(); for path in proxies_to_start( session.auto_proxies(), session.proxies(), @@ -135,38 +140,10 @@ impl Player { // 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 { + if self.in_flight_proxies() + starting.len() >= 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(); + starting.push(path); } for key in unseen_sources(session.sources(), &self.waves) { self.waves.insert(key.clone(), Wave::Loading); @@ -200,6 +177,9 @@ impl Player { }) .detach(); } + for path in starting { + self.start_proxy_for(&path, cx); + } } /// Probes what an export would open, once per (settings, resolution, cuts) diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index e1e4ec0..cc1ba76 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -360,6 +360,160 @@ impl Player { } } + /// Starts the stand-in for one file: the slot is taken the moment the ask + /// goes out, so a repaint mid-encode cannot start a second one, and what + /// comes back off the worker settles the slot. + /// + /// One body, two doors: the sweep [`Player::cache_media`] runs over + /// everything the session has not seen, and the switch on a library row + /// ([`Player::toggle_proxy`]) for the one file under the pointer. The cap on + /// how many run at once belongs to the sweep -- a person who asks for *this* + /// film's stand-in has asked, and is told by the row how far it has got. + pub(crate) fn start_proxy_for(&mut self, path: &std::path::Path, cx: &mut Context) { + let path = path.to_path_buf(); + 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| { + // Switched off while the header was being read + // ([`Player::toggle_proxy`]): the slot is no longer the `Asked` + // this put there, so what came back is *stopped as it lands* + // rather than installed over the stop. Without this the second + // half of a click made during the ask is an encoder nothing in + // the map can reach -- and it finishes minutes later and puts + // back the stand-in somebody switched off. + let stopped = !matches!(this.proxies.get(&path), Some(Proxy::Asked)); + let state = match started { + // Cancelled and *held*, exactly as a stop of a running one + // is: the worker's own answer is what settles it, so an + // encode that beat the stop is reported as the finished + // stand-in it is ([`Player::poll_proxies`]). + Ok(Some(job)) if stopped => { + job.cancel(); + Proxy::Cancelling(job) + } + // ...and a stop of something that was never going to be + // encoded is simply the film itself, which is what it was. + Ok(None) | Err(_) if stopped => Proxy::Cancelled, + 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(); + } + + /// The switch on a library row: this file's stand-in on, or off. One + /// control for the whole life of the thing, because a row with a separate + /// start, stop and delete is three buttons for one fact. + /// + /// * being made -- the ask is to *stop*, which is + /// [`Player::cancel_proxy`]'s half-written-file-and-all path and never a + /// deletion; + /// * asked for, and the worker has not answered yet -- the same stop, made + /// before there is a job to stop: the slot is marked and the answer is + /// cancelled as it lands ([`Player::start_proxy_for`]). Never a second + /// start, which is what two encoders on one `.part` path used to be; + /// * there is one -- the file in the cache goes ([`engine::proxy::delete`]), + /// and the slot is left [`Proxy::Cancelled`] rather than emptied: an empty + /// slot is what the next repaint's sweep starts an encode from + /// ([`proxies_to_start`] passes on everything the map has not seen), so + /// emptying it would rebuild the stand-in a second after it was turned + /// off. A delete that could not happen leaves the row *on*, because the + /// file is still there and still what plays; + /// * anything else -- start one. + /// + /// `showed_stop` is what the row was drawing when the pointer went down: + /// a stand-in that finished between that paint and this click is a click on + /// a **stop**, and a stop settles as the ready stand-in it is rather than + /// deleting a file nobody asked to lose ([`Player::cancel_proxy`]'s own + /// promise). + /// + /// The off is remembered past the window ([`engine::proxy::set_off`]): the + /// sweep runs again at every launch, and a switch that forgets is one that + /// re-encodes tomorrow what was turned off today. + pub(crate) fn toggle_proxy( + &mut self, + path: &std::path::Path, + showed_stop: bool, + cx: &mut Context, + ) { + match self.proxies.get(path) { + Some(Proxy::Making(_)) => self.cancel_proxy(path, cx), + // Already winding down: the second click on a stop is nothing. + Some(Proxy::Cancelling(_)) => {} + Some(Proxy::Asked) => { + engine::proxy::set_off(path, true); + self.proxies.insert(path.to_path_buf(), Proxy::Cancelled); + let text = format!("STOPPING the stand-in for {}…", file_name(path)); + eprintln!("{text}"); + self.notify_user(text.into()); + cx.notify(); + } + // The encode beat the click: what is under the pointer is a stop, + // and the film has a stand-in now. + Some(Proxy::Ready) if showed_stop => { + let text = format!( + "PROXY READY for {} — it finished before the stop; click again to delete it", + file_name(path) + ); + eprintln!("{text}"); + self.notify_user(text.into()); + cx.notify(); + } + Some(Proxy::Ready) => { + let text = match engine::proxy::delete(path) { + Ok(gone) => { + engine::proxy::set_off(path, true); + self.proxies.insert(path.to_path_buf(), Proxy::Cancelled); + match gone { + true => format!( + "PROXY OFF for {} — the film itself is what plays", + file_name(path) + ), + false => { + format!("NO PROXY for {} — nothing to delete", file_name(path)) + } + } + } + // The file is still on the disk and [`engine::proxy::cached`] + // is still handing it to playback, so the row stays on: the + // one thing it must never do is say off over a proxy that is + // playing. + Err(e) => format!( + "PROXY KEPT for {} — {e} — it could not be deleted and is still what plays", + file_name(path) + ), + }; + eprintln!("{text}"); + self.notify_user(text.into()); + cx.notify(); + } + _ => { + engine::proxy::set_off(path, false); + self.start_proxy_for(path, cx); + } + } + } + /// The × on a library row while its stand-in is being made: the worker is /// asked to give up at its next frame and delete the half-written file it /// was writing ([`engine::proxy::Job::cancel`]), and the row says so until @@ -388,6 +542,9 @@ impl Player { }; job.cancel(); *slot = Proxy::Cancelling(job); + // Remembered past this window, for [`Player::toggle_proxy`]'s reason: + // the launch sweep would otherwise start again what was just stopped. + engine::proxy::set_off(path, true); let text = format!("STOPPING the stand-in for {}…", file_name(path)); eprintln!("{text}"); self.notify_user(text.into()); diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs index f33ce9d..e57427f 100644 --- a/crates/app/src/ui/library.rs +++ b/crates/app/src/ui/library.rs @@ -126,15 +126,55 @@ impl Player { // that says how far it has got is where the way out of it belongs. // Gone the moment the worker settles, like the percentage beside // it: there is nothing left to stop. - let making = matches!(self.proxies.get(&row.path), Some(Proxy::Making(_))); + // The switch, and what it is showing. One control for the whole + // life of a stand-in ([`Player::toggle_proxy`]): a filled dot for + // one that exists, a stop square while one is being made -- with + // how far it has got drawn under it -- and a hollow dot for a row + // that has none. Never an ×: that shape means the file leaves the + // library, and taking a *stand-in* off a row is not that. + let (glyph, proxy_on, progress, waiting) = match self.proxies.get(&row.path) { + Some(Proxy::Ready) => ("●", true, None, false), + Some(Proxy::Making(job)) => ("■", true, Some(job.progress()), false), + // Asked for and already winding down: the same square, dimmed, + // so a second click does not look like the first one missed. + Some(Proxy::Cancelling(_)) => ("■", true, None, true), + Some(Proxy::Asked) => ("○", false, None, true), + _ => ("○", false, None, false), + }; + // What the row is drawing right now, carried into the click: a + // stand-in that finishes between this paint and the pointer going + // down must not turn a stop into a deletion + // ([`Player::toggle_proxy`]). + let showed_stop = glyph == "■"; let stop_path = row.path.clone(); - let stop_tip: SharedString = format!( - "Stop making the stand-in for {} — nothing of it is kept, and the film itself is \ - what plays", - row.name - ) + let stop_tip: SharedString = match self.proxies.get(&row.path) { + Some(Proxy::Making(_)) => format!( + "Stop making the stand-in for {} — nothing of it is kept, and the film itself \ + is what plays", + row.name + ), + Some(Proxy::Cancelling(_)) => { + format!("Stopping the stand-in for {}…", row.name) + } + Some(Proxy::Ready) => format!( + "Stand-in ON for {} — click to delete it; the film itself is what plays after \ + that, and nothing of the film is touched", + row.name + ), + _ => format!("Stand-in OFF for {} — click to make one", row.name), + } .into(); let usable = row.unusable.is_none(); + // What is left of the row for words: the switch and the gap before + // it, on the rows that carry one. Both lines are held to it -- the + // name alone was, and the detail line under it ran on under the + // switch and was cut mid-word -- and an unusable row draws no switch + // and so pays nothing for one. + let text_w = row_text_w(width) + - match usable { + true => HIT_MIN + 6., + false => 0., + }; let (path, stream) = (row.path.clone(), row.stream); let dragged = (path.clone(), stream); let menu_path = path.clone(); @@ -221,39 +261,71 @@ impl Player { div() .truncate() .text_size(px(11.)) - .child(clip_middle(&name, row_text_w(width))), + // Less the stand-in switch and the gap before + // it: a media row carries one where a subtitle + // row -- built to the same `row_text_w` -- does + // not, so the difference is taken here. + .child(clip_middle(&name, text_w)), ) .child( div() .truncate() .text_size(px(10.)) .text_color(rgb(FG_SECONDARY())) - .child(under), + .child(clip_middle(&under, text_w)), ), ) - // The way out of the encode, on the row that shows it running. - // A `HIT_MIN` target and the subtitle row's ×, and it stops the - // click there: the row under it picks the file, and stopping an - // encode is not a way of choosing what to place. - .when(making, |d| { + // The stand-in switch, on every row that can carry one. A + // `HIT_MIN` target that stops the click there: the row under it + // picks the file, and turning a stand-in on or off is not a way + // of choosing what to place. The selection language the rest of + // the window speaks says which way it is set -- lit like a + // picked row when there is one, dimmed like an unusable one + // when there is not. + .when(usable, |d| { d.child( div() - .id(("proxy-stop", i)) + .id(("proxy-toggle", i)) .flex_none() .w(px(HIT_MIN)) .h_full() .flex() + .flex_col() .items_center() .justify_center() + .gap(px(2.)) .rounded(px(3.)) + .text_size(px(10.)) + .when(proxy_on, |d| d.bg(rgb(BG_SELECTED()))) + .when(!proxy_on, |d| d.text_color(rgb(FG_SECONDARY()))) + .when(waiting, |d| d.opacity(0.55)) .cursor_pointer() .hover(|s| s.bg(rgb(BG_HOVER()))) .tooltip(move |_, cx| cx.new(|_| Tip(stop_tip.clone())).into()) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { cx.stop_propagation(); - this.cancel_proxy(&stop_path, cx); + this.toggle_proxy(&stop_path, showed_stop, cx); })) - .child("×"), + .child(glyph) + // How far the encode has come, under the stop it is + // stopped with: a bar rather than only the row's + // "proxy 37%", so the control reads as a job that is + // running and not as a thing that removes something. + .children(progress.map(|p| { + div() + .flex_none() + .w(px(PROXY_BAR_W)) + .h(px(2.)) + .rounded(px(1.)) + .bg(rgb(BG_RAISED())) + .child( + div() + .h_full() + .w(px(PROXY_BAR_W * p.clamp(0., 1.))) + .rounded(px(1.)) + .bg(rgb(ACCENT_PRIMARY())), + ) + })), ) }) }) diff --git a/crates/engine/src/proxy.rs b/crates/engine/src/proxy.rs index 0dd326a..cd23432 100644 --- a/crates/engine/src/proxy.rs +++ b/crates/engine/src/proxy.rs @@ -223,6 +223,114 @@ pub fn cached(source: &Path) -> Option { path_for(source).filter(|p| p.is_file()) } +/// Deletes the stand-in of `source`, if there is one, and says whether a file +/// went. The one *by hand* eviction: [`sweep`] takes the oldest to stay under a +/// cap, this takes the one that was asked for. +/// +/// The source itself is never touched -- what is deleted is [`path_for`]'s +/// answer, a name in the cache directory and nothing else -- and deleting one +/// under a session that is playing off it costs a re-open: [`cached`] stats, +/// finds nothing, and the film itself is what plays from the next span on +/// ([`crate::PlaybackSession::picture_path`]). +/// Three answers and not two, because they are three different rows: `Ok(true)` +/// is a stand-in that went, `Ok(false)` is one that was never there (a no-op, +/// and the switch is honestly off afterwards), and `Err` is a file that is +/// **still on the disk** -- a read-only cache directory, a filesystem gone +/// away. A caller that folded the last two together drew the row as OFF over a +/// proxy [`cached`] went on handing to playback. +pub fn delete(source: &Path) -> std::io::Result { + let Some(path) = path_for(source) else { + return Ok(false); + }; + match std::fs::remove_file(&path) { + Ok(()) => { + eprintln!("proxy cache: deleted {}", path.display()); + Ok(true) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e), + } +} + +/// The mark beside a cache entry that says its film was switched *off* by hand, +/// and the one thing about a stand-in that outlives the window: without it the +/// next launch's sweep re-encodes the very proxy somebody just turned off. +/// +/// Keyed exactly as the stand-in itself is ([`path_for`]) and living beside it, +/// which is what makes it answer for a film that is in no project at all -- the +/// `.edith` file knows only the sources of one timeline, and the switch is on a +/// library row that may belong to none. Derived and disposable like everything +/// else in this directory: a re-encoded source names another key and is asked +/// again, and deleting the cache forgets the choice, which costs one click. +/// +/// corner-cut: the choice therefore does not survive a cache wipe or an edit to +/// the source file. Upgrade path is a list in the `.edith`, which needs the +/// project format to carry per-source flags. +fn off_marker(source: &Path) -> Option { + Some(path_for(source)?.with_extension("off")) +} + +/// Whether this film's stand-in was switched off by hand ([`off_marker`]). +pub fn is_off(source: &Path) -> bool { + off_marker(source).is_some_and(|p| p.exists()) +} + +/// Writes or clears that mark. Best effort: a cache directory that cannot be +/// written is a choice that does not survive the session, never a refused +/// click. +pub fn set_off(source: &Path, off: bool) { + let Some(marker) = off_marker(source) else { + return; + }; + match off { + true => { + if let Some(dir) = marker.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(&marker, b""); + } + false => { + let _ = std::fs::remove_file(&marker); + } + } +} + +/// The stand-ins being written *right now*, one entry per live encoder, held +/// for the life of the [`Job`]. +/// +/// The one-encoder-per-film rule lives here rather than only in the window that +/// draws the switch: two starts for one film race over one `.part` path, and +/// the second unlinks the first's file and leaves it writing into an orphaned +/// inode with nothing left holding its handle -- an encode nobody can stop, +/// which finishes minutes later and puts back a proxy somebody had switched +/// off. A guarantee that lives in the caller is a guarantee every future caller +/// has to re-make. +static IN_FLIGHT: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A held seat in [`IN_FLIGHT`], given up when the job that owns it is dropped. +struct Claim(PathBuf); + +impl Drop for Claim { + fn drop(&mut self) { + let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(i) = held.iter().position(|p| *p == self.0) { + held.swap_remove(i); + } + } +} + +/// Takes the seat for `out`, or `None` where an encoder already has it. +fn claim(out: &Path) -> Option { + let mut held = IN_FLIGHT.lock().unwrap_or_else(|e| e.into_inner()); + match held.iter().any(|p| p == out) { + true => None, + false => { + held.push(out.to_path_buf()); + Some(Claim(out.to_path_buf())) + } + } +} + /// A proxy being made -- or one that was already there, which is the same thing /// to whoever is waiting for a path. /// @@ -234,6 +342,9 @@ pub struct Job { out: PathBuf, /// `None` for a cache hit: there was nothing to run. handle: Option, + /// The seat this encoder holds ([`IN_FLIGHT`]), given back when the job + /// goes. `None` for a cache hit, which codes nothing. + _claim: Option, } impl Job { @@ -319,6 +430,13 @@ pub fn generate_if_wanted(source: &Path) -> crate::Result> { if crate::is_audio(source) || crate::is_image(source) { return Ok(None); } + // Switched off by hand, in this session or in one last week ([`set_off`]): + // the sweep that runs at every launch comes through here, and without this + // it re-encodes the stand-in somebody just turned off. Answered before the + // header is read, so a library of switched-off films costs no disk at all. + if is_off(source) { + return Ok(None); + } match started(source, wanted) { Err(e) if NoVideoTrack::is_it(&e) => Ok(None), other => other, @@ -330,8 +448,16 @@ pub fn generate_if_wanted(source: &Path) -> crate::Result> { 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(Some(Job { out, handle: None })); + return Ok(Some(Job { + out, + handle: None, + _claim: None, + })); } + // One encoder per film, taken before the header is read and given back when + // the job is dropped ([`IN_FLIGHT`]): the second start would unlink the + // first's `.part` below and orphan an encode nothing can stop. + let claim = claim(&out).ok_or("a stand-in for this film is already being made")?; // 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. @@ -402,6 +528,7 @@ fn started(source: &Path, only_if: fn(&VideoMeta) -> bool) -> crate::Result