Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 90 additions & 11 deletions crates/flyhigh-engine/src/gen_tex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,19 @@
//! slot of the interval is then synthesised too (`generate(0.0, out)` returns true) and the host must present that
//! output instead of its source frame.
//!
//! Statistics come back through an async readback (`StatsRun`): native hosts block on it inside `push_slot`, the
//! browser host awaits the promise of `fh_vid_stats` before the first `generate` of the interval (the lookahead hides it).
//! Statistics come back through a tagged async readback. Hosts resolve it before the interval's first `generate`.
use crate::gmhs::{CadenceScratch, PairStats, StatsRun};
use crate::gpu::memory::Charge;
use crate::net::build::PlanResources;
use crate::{gmhs, Blob, Gpu, NetOpts, SessionExt, Step, TimedRun};
use anyhow::{Context, Result};
use serde_json::Value;
use std::collections::VecDeque;
use std::rc::Rc;

#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "gen_tex_tests.rs"]
mod tests;

/// Still shot: some pair of the window changed less than this share of cells (held drawing, maybe with twinkling
/// effects); a camera move changes most of the frame in every pair.
Expand Down Expand Up @@ -106,11 +111,35 @@ pub struct GenTex {
scratch: Option<CadenceScratch>,
slots: Vec<usize>, // last pushed input slots, newest last (<= 3)
n_pushed: u64,
pending: Option<StatsRun>, // statistics of the newest pair, not yet read back
pending: Option<PendingPairStats>,
generation: Rc<()>,
hist: VecDeque<PairStats>, // per-pair statistics, oldest first; back = the "next" pair (lookahead)
half_done: bool, // linear_t: the t = 0.5 maps of the current pair are computed
}

struct PairKey {
generation: Rc<()>,
sequence: u64,
}

/// In-flight readback for one cadence pair. Finish it before passing it back to the stream.
pub struct PendingPairStats {
key: PairKey,
run: StatsRun,
}

/// Completed statistics bound to their original stream generation and pair.
pub struct FinishedPairStats {
key: PairKey,
stats: PairStats,
}

impl PendingPairStats {
pub async fn finish(self) -> Result<FinishedPairStats> {
Ok(FinishedPairStats { key: self.key, stats: self.run.finish().await? })
}
}

/// What the host can do after a push.
#[derive(Clone, Copy, Debug, Default)]
pub struct PushInfo {
Expand Down Expand Up @@ -234,8 +263,44 @@ impl GenTex {
cascade_iters: crate::options::cascade_for(opts.precise).1,
};
let mut sess = Vec::new();
for _ in 0..n_sess {
sess.push(SessionExt::new(gpu, blob, ops, opts.w, opts.h, opts.k, opts.iw, opts.ih, tune, &net));
let mut resources = PlanResources::default();
// Every mid consumes the render before the next one, including the compositor's saved background.
if cadence {
resources.render = Some(gpu.alloc((3 * (opts.w.div_ceil(32) * 32) * (opts.h.div_ceil(32) * 32)) as usize));
}
let can_share_workspace = cadence && std::env::var_os("FH_NO_ARENA").is_none();
let mut warmed_tune = None;
for attempt in 0..3 {
resources.workspace = (can_share_workspace && attempt < 2).then(Default::default);
resources.layout_mismatch = false;
for _ in 0..n_sess {
sess.push(SessionExt::new_with(
gpu,
blob,
ops,
opts.w,
opts.h,
opts.k,
opts.iw,
opts.ih,
warmed_tune.as_ref().or(tune),
&net,
&mut resources,
));
if resources.layout_mismatch {
break;
}
}
if !resources.layout_mismatch {
break;
}
// Cold native autotune can change the allocation trace. Retry with those choices, otherwise keep private arenas.
sess.clear();
if attempt == 0 {
let mut choices = gpu.tune.borrow().clone();
choices.extend(tune.into_iter().flatten().map(|(k, v)| (*k, *v)));
warmed_tune = Some(choices);
}
}
let scratch = if cadence {
Some(CadenceScratch::new(gpu, &sess[0]).context("cadence: GMHS maps missing")?)
Expand All @@ -254,6 +319,7 @@ impl GenTex {
slots: Vec::new(),
n_pushed: 0,
pending: None,
generation: Rc::new(()),
hist: VecDeque::new(),
half_done: false,
})
Expand Down Expand Up @@ -310,6 +376,7 @@ impl GenTex {
self.n_pushed = 0;
self.stats = [PairStats::default(); 3];
self.pending = None;
self.generation = Rc::new(());
self.hist.clear();
}
pub fn stats(&self) -> [PairStats; 3] {
Expand Down Expand Up @@ -361,24 +428,36 @@ impl GenTex {
self.hist.pop_front();
}
if let Some(sc) = &self.scratch {
self.pending = Some(gmhs::pair_stats_begin(gpu, &self.sess[sn], sc)?);
let key = PairKey { generation: self.generation.clone(), sequence: self.n_pushed };
self.pending =
Some(PendingPairStats { key, run: gmhs::pair_stats_begin(gpu, &self.sess[sn], sc)? });
}
let ready = self.slots.len() >= 3;
Ok((PushInfo { ready, base_slot: if ready { self.slots[0] } else { slot }, real_replaced: false }, run))
}
}
}
/// Take the pending statistics readback (Video + cadence); the caller awaits `finish` and passes the result to `set_stats`.
pub fn take_stats(&mut self) -> Option<StatsRun> {
pub fn take_stats(&mut self) -> Option<PendingPairStats> {
self.pending.take()
}
pub fn has_pending_stats(&self) -> bool {
self.pending.is_some()
}
pub fn set_stats(&mut self, st: PairStats) {
self.stats[2] = st;
if let Some(b) = self.hist.back_mut() {
*b = st;
/// Ignore completions from another generation or a pair that has left history.
pub fn set_stats(&mut self, st: FinishedPairStats) {
if !Rc::ptr_eq(&st.key.generation, &self.generation) {
return;
}
let Some(age) = self.n_pushed.checked_sub(st.key.sequence) else { return };
if age >= self.hist.len() as u64 {
return;
}
let i = self.hist.len() - 1 - age as usize;
self.hist[i] = st.stats;
if age < self.stats.len() as u64 {
let i = self.stats.len() - 1 - age as usize;
self.stats[i] = st.stats;
}
}
/// Native convenience: block for the pending statistics.
Expand Down
Loading
Loading