diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index 595e1fb..b92efa1 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -468,11 +468,14 @@ impl GenTex { let (a, b) = ((sa, &self.ins[sa].1), (sb, &self.ins[sb].1)); if self.opts.linear_t { // the network's t-dependent stage once per pair; each phase is then only a render - if !self.half_done { - s.mid_maps_half(gpu); + let setup = if self.half_done { + Vec::new() + } else { + let setup = s.mid_map_steps_half(gpu); self.half_done = true; - } - run(gpu, &[s.render_tex_step(gpu, a, b, (out, view), Some(t))], timed) + setup + }; + gpu.submit_optional_timing(&setup, &[s.render_tex_step(gpu, a, b, (out, view), Some(t))], timed) } else { s.set_t(gpu, t); run(gpu, &s.mid_steps_fast(gpu, a, b, (out, view)), timed) @@ -516,11 +519,5 @@ impl GenTex { /// Runs `steps`; with `timed` and timestamp queries they go out under a timestamp pair instead and the run is /// returned to await for the GPU milliseconds. fn run(gpu: &Gpu, steps: &[Step], timed: bool) -> Option { - if timed { - if let Some(r) = gpu.begin_timed(steps) { - return Some(r); - } - } - gpu.replay(steps); - None + gpu.submit_optional_timing(&[], steps, timed) } diff --git a/crates/flyhigh-engine/src/gpu/device.rs b/crates/flyhigh-engine/src/gpu/device.rs index 42c0af0..74d219c 100644 --- a/crates/flyhigh-engine/src/gpu/device.rs +++ b/crates/flyhigh-engine/src/gpu/device.rs @@ -273,6 +273,7 @@ impl Gpu { bgra_storage: caps.bgra_storage, timestamps: caps.timestamps, ts_inside: caps.ts_inside, + timing: Default::default(), shader_compiler, arena: std::cell::RefCell::new(None), arena_ids: std::cell::RefCell::new(HashMap::new()), diff --git a/crates/flyhigh-engine/src/gpu/exec.rs b/crates/flyhigh-engine/src/gpu/exec.rs index acdcbee..d3daffc 100644 --- a/crates/flyhigh-engine/src/gpu/exec.rs +++ b/crates/flyhigh-engine/src/gpu/exec.rs @@ -9,6 +9,15 @@ impl Gpu { // with `qs`: pass-level timestamps (the WebGPU-standard kind) at the beginning of the first compute pass // (query 0) and the end of the last one (query 1) — the whole plan's GPU time without encoder-level queries pub fn encode_plan_ts(&self, enc: &mut wgpu::CommandEncoder, plan: &[Step], qs: Option<&wgpu::QuerySet>) { + self.encode_plan_query_range(enc, plan, qs.map(|q| (q, 0))) + } + + pub(crate) fn encode_plan_query_range( + &self, + enc: &mut wgpu::CommandEncoder, + plan: &[Step], + qs: Option<(&wgpu::QuerySet, u32)>, + ) { let last_c = plan.iter().rposition(|s| matches!(s, Step::Compute { .. })); let split = self.pass_split.get(); let mut first = true; @@ -24,10 +33,10 @@ impl Gpu { let end = if split > 0 { j.min(i + split) } else { j }; // this pass = plan[i..end) let is_last = last_c.is_some_and(|l| l < end); let tw = match qs { - Some(q) if first || is_last => Some(wgpu::ComputePassTimestampWrites { + Some((q, start)) if first || is_last => Some(wgpu::ComputePassTimestampWrites { query_set: q, - beginning_of_pass_write_index: if first { Some(0) } else { None }, - end_of_pass_write_index: if is_last { Some(1) } else { None }, + beginning_of_pass_write_index: first.then_some(start), + end_of_pass_write_index: is_last.then_some(start + 1), }), _ => None, }; diff --git a/crates/flyhigh-engine/src/gpu/mod.rs b/crates/flyhigh-engine/src/gpu/mod.rs index e7c8782..0da6fbd 100644 --- a/crates/flyhigh-engine/src/gpu/mod.rs +++ b/crates/flyhigh-engine/src/gpu/mod.rs @@ -30,6 +30,7 @@ pub struct Gpu { pub bgra_storage: bool, // BGRA8UNORM_STORAGE: canvases that prefer bgra8unorm can be written directly pub timestamps: bool, // TIMESTAMP_QUERY: gpu_time_ms works (pass-level timestamps, WebGPU-standard) pub ts_inside: bool, // + TIMESTAMP_QUERY_INSIDE_ENCODERS (native): per-step profile_plan + pub(crate) timing: std::cell::RefCell, pub shader_compiler: Option, // DX12: the HLSL compiler wgpu loaded (None on other backends) // buffer arena (Some while a plan is being built): tensors whose last reader has been built release their // buffer here and later tensors of the same plan reuse it — a static in-order plan makes this safe diff --git a/crates/flyhigh-engine/src/gpu/timing.rs b/crates/flyhigh-engine/src/gpu/timing.rs index ffb3e5b..3a56f5f 100644 --- a/crates/flyhigh-engine/src/gpu/timing.rs +++ b/crates/flyhigh-engine/src/gpu/timing.rs @@ -2,8 +2,114 @@ use crate::{map_read, Gpu, MapWait, Step}; use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::task::{Context, Poll, Waker}; + +const TIMING_SLOTS: usize = 4; +const TIMING_BYTES: u64 = 32; + +pub(crate) struct TimingPool { + queries: Option, + resolve: wgpu::Buffer, + slots: [Arc; TIMING_SLOTS], +} + +struct TimingSlot { + stage: wgpu::Buffer, + device: wgpu::Device, + queries: Option, + busy: AtomicBool, +} + +struct TimingLease { + slot: Arc, + mapping: bool, +} + +impl Drop for TimingLease { + fn drop(&mut self) { + if self.mapping { + // Cancellation may race a failed map, which has already unmapped the staging buffer. + let _cancel = self.slot.device.push_error_scope(wgpu::ErrorFilter::Validation); + self.slot.stage.unmap(); + } + self.slot.busy.store(false, Ordering::Release); + } +} + +#[derive(Default)] +pub(crate) enum TimingState { + #[default] + Cold, + Checking(Pin>>>), + Ready(TimingPool), + Unavailable, +} + +impl TimingState { + fn pool(&mut self, device: &wgpu::Device, deferred: bool) -> Option<&TimingPool> { + if matches!(self, Self::Cold) { + let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let buffer = |label, usage| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: TIMING_BYTES, + usage, + mapped_at_creation: false, + }) + }; + let queries = || { + device.create_query_set(&wgpu::QuerySetDescriptor { + label: Some("fh_live_timestamps"), + ty: wgpu::QueryType::Timestamp, + count: 4, + }) + }; + let pool = TimingPool { + queries: (!deferred).then(queries), + resolve: buffer("fh_timing_resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC), + slots: std::array::from_fn(|_| { + Arc::new(TimingSlot { + stage: buffer( + "fh_timing_readback", + wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + ), + device: device.clone(), + queries: deferred.then(queries), + busy: AtomicBool::new(false), + }) + }), + }; + let (validation, internal, oom) = (validation.pop(), internal.pop(), oom.pop()); + *self = Self::Checking(Box::pin(async move { + let (validation, internal, oom) = (validation.await, internal.await, oom.await); + (validation.is_none() && internal.is_none() && oom.is_none()).then_some(pool) + })); + } + if let Self::Checking(check) = self { + match check.as_mut().poll(&mut Context::from_waker(Waker::noop())) { + Poll::Pending => return None, + Poll::Ready(Some(pool)) => *self = Self::Ready(pool), + Poll::Ready(None) => *self = Self::Unavailable, + } + } + match self { + Self::Ready(pool) => Some(pool), + _ => None, + } + } +} impl Gpu { + fn defer_timing_resolve(&self) -> bool { + cfg!(target_os = "macos") && self.adapter.get_info().backend == wgpu::Backend::Metal + } + // pure GPU execution time of the whole command buffer, via timestamp queries (best of N). // wall_clock(replay+wait) - this = CPU-side overhead (encode + submit + driver launch + poll). #[cfg(not(target_arch = "wasm32"))] @@ -20,6 +126,13 @@ impl Gpu { if !self.timestamps { return f64::NAN; } + #[cfg(target_os = "macos")] + if self.defer_timing_resolve() { + return (0..reps) + .filter_map(|_| self.begin_timed(plan).and_then(|r| r.block_parts(self)).map(|p| p.total_ms)) + .reduce(f64::min) + .unwrap_or(f64::NAN); + } let qs = self.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, @@ -73,39 +186,74 @@ impl Gpu { // timestamps, SUBMITS IT NOW and requests the readback; `TimedRun::finish` awaits the result later. (An async // export that submits inside its body runs that body in a microtask — after whatever the host submitted next.) pub fn begin_timed(&self, plan: &[Step]) -> Option { - if !self.timestamps { + self.begin_timed_parts(&[], plan) + } + + pub(crate) fn begin_timed_parts(&self, setup: &[Step], plan: &[Step]) -> Option { + let has_compute = |steps: &[Step]| steps.iter().any(|s| matches!(s, Step::Compute { .. })); + let can_time = |steps: &[Step]| self.ts_inside || has_compute(steps); + if !self.timestamps || plan.is_empty() || !can_time(plan) || (!setup.is_empty() && !can_time(setup)) { return None; } - let qs = self.device.create_query_set(&wgpu::QuerySetDescriptor { - label: None, - ty: wgpu::QueryType::Timestamp, - count: 2, - }); - let resolve = self.device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size: 16, - usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, - mapped_at_creation: false, - }); - let stage = self.device.create_buffer(&wgpu::BufferDescriptor { - label: None, - size: 16, - usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); + let deferred = self.defer_timing_resolve(); + let mut timing = self.timing.borrow_mut(); + let pool = timing.pool(&self.device, deferred)?; + let mut lease = pool.slots.iter().find_map(|slot| { + slot.busy + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .ok() + .map(|_| TimingLease { slot: slot.clone(), mapping: false }) + })?; + let queries = lease.slot.queries.as_ref().or(pool.queries.as_ref())?; let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); - if self.ts_inside { - enc.write_timestamp(&qs, 0); - self.encode_plan(&mut enc, plan); - enc.write_timestamp(&qs, 1); + let mut section = |steps, index| { + if has_compute(steps) { + self.encode_plan_query_range(&mut enc, steps, Some((queries, index))); + } else { + enc.write_timestamp(queries, index); + self.encode_plan(&mut enc, steps); + enc.write_timestamp(queries, index + 1); + } + }; + let has_setup = !setup.is_empty(); + let index = if has_setup { + section(setup, 0); + 2 } else { - self.encode_plan_ts(&mut enc, plan, Some(&qs)); + 0 + }; + section(plan, index); + let count = index + 2; + let read = if deferred { + // Metal can resolve a counter before its samples become visible. Keep the query set leased + // until a separate resolve is submitted after the sampling command has completed. + self.queue.submit(Some(enc.finish())); + TimingRead::Deferred(DeferredResolve { + ready: super::readback::queue_done(&self.queue), + device: self.device.clone(), + queue: self.queue.clone(), + queries: queries.clone(), + resolve: pool.resolve.clone(), + count, + }) + } else { + record_readback(&mut enc, queries, &pool.resolve, &lease.slot.stage, count); + self.queue.submit(Some(enc.finish())); + lease.mapping = true; + TimingRead::Mapping(map_read(&lease.slot.stage)) + }; + Some(TimedRun { lease, read, period: self.queue.get_timestamp_period() as f64, has_setup }) + } + + pub(crate) fn submit_optional_timing(&self, setup: &[Step], plan: &[Step], timed: bool) -> Option { + if timed { + if let Some(run) = self.begin_timed_parts(setup, plan) { + return Some(run); + } } - enc.resolve_query_set(&qs, 0..2, &resolve, 0); - enc.copy_buffer_to_buffer(&resolve, 0, &stage, 0, 16); - self.queue.submit(Some(enc.finish())); - let fut = map_read(&stage); - Some(TimedRun { stage, fut, period: self.queue.get_timestamp_period() as f64 }) + self.replay(setup); + self.replay(plan); + None } // per-step GPU time: one timestamp per step, each compute in its own pass so encoder-level // write_timestamp can bracket it; aggregated by pipeline name, averaged over REPS. Profiling only — @@ -198,28 +346,108 @@ impl Gpu { // a submitted timed run whose timestamp readback is still in flight (see `Gpu::begin_timed`) pub struct TimedRun { - stage: wgpu::Buffer, - fut: MapWait, + lease: TimingLease, + read: TimingRead, period: f64, + has_setup: bool, +} + +enum TimingRead { + Mapping(MapWait), + Deferred(DeferredResolve), +} + +struct DeferredResolve { + ready: super::readback::QueueWait, + device: wgpu::Device, + queue: wgpu::Queue, + queries: wgpu::QuerySet, + resolve: wgpu::Buffer, + count: u32, +} + +fn record_readback( + enc: &mut wgpu::CommandEncoder, + queries: &wgpu::QuerySet, + resolve: &wgpu::Buffer, + stage: &wgpu::Buffer, + count: u32, +) { + enc.resolve_query_set(queries, 0..count, resolve, 0); + enc.copy_buffer_to_buffer(resolve, 0, stage, 0, u64::from(count) * 8); +} + +#[derive(Clone, Copy, Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TimingParts { + pub setup_ms: Option, + pub frame_ms: f64, + pub total_ms: f64, } impl TimedRun { pub async fn finish(self) -> f64 { - if self.fut.await.is_err() { - return f64::NAN; + self.finish_parts().await.map_or(f64::NAN, |p| p.total_ms) + } + + pub async fn finish_parts(self) -> Option { + self.finish_parts_impl(false).await + } + + async fn finish_parts_impl(mut self, blocking: bool) -> Option { + let stage = &self.lease.slot.stage; + let mapping = match self.read { + TimingRead::Mapping(fut) => fut, + TimingRead::Deferred(res) => { + res.ready.await; + let mut enc = res.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + record_readback(&mut enc, &res.queries, &res.resolve, stage, res.count); + let submitted = res.queue.submit(Some(enc.finish())); + self.lease.mapping = true; + let mapping = map_read(stage); + if blocking + && res + .device + .poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }) + .is_err() + { + self.lease.mapping = false; + return None; + } + mapping + } + }; + if mapping.await.is_err() { + self.lease.mapping = false; + return None; } - let ms = { - let data = self.stage.slice(..).get_mapped_range().unwrap(); + let parts = { + let data = stage.slice(..).get_mapped_range().ok()?; let ts: &[u64] = bytemuck::cast_slice(&data); - ts[1].wrapping_sub(ts[0]) as f64 * self.period / 1e6 + let ms = |i: usize| { + let value = ts[i + 1].checked_sub(ts[i])? as f64 * self.period / 1e6; + (value.is_finite() && value > 0.0).then_some(value) + }; + if self.has_setup { + ms(0).zip(ms(2)).map(|(setup, frame)| (Some(setup), frame)) + } else { + ms(0).map(|frame| (None, frame)) + } }; - self.stage.unmap(); - ms + stage.unmap(); + self.lease.mapping = false; + let (setup_ms, frame_ms) = parts?; + Some(TimingParts { setup_ms, frame_ms, total_ms: setup_ms.unwrap_or(0.0) + frame_ms }) } /// Native: poll the device and wait for the result. #[cfg(not(target_arch = "wasm32"))] pub fn block(self, gpu: &Gpu) -> f64 { + self.block_parts(gpu).map_or(f64::NAN, |p| p.total_ms) + } + + #[cfg(not(target_arch = "wasm32"))] + pub fn block_parts(self, gpu: &Gpu) -> Option { gpu.wait(); - pollster::block_on(self.finish()) + pollster::block_on(self.finish_parts_impl(true)) } } diff --git a/crates/flyhigh-engine/src/net/session_ext.rs b/crates/flyhigh-engine/src/net/session_ext.rs index 01f70b9..8101cf6 100644 --- a/crates/flyhigh-engine/src/net/session_ext.rs +++ b/crates/flyhigh-engine/src/net/session_ext.rs @@ -244,8 +244,11 @@ impl SessionExt { } /// linear_t: run the t-dependent network once for the current pair (at t = 0.5) pub fn mid_maps_half(&self, gpu: &Gpu) { + gpu.replay(&self.mid_map_steps_half(gpu)); + } + pub(crate) fn mid_map_steps_half(&self, gpu: &Gpu) -> Vec { self.set_t(gpu, 0.5); - gpu.replay(&self.plan_mid.iter().map(clone_step).collect::>()); + self.plan_mid.iter().map(clone_step).collect() } pub fn mid_fast( &self, diff --git a/crates/flyhigh-engine/src/session.rs b/crates/flyhigh-engine/src/session.rs index 5b00e2f..e524f9b 100644 --- a/crates/flyhigh-engine/src/session.rs +++ b/crates/flyhigh-engine/src/session.rs @@ -522,13 +522,15 @@ impl Session { fn mid_steps(&self, t: f32, out: usize) -> Result> { let (a, b) = self.pair.get().context("pair two input slots first")?; let (av, bv, ov) = ((a, &self.ext.ins[a].1), (b, &self.ext.ins[b].1), (out, &self.ext.outs[out].1)); - self.ext.set_t(&self.gpu, t); Ok(if self.ext.is_fast() && self.opts.linear_t { vec![self.ext.render_tex_step(&self.gpu, av, bv, ov, Some(t))] - } else if self.ext.is_fast() { - self.ext.mid_steps_fast(&self.gpu, av, bv, ov) } else { - self.ext.mid_steps(&self.gpu, out, ov.1) + self.ext.set_t(&self.gpu, t); + if self.ext.is_fast() { + self.ext.mid_steps_fast(&self.gpu, av, bv, ov) + } else { + self.ext.mid_steps(&self.gpu, out, ov.1) + } }) } @@ -553,14 +555,22 @@ impl Session { pub fn pair_timed_begin(&self, a: usize, b: usize) -> Result> { self.check_in(a)?; self.check_in(b)?; - Ok(self.gpu.begin_timed(&self.pair_steps(a, b))) + let run = self.gpu.submit_optional_timing(&[], &self.pair_steps(a, b), true); + self.pair.set(Some((a, b))); + self.half_done.set(false); + Ok(run) } /// One more generated frame of the last pair, submitted with timestamps (see `pair_timed_begin`). pub fn mid_timed_begin(&self, t: f32, out: usize) -> Result> { self.check_out(out)?; let steps = self.mid_steps(t, out)?; - Ok(self.gpu.begin_timed(&steps)) + let setup = if self.ext.is_fast() && self.opts.linear_t && !self.half_done.replace(true) { + self.ext.mid_map_steps_half(&self.gpu) + } else { + Vec::new() + }; + Ok(self.gpu.submit_optional_timing(&setup, &steps, true)) } /// Compiles every kernel the session runs, before the first real frame: one pair and one mid on slots added for diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 6e230b7..be7f087 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -167,6 +167,8 @@ fn realtime_pushes_give_timestamped_intervals_and_mids() { fn timed_push_and_generate_report_gpu_time() { let Some(e) = engine() else { return }; let mut s = Stream::new(&e.gpu, &e.blob, &e.ops, TexOptions::new(W, H), &StreamOptions::default(), None).unwrap(); + s.warm_up(&e.gpu).unwrap(); + e.gpu.wait(); let s0 = s.next_input(|_| false).unwrap(); write(&e, &s, s0, &frame(0.0)); let (_, run) = s.push_timed(&e.gpu, s0, 0.0).unwrap(); @@ -182,13 +184,79 @@ fn timed_push_and_generate_report_gpu_time() { eprintln!("pair {pair_ms:?} ms, mid {mid_ms:?} ms"); if e.gpu.timestamps { let (pair_ms, mid_ms) = (pair_ms.unwrap(), mid_ms.unwrap()); - assert!(pair_ms > 0.0 && mid_ms > 0.0 && pair_ms > mid_ms, "the pair is the expensive half"); + assert!(pair_ms.is_finite() && pair_ms > 0.0 && mid_ms.is_finite() && mid_ms > 0.0); } else { assert!(pair_ms.is_none() && mid_ms.is_none(), "no timestamp queries, no times"); } assert_eq!(s.report().counters.mids, 1, "a timed generate counts like any other"); } +#[test] +#[ignore] +fn timing_pressure_never_changes_a_generated_frame() { + let Some(e) = engine() else { return }; + let tex = TexOptions { iw: 128, ih: 96, fast_render: true, linear_t: true, ..TexOptions::new(W, H) }; + let opts = StreamOptions { outputs: 2, ..Default::default() }; + let mut timed = Stream::new(&e.gpu, &e.blob, &e.ops, tex.clone(), &opts, None).unwrap(); + let mut plain = Stream::new(&e.gpu, &e.blob, &e.ops, tex, &opts, None).unwrap(); + for s in [&mut timed, &mut plain] { + for (i, shift) in [0.0, 8.0].into_iter().enumerate() { + let slot = s.next_input(|_| false).unwrap(); + write(&e, s, slot, &frame(shift)); + s.push(&e.gpu, slot, i as f64 * 40.0).unwrap(); + } + } + let mut runs = Vec::new(); + for _ in 0..4 { + let (written, run) = timed.generate_timed(&e.gpu, 0.25, 0).unwrap(); + assert_eq!(written, Generated::Written); + if let Some(run) = run { + runs.push(run); + } + } + let (written, exhausted) = timed.generate_timed(&e.gpu, 0.75, 1).unwrap(); + assert_eq!(written, Generated::Written); + assert!(exhausted.is_none(), "no new timing buffer is allocated under pressure"); + plain.generate(&e.gpu, 0.25, 0).unwrap(); + plain.generate(&e.gpu, 0.75, 1).unwrap(); + assert_eq!(read_output(&e, &timed, 0), read_output(&e, &plain, 0)); + assert_eq!(read_output(&e, &timed, 1), read_output(&e, &plain, 1)); + if e.gpu.timestamps { + assert_eq!(runs.len(), 4); + drop(runs.pop()); + assert!(timed.generate_timed(&e.gpu, 0.5, 1).unwrap().1.is_some(), "abandoned samples release their slot"); + } +} + +#[test] +#[ignore] +fn linear_timing_reports_setup_once_for_each_pair() { + let Some(e) = engine() else { return }; + if !e.gpu.timestamps { + return; + } + let tex = TexOptions { iw: 128, ih: 96, fast_render: true, linear_t: true, ..TexOptions::new(W, H) }; + let mut s = Stream::new(&e.gpu, &e.blob, &e.ops, tex, &StreamOptions::default(), None).unwrap(); + s.warm_up(&e.gpu).unwrap(); + e.gpu.wait(); + for i in 0..5 { + let slot = s.next_input(|_| false).unwrap(); + write(&e, &s, slot, &frame(i as f32 * 4.0)); + s.push(&e.gpu, slot, f64::from(i) * 40.0).unwrap(); + if i == 0 { + continue; + } + let p = |s: &mut Stream, t| s.generate_timed(&e.gpu, t, 0).unwrap().1.unwrap().block_parts(&e.gpu).unwrap(); + let first = p(&mut s, 0.25); + let later = p(&mut s, 0.75); + assert!(first.setup_ms.unwrap() > 0.0); + assert!(first.total_ms > first.frame_ms); + assert_eq!(later.setup_ms, None); + assert_eq!(later.total_ms, later.frame_ms); + } + assert!(s.frame_cost_ms(&e.gpu, 0).unwrap() > 0.0); +} + #[test] #[ignore] fn two_streams_share_one_engine() { diff --git a/crates/flyhigh-web/src/core.rs b/crates/flyhigh-web/src/core.rs index f6c8ef8..d10f533 100644 --- a/crates/flyhigh-web/src/core.rs +++ b/crates/flyhigh-web/src/core.rs @@ -14,7 +14,7 @@ use serde::Deserialize; use std::cell::RefCell; use std::rc::Rc; use wasm_bindgen::prelude::*; -use wasm_bindgen_futures::future_to_promise; +use wasm_bindgen_futures::{future_to_promise, JsFuture}; fn err(e: impl std::fmt::Display) -> JsValue { JsValue::from_str(&e.to_string()) @@ -120,7 +120,9 @@ fn u32_value(v: &serde_json::Value, what: &str) -> Result { fn timed_promise(run: Option) -> js_sys::Promise { match run { - Some(r) => future_to_promise(async move { Ok(JsValue::from_f64(r.finish().await)) }), + Some(r) => future_to_promise(async move { + Ok(r.finish_parts().await.map_or(JsValue::NULL, |part| JsValue::from_f64(part.total_ms))) + }), None => js_sys::Promise::resolve(&JsValue::NULL), } } @@ -598,15 +600,34 @@ impl FhStream { Ok(obj) } - /// `generate` with its GPU time: `{ written, cost }`, `cost` a promise of milliseconds (`null` without timestamp - /// queries, when nothing was written, or for a cadence composite). The Pacer's `costSample(now, 'mid', ms)` takes it; its - /// probe requests are meant for this call. + /// `generate` with its GPU time: `{ written, cost, timing }`. Both promises resolve to `null` when timing + /// is unavailable. `cost` is the per-frame time used by the Pacer. `timing` separates `setupMs` + /// (first linear phase only) from `frameMs` and includes `totalMs`. #[wasm_bindgen(js_name = generateTimed)] pub fn generate_timed(&self, t: f32, out: u32) -> Result { let (g, run) = self.inner.borrow_mut().generate_timed(&self.gpu, t, out as usize).map_err(err)?; let obj = js_sys::Object::new(); js_sys::Reflect::set(&obj, &JsValue::from_str("written"), &JsValue::from_bool(g == Generated::Written))?; - js_sys::Reflect::set(&obj, &JsValue::from_str("cost"), &timed_promise(run))?; + let timing = match run { + Some(r) => future_to_promise(async move { + match r.finish_parts().await { + Some(parts) => to_js(&parts), + None => Ok(JsValue::NULL), + } + }), + None => js_sys::Promise::resolve(&JsValue::NULL), + }; + let sample = timing.clone(); + let cost = future_to_promise(async move { + let parts = JsFuture::from(sample).await?; + if parts.is_null() { + Ok(JsValue::NULL) + } else { + js_sys::Reflect::get(&parts, &JsValue::from_str("frameMs")) + } + }); + js_sys::Reflect::set(&obj, &JsValue::from_str("cost"), &cost)?; + js_sys::Reflect::set(&obj, &JsValue::from_str("timing"), &timing)?; Ok(obj.into()) } diff --git a/docs/api-js.md b/docs/api-js.md index bc0b3b9..c439a28 100644 --- a/docs/api-js.md +++ b/docs/api-js.md @@ -90,9 +90,11 @@ Camera warp on a pointer-locked page: `mouse(performance.now(), e.movementX, e.m `warp(output, slot, out, now)` (true: present output slot `out`; false: present the frame as it is). It needs `push` timestamps on the same clock (`performance.now()` at arrival), not media time ([integration guide](integration.md#input-latency-the-camera-warp)). -`pushTimed(slot, pts)` and `generateTimed(t, out)` do the same work under timestamp queries and add `cost`, a promise -of the GPU milliseconds (`null` without timestamps, when nothing ran, or for a cadence composite): what the Pacer's `costSample` wants, for -its probe requests and now and then otherwise (`generateTimed` returns `{ written, cost }`). In Firefox a pending +`pushTimed(slot, pts)` and `generateTimed(t, out)` add `cost`, a promise of GPU milliseconds for the Pacer's +`costSample`. If timing is unavailable or all readback slots are busy, the work still runs and `cost` resolves +to `null`. `generateTimed` also returns `timing`, a promise of `{ setupMs, frameMs, totalMs }` or `null`. +Its `cost` remains the per-frame time (`frameMs`). Use `totalMs` to measure the full call, including +the once-per-pair refinement (`setupMs`), which is `null` when no setup ran. In Firefox a pending readback (`classify`, `stats`, a `cost`) resolves only on GPU polls (70 to 100 ms); submit an empty command buffer every millisecond while one is pending (`device.queue.submit([])`) and it resolves in 5 ms. diff --git a/docs/api-rust.md b/docs/api-rust.md index 54872e4..5de520f 100644 --- a/docs/api-rust.md +++ b/docs/api-rust.md @@ -67,11 +67,16 @@ match stream.generate(engine.gpu(), 0.5, out)? { Generated::Written => present(o `StreamOptions`: `mode` (`Realtime`, `Video` with one frame of lookahead), `cadence` (anime on twos, video mode), `scene_cut` (`Some(SceneCut { threshold })`, default 0.08), `held_frames` (`Some(HeldFrames { mean, max })`, default -off), `inputs` / `outputs` created up front. `push_timed` and `generate_timed` do the same work under timestamp -queries and return the `TimedRun` to await (`block(gpu)` natively) for the GPU milliseconds the Pacer's -`cost_sample` takes. `stream.report()` counts pushes, pairs, mids, classifications. Details: +off), `inputs` / `outputs` created up front. `push_timed` and `generate_timed` submit the same work and +return no `TimedRun` when timing is unavailable or all readback slots are busy. Await +`TimedRun::finish` (or `block(gpu)` natively) for total GPU milliseconds, or `finish_parts` (`block_parts(gpu)` +natively) to see the once-per-pair linear-path setup and the frame render separately. `stream.report()` counts pushes, pairs, +mids, and classifications. Details: [ARCHITECTURE.md](../ARCHITECTURE.md). +Native Metal resolves timestamp counters only after the sampling submission completes. Native asynchronous hosts +must keep polling the device until the result is ready; the blocking methods handle both submissions. + Camera warp for games: `stream.mouse(gpu, t_ms, dx, dy)` per mouse event (on the clock of `push`'s timestamps: arrival times in host ms), `stream.set_mouse_captured(bool)`, and at present time `stream.warp(gpu, Shown::Input(slot) | Shown::Output(slot), out, now_ms)?`: true when output slot `out` holds the