From f0e8fb3640cfcafd3d2f09f471538d72c782476b Mon Sep 17 00:00:00 2001 From: monzikkkkk Date: Thu, 19 Nov 2026 22:22:25 +0200 Subject: [PATCH 1/3] Preserve flash timing and thin lines during camera pans --- CHANGELOG.md | 5 + crates/flyhigh-engine/src/gen_tex.rs | 55 +++++-- crates/flyhigh-engine/src/gpu/pipeline.rs | 6 + crates/flyhigh-engine/src/lib.rs | 1 + crates/flyhigh-engine/src/net/build.rs | 6 + crates/flyhigh-engine/src/pan.rs | 162 +++++++++++++++++++ crates/flyhigh-engine/src/stream/classify.rs | 30 +++- crates/flyhigh-engine/tests/stream.rs | 72 +++++++++ docs/options.md | 2 +- shaders/classify.wgsl | 44 +++-- shaders/pan_apply.wgsl | 37 +++++ shaders/pan_search.wgsl | 37 +++++ shaders/pan_select.wgsl | 25 +++ 13 files changed, 450 insertions(+), 32 deletions(-) create mode 100644 crates/flyhigh-engine/src/pan.rs create mode 100644 shaders/pan_apply.wgsl create mode 100644 shaders/pan_search.wgsl create mode 100644 shaders/pan_select.wgsl diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b91880..a7ce65b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ follow semantic versioning as described in [CONTRIBUTING.md](CONTRIBUTING.md). - Engine reports include live and peak GPU allocation bytes, with separate totals for frame slots, network buffers, cadence scratch, and auxiliary resources. +### Fixed + +- Preserve the timing of abrupt flashes, including localized flashes during a pan and flashes immediately after a cut. +- Preserve thin repeated lines on coherent pans in the texture generator at repair level 2 by aligning the original frames. + ## [0.5.0] - 2026-11-18 ### Added diff --git a/crates/flyhigh-engine/src/gen_tex.rs b/crates/flyhigh-engine/src/gen_tex.rs index dcc6385..00406e1 100644 --- a/crates/flyhigh-engine/src/gen_tex.rs +++ b/crates/flyhigh-engine/src/gen_tex.rs @@ -12,9 +12,11 @@ use crate::gmhs::{CadenceScratch, PairStats, StatsRun}; use crate::gpu::memory::Charge; use crate::net::build::PlanResources; +use crate::pan::PanRepair; use crate::{gmhs, Blob, Gpu, NetOpts, SessionExt, Step, TimedRun}; use anyhow::{Context, Result}; use serde_json::Value; +use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; @@ -109,6 +111,7 @@ pub struct GenTex { order: [usize; 3], stats: [PairStats; 3], scratch: Option, + pan: Option>, slots: Vec, // last pushed input slots, newest last (<= 3) n_pushed: u64, pending: Option, @@ -302,6 +305,8 @@ impl GenTex { warmed_tune = Some(choices); } } + let pan = (opts.repair == 2 && !opts.protection_mask) + .then(|| RefCell::new(PanRepair::new(gpu, opts.w, opts.h, &sess))); let scratch = if cadence { Some(CadenceScratch::new(gpu, &sess[0]).context("cadence: GMHS maps missing")?) } else { @@ -316,6 +321,7 @@ impl GenTex { order: [0, 1, 2], stats: [PairStats::default(); 3], scratch, + pan, slots: Vec::new(), n_pushed: 0, pending: None, @@ -386,6 +392,29 @@ impl GenTex { self.scratch.is_some() } + fn pair_steps(&self, gpu: &Gpu, pair: usize, a: usize, b: usize) -> Vec { + let (a, b) = ((a, &self.ins[a].1), (b, &self.ins[b].1)); + let mut steps = self.sess[pair].pair_steps_views(gpu, a, b); + if let Some(pan) = &self.pan { + pan.borrow_mut().search(gpu, pair, a, b, &mut steps); + } + steps + } + + fn repair_pan(&self, gpu: &Gpu, steps: &mut Vec, pair: usize, slots: (usize, usize), out: usize, t: f32) { + if let Some(pan) = &self.pan { + let (a, b) = slots; + steps.push(pan.borrow_mut().render( + gpu, + pair, + (a, &self.ins[a].1), + (b, &self.ins[b].1), + (out, &self.outs[out].1), + t, + )); + } + } + /// The host wrote the newest source frame into input slot `slot`: run its pair. Video + cadence: the pair's /// statistics readback is started; call `take_stats()` (native) or await it (browser) before generating. pub fn push_slot(&mut self, gpu: &Gpu, slot: usize) -> Result { @@ -412,14 +441,14 @@ impl GenTex { }; match self.opts.mode { TexMode::Realtime => { - let steps = self.sess[0].pair_steps_views(gpu, (prev, &self.ins[prev].1), (slot, &self.ins[slot].1)); + let steps = self.pair_steps(gpu, 0, prev, slot); let run = run(gpu, &steps, timed); Ok((PushInfo { ready: true, base_slot: prev, real_replaced: false }, run)) } TexMode::Video => { self.order.rotate_left(1); let sn = self.order[2]; - let steps = self.sess[sn].pair_steps_views(gpu, (prev, &self.ins[prev].1), (slot, &self.ins[slot].1)); + let steps = self.pair_steps(gpu, sn, prev, slot); let run = run(gpu, &steps, timed); self.stats.rotate_left(1); self.stats[2] = PairStats::default(); @@ -506,13 +535,14 @@ impl GenTex { let s = &self.sess[0]; let (sa, sb) = (self.slots[self.slots.len() - 2], self.slots[self.slots.len() - 1]); let (a, b, o) = ((sa, &self.ins[sa].1), (sb, &self.ins[sb].1), (out, &self.outs[out].1)); - let steps = if s.is_fast() && self.opts.linear_t { + let mut steps = if s.is_fast() && self.opts.linear_t { vec![s.render_tex_step(gpu, a, b, o, Some(0.5))] } else if s.is_fast() { s.mid_steps_fast(gpu, a, b, o) } else { s.mid_steps(gpu, out, o.1) }; + self.repair_pan(gpu, &mut steps, 0, (sa, sb), out, 0.5); Some(gpu.gpu_time_ms_n(&steps, 5)) } /// GPU time (ms) of the pair stage for the current pair (realtime mode), measured by running it again. @@ -522,7 +552,7 @@ impl GenTex { return None; } let (sa, sb) = (self.slots[self.slots.len() - 2], self.slots[self.slots.len() - 1]); - let steps = self.sess[0].pair_steps_views(gpu, (sa, &self.ins[sa].1), (sb, &self.ins[sb].1)); + let steps = self.pair_steps(gpu, 0, sa, sb); Some(gpu.gpu_time_ms_n(&steps, 3)) } /// Synthesise phase `t` of the current interval into output slot `out`. Returns false when nothing was written @@ -547,8 +577,8 @@ impl GenTex { } anyhow::ensure!(self.slots.len() >= 2, "realtime mode: push two frames first"); let s = &self.sess[0]; - let run = if s.is_fast() { - let (sa, sb) = (self.slots[self.slots.len() - 2], self.slots[self.slots.len() - 1]); + let (sa, sb) = (self.slots[self.slots.len() - 2], self.slots[self.slots.len() - 1]); + let (setup, mut steps) = if s.is_fast() { 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 @@ -559,16 +589,17 @@ impl GenTex { self.half_done = true; setup }; - gpu.submit_optional_timing(&setup, &[s.render_tex_step(gpu, a, b, (out, view), Some(t))], timed) + (setup, vec![s.render_tex_step(gpu, a, b, (out, view), Some(t))]) } else { s.set_t(gpu, t); - run(gpu, &s.mid_steps_fast(gpu, a, b, (out, view)), timed) + (Vec::new(), s.mid_steps_fast(gpu, a, b, (out, view))) } } else { s.set_t(gpu, t); - run(gpu, &s.mid_steps(gpu, out, view), timed) + (Vec::new(), s.mid_steps(gpu, out, view)) }; - Ok((true, run)) + self.repair_pan(gpu, &mut steps, 0, (sa, sb), out, t); + Ok((true, gpu.submit_optional_timing(&setup, &steps, timed))) } TexMode::Video => { anyhow::ensure!(self.slots.len() >= 3, "video mode: push three frames first"); @@ -592,7 +623,9 @@ impl GenTex { } let s = &self.sess[sc_]; s.set_t(gpu, t); - Ok((true, run(gpu, &s.mid_steps(gpu, out, view), timed))) + let mut steps = s.mid_steps(gpu, out, view); + self.repair_pan(gpu, &mut steps, sc_, (self.slots[0], self.slots[1]), out, t); + Ok((true, run(gpu, &steps, timed))) } } } diff --git a/crates/flyhigh-engine/src/gpu/pipeline.rs b/crates/flyhigh-engine/src/gpu/pipeline.rs index 0a78d83..06f76b3 100644 --- a/crates/flyhigh-engine/src/gpu/pipeline.rs +++ b/crates/flyhigh-engine/src/gpu/pipeline.rs @@ -140,6 +140,9 @@ const KERNELS: &[&str] = &[ "near_k", "near_t", "near_apply", + "pan_search", + "pan_select", + "pan_apply", ]; /// The kernel's name as the cache holds it, or None for a name that is not a kernel. @@ -181,6 +184,9 @@ pub(crate) fn kernel_source(name: &str) -> Option<(String, &'static str)> { "tex_in" => plain(include_str!("../../../../shaders/tex_in.wgsl"), "main"), "tex_out" => plain(include_str!("../../../../shaders/tex_out.wgsl"), "main"), "classify" => plain(include_str!("../../../../shaders/classify.wgsl"), "main"), + "pan_search" => plain(include_str!("../../../../shaders/pan_search.wgsl"), "main"), + "pan_select" => plain(include_str!("../../../../shaders/pan_select.wgsl"), "main"), + "pan_apply" => plain(include_str!("../../../../shaders/pan_apply.wgsl"), "main"), "implicit2" => plain(include_str!("../../../../shaders/conv_implicit2.wgsl"), "main"), "epilogue" => plain(include_str!("../../../../shaders/conv_epilogue.wgsl"), "main"), "fused" => plain(include_str!("../../../../shaders/conv_fused.wgsl"), "main"), diff --git a/crates/flyhigh-engine/src/lib.rs b/crates/flyhigh-engine/src/lib.rs index f342a7a..7c32d10 100644 --- a/crates/flyhigh-engine/src/lib.rs +++ b/crates/flyhigh-engine/src/lib.rs @@ -62,5 +62,6 @@ pub mod api; pub mod gen_tex; pub mod gmhs; pub mod pacer; +mod pan; pub mod stream; pub mod warp; diff --git a/crates/flyhigh-engine/src/net/build.rs b/crates/flyhigh-engine/src/net/build.rs index fe04eb0..3c44c2c 100644 --- a/crates/flyhigh-engine/src/net/build.rs +++ b/crates/flyhigh-engine/src/net/build.rs @@ -737,6 +737,12 @@ pub(crate) fn build_network_with( env.insert(names(op, "out")[0].clone(), o); } if let Some(age) = &static_age { + if net.repair == 2 { + env.insert( + "static:age".into(), + Tensor { buf: age.clone(), c: 1, h: hp, w: wp, c0: 0, scale: static_frames as f32 }, + ); + } // the whole padded plane: the padding replicates the frame's edge, so the neighbourhood test stays valid there let r = &env["render"]; assert!(r.c0 == 0 && (r.h, r.w) == (hp, wp), "keep_static: render is not a full-resolution plain tensor"); diff --git a/crates/flyhigh-engine/src/pan.rs b/crates/flyhigh-engine/src/pan.rs new file mode 100644 index 0000000..db1928b --- /dev/null +++ b/crates/flyhigh-engine/src/pan.rs @@ -0,0 +1,162 @@ +//! Preserve fine repeated edges when a single translation aligns the original frames. +use crate::gpu::memory::Buffer; +use crate::ops::step::meta; +use crate::{clone_step, workgroups_2d, Binding, Gpu, SessionExt, Step, Tensor}; +use std::collections::HashMap; + +type Input<'a> = (usize, &'a wgpu::TextureView); + +pub(crate) struct PanRepair { + size: (u32, u32), + sampler: wgpu::Sampler, + phase: Buffer, + fits: Vec, + ages: Vec>, + errors: Buffer, + levels: [(u32, Buffer); 3], + searches: HashMap<(usize, usize, usize), Vec>, + renders: HashMap<(usize, usize, usize, usize), Step>, +} + +impl PanRepair { + pub(crate) fn new(gpu: &Gpu, w: u32, h: u32, sessions: &[SessionExt]) -> Self { + let buffer = |label, size, usage| { + gpu.buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false }) + }; + Self { + size: (w, h), + sampler: gpu.device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("fh_pan"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }), + phase: buffer("fh_pan_phase", 16, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST), + fits: (0..sessions.len()).map(|_| buffer("fh_pan_fit", 16, wgpu::BufferUsages::STORAGE)).collect(), + ages: sessions.iter().map(|s| s.env.get("fast:age").or_else(|| s.env.get("static:age")).cloned()).collect(), + errors: buffer("fh_pan_errors", 225 * 4, wgpu::BufferUsages::STORAGE), + levels: [(15u32, 1u32), (9, 4), (9, 16)].map(|(width, divisor)| { + let params = [w, h, width, divisor, u32::from(divisor == 1), u32::from(divisor == 16), 0, 0]; + ( + width, + gpu.buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("fh_pan_search_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }), + ) + }), + searches: HashMap::new(), + renders: HashMap::new(), + } + } + + pub(crate) fn search(&mut self, gpu: &Gpu, pair: usize, a: Input<'_>, b: Input<'_>, plan: &mut Vec) { + let (w, h) = self.size; + let steps = self.searches.entry((pair, a.0, b.0)).or_insert_with(|| { + let mut steps = Vec::with_capacity(2 * self.levels.len()); + let fit = &self.fits[pair]; + for (width, params) in &self.levels { + let samples = [ + wgpu::BindingResource::TextureView(a.1), + wgpu::BindingResource::TextureView(b.1), + wgpu::BindingResource::Sampler(&self.sampler), + fit.as_entire_binding(), + self.errors.as_entire_binding(), + params.as_entire_binding(), + ]; + let select = [self.errors.as_entire_binding(), fit.as_entire_binding(), params.as_entire_binding()]; + steps.push(step( + gpu, + "pan_search", + &samples, + (width * width, 1, 1), + vec![ + Binding::Texture(w, h), + Binding::Texture(w, h), + Binding::Sampler, + Binding::Buffer(fit.size()), + Binding::Buffer(self.errors.size()), + Binding::Params, + ], + &[fit, &self.errors, params], + )); + steps.push(step( + gpu, + "pan_select", + &select, + (1, 1, 1), + vec![Binding::Buffer(self.errors.size()), Binding::Buffer(fit.size()), Binding::Params], + &[&self.errors, fit, params], + )); + } + steps + }); + plan.extend(steps.iter().map(clone_step)); + } + + pub(crate) fn render( + &mut self, + gpu: &Gpu, + pair: usize, + a: Input<'_>, + b: Input<'_>, + out: Input<'_>, + t: f32, + ) -> Step { + let (w, h) = self.size; + let age = self.ages[pair].as_ref(); + let age_buffer = age.map_or(gpu.zero.as_ref(), |t| t.buf.as_ref()); + let fit = &self.fits[pair]; + let step = self.renders.entry((pair, a.0, b.0, out.0)).or_insert_with(|| { + let resources = [ + wgpu::BindingResource::TextureView(a.1), + wgpu::BindingResource::TextureView(b.1), + wgpu::BindingResource::Sampler(&self.sampler), + fit.as_entire_binding(), + wgpu::BindingResource::TextureView(out.1), + self.phase.as_entire_binding(), + age_buffer.as_entire_binding(), + ]; + step( + gpu, + "pan_apply", + &resources, + workgroups_2d(w, h, 1), + vec![ + Binding::Texture(w, h), + Binding::Texture(w, h), + Binding::Sampler, + Binding::Buffer(16), + Binding::Texture(w, h), + Binding::Params, + Binding::Buffer(age_buffer.size()), + ], + &[fit, &self.phase, age_buffer], + ) + }); + gpu.queue.write_buffer(&self.phase, 0, bytemuck::cast_slice(&[t, age.map_or(0.0, |a| a.scale), 0.0, 0.0])); + clone_step(step) + } +} + +fn step( + gpu: &Gpu, + pipe: &'static str, + resources: &[wgpu::BindingResource<'_>], + groups: (u32, u32, u32), + bindings: Vec, + buffers: &[&Buffer], +) -> Step { + let entries: Vec<_> = resources + .iter() + .enumerate() + .map(|(binding, resource)| wgpu::BindGroupEntry { binding: binding as u32, resource: resource.clone() }) + .collect(); + let bg = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some(pipe), + layout: &gpu.pipeline(pipe).get_bind_group_layout(0), + entries: &entries, + }); + Step::Compute { pipe, bg, groups, meta: meta(bindings, &[], buffers.iter().copied(), None) } +} diff --git a/crates/flyhigh-engine/src/stream/classify.rs b/crates/flyhigh-engine/src/stream/classify.rs index 695a7fc..81d3a7e 100644 --- a/crates/flyhigh-engine/src/stream/classify.rs +++ b/crates/flyhigh-engine/src/stream/classify.rs @@ -1,5 +1,5 @@ //! The pair classifier: is the interval between two source frames motion, a scene cut or a held frame. A tiny -//! compute pass over the two textures (classify.wgsl) and an 8-byte readback; the decision lands asynchronously, +//! compute pass over the two textures (classify.wgsl) and a 12-byte readback; the decision lands asynchronously, //! before the interval's first mid is due. use super::IntervalKind; use crate::gpu::memory::Buffer; @@ -17,6 +17,11 @@ pub const GRID: (u32, u32) = (48, 27); const IN_FLIGHT: usize = 3; /// The kernel's unit: the rgb absolute difference of one cell, 0..765 in 1/255 steps. const CELL_MAX: f32 = 765.0; +const STATS_BYTES: u64 = 12; +// A coherent tile must change brightness by at least 32 levels, with enough change across the frame to distinguish +// a flash from a small moving highlight. Flash steps use the cut path even during continuous camera motion. +const FLASH_LUMA: u32 = 32; +const FLASH_MEAN: f32 = 0.045; /// A pair over the cut threshold is a cut only when the moving pair before it differed by less than this share of /// the threshold. A camera flick in a game is a run of large differences (on a 60 fps capture the pair before a /// "cut" differed by 54 to 98 against a threshold of 90), a cut a lone spike after a calm pair (1 to 35 on anime); @@ -95,6 +100,15 @@ impl Classification { } self } + + fn with_history(mut self, tile_luma: u32, before: Option, th: &Thresholds) -> Self { + if th.cut_mean.is_some() && self.mean >= FLASH_MEAN && tile_luma >= FLASH_LUMA { + self.kind = IntervalKind::Cut; + self + } else { + self.after(before, th) + } + } } pub struct Classifier { @@ -119,7 +133,7 @@ impl Classifier { }); let stats = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_classify_stats"), - size: 8, + size: STATS_BYTES, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -132,7 +146,7 @@ impl Classifier { .map(|_| { let b = gpu.buffer(&wgpu::BufferDescriptor { label: Some("fh_classify_stage"), - size: 8, + size: STATS_BYTES, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -181,15 +195,15 @@ impl Classifier { }); // one stats buffer serves overlapping classifications: the zeroing, the dispatch and the copy out are // queue-ordered per submit - gpu.queue.write_buffer(&self.stats, 0, &[0u8; 8]); + gpu.queue.write_buffer(&self.stats, 0, &[0u8; STATS_BYTES as usize]); let mut enc = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("fh_classify") }); { let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor::default()); pass.set_pipeline(&pipe); pass.set_bind_group(0, &*bg, &[]); - pass.dispatch_workgroups(GRID.0.div_ceil(8), GRID.1.div_ceil(8), 1); + pass.dispatch_workgroups(GRID.0.div_ceil(8), GRID.1.div_ceil(9), 1); } - enc.copy_buffer_to_buffer(&self.stats, 0, &stage, 0, 8); + enc.copy_buffer_to_buffer(&self.stats, 0, &stage, 0, STATS_BYTES); gpu.queue.submit(Some(enc.finish())); let th = self.thresholds; let cells = GRID.0 * GRID.1; @@ -198,8 +212,8 @@ impl Classifier { Some(Readback::tracked( &stage, Box::new(move |d: &[u8]| { - let s: &[u32] = bytemuck::cast_slice(&d[..8]); - let c = Classification::from_stats(s[0], s[1], cells, &th).after(last_moving.get(), &th); + let s: &[u32] = bytemuck::cast_slice(&d[..STATS_BYTES as usize]); + let c = Classification::from_stats(s[0], s[1], cells, &th).with_history(s[2], last_moving.get(), &th); let held = c.kind == IntervalKind::Hold; if !held { last_moving.set(Some(c.mean)); diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 9cf9538..352a2da 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -178,6 +178,78 @@ fn the_classifier_tells_cuts_holds_and_motion_apart() { assert_eq!(s.counters().classified, 3); } +#[test] +#[ignore] +fn a_local_flash_and_its_clear_frame_are_discontinuities() { + 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(); + let original = [48u8, 48, 48, 255].repeat((W * H) as usize); + let mut flash = original.clone(); + for row in flash.as_chunks_mut::<{ (W * 4) as usize }>().0 { + for pixel in row[(3 * W) as usize..].as_chunks_mut::<4>().0 { + pixel[..3].fill(112); + } + } + write(&e, &s, 0, &original); + write(&e, &s, 1, &flash); + let onset = s.classify(&e.gpu, 0, 1).unwrap().block(&e.gpu).unwrap(); + let clear = s.classify(&e.gpu, 1, 0).unwrap().block(&e.gpu).unwrap(); + assert!(onset.mean < 0.08, "the localized flash is below the ordinary cut threshold"); + assert_eq!((onset.kind, clear.kind), (IntervalKind::Cut, IntervalKind::Cut)); +} + +#[test] +#[ignore] +fn a_rigid_pan_keeps_thin_repeated_lines_aligned() { + let Some(e) = engine() else { return }; + let panning = |shift: i32| { + let mut rgb = Vec::new(); + for y in 0..H as i32 { + let y = y - shift; + for x in 0..W as i32 { + let value = if (45..210).contains(&x) && (35..165).contains(&y) && y % 9 < 2 { + 216 + } else { + let edge = x > 26 + y / 4 && y > 21 && y < 148 - x / 7; + if edge { + 75 + } else { + 33 + } + }; + rgb.extend_from_slice(&[value, value, value, 255]); + } + } + rgb + }; + let mut opts = TexOptions::new(W, H); + opts.repair = 2; + opts.iw = 128; + opts.ih = 96; + for (mode, fast) in [(Mode::Realtime, false), (Mode::Realtime, true), (Mode::Video, false)] { + opts.fast_render = fast; + opts.linear_t = fast; + let stream = StreamOptions { mode, cadence: mode == Mode::Video, ..StreamOptions::default() }; + let mut s = Stream::new(&e.gpu, &e.blob, &e.ops, opts.clone(), &stream, None).unwrap(); + write(&e, &s, 0, &panning(0)); + write(&e, &s, 1, &panning(-8)); + s.push(&e.gpu, 0, 0.0).unwrap(); + s.push(&e.gpu, 1, 41.7).unwrap(); + if mode == Mode::Video { + s.resolve_stats(&e.gpu).unwrap(); + write(&e, &s, 2, &panning(-16)); + s.push(&e.gpu, 2, 83.4).unwrap(); + s.resolve_stats(&e.gpu).unwrap(); + } + assert_eq!(s.generate(&e.gpu, 0.5, 0).unwrap(), Generated::Written); + let reference = panning(-4); + let output = read_output(&e, &s, 0); + let interior = (24 * W * 4) as usize..((H - 24) * W * 4) as usize; + let error = mae(&output[interior.clone()], &reference[interior]); + assert!(error < 1.0, "moving lines should match the known midpoint ({mode:?}, fast={fast}, MAE={error:.3})"); + } +} + #[test] #[ignore] fn realtime_pushes_give_timestamped_intervals_and_mids() { diff --git a/docs/options.md b/docs/options.md index 388f726..3eff359 100644 --- a/docs/options.md +++ b/docs/options.md @@ -52,7 +52,7 @@ How source frames with timestamps become generatable intervals (ARCHITECTURE.md) |---|---|---|---|---| | `mode` | realtime | realtime, video | Realtime: no lookahead, the in-betweens of the previous and the newest frame; for games and capture. Video: one source frame of lookahead (one frame more latency), the interval that can be generated starts two frames back; cadence re-timing needs it. | `mode (0, 1)` | | `cadence` | off | on, off | Video mode only. Anime is often drawn on twos (each drawing held for two frames) over a camera pan on every frame; with cadence on, held elements are re-timed onto a smooth path. Presented frames are then generated in-betweens, the real drawings included, except where the model could not match the frames (there the real drawing stays): big drawing steps show the generator's softness more often. A choice for the viewer, not a default. Needs repair at least 1 (0 is raised to 1). | `cadence (0, 1)` | -| `scene_cut` | threshold 0.08 | off, or a threshold 0 to 1 | A pair whose mean per-channel difference (0 to 1, measured on a 48 x 27 grid) is above the threshold is a scene cut: the interval is not interpolated, the source frames are shown. Off = every pair is motion. | `scene_cut (threshold, 0 = off)` | +| `scene_cut` | threshold 0.08 | off, or a threshold 0 to 1 | Detects cuts from the mean per-channel difference on a 48 x 27 grid and detects abrupt brightness steps from spatially coherent changes. The player shows source frames across these transitions. | `scene_cut (threshold, 0 = off)` | | `held_frames` | off | off, or mean and max thresholds 0 to 1 | A pair whose mean difference is below `mean` and whose most different cell is below `max` is a held frame: shown as is and counted for the unique-frame rate, instead of a still in-between. The first change after a held frame is then shown as drawn too (animation on twos and threes is not motion), unless cadence re-timing spreads it. On for anime; the defaults 0.0033 and 0.06 stay above codec noise on a re-encoded hold. | `held_frames (0, 1), held_mean, held_max` | | `inputs` | 4 | | Input slots created up front (more with `add_input`); the Pacer's history says how many a host needs. | `inputs` | | `outputs` | 4 | | Output slots created up front (more with `add_output`). | `outputs` | diff --git a/shaders/classify.wgsl b/shaders/classify.wgsl index aeefae7..b4c6fc7 100644 --- a/shaders/classify.wgsl +++ b/shaders/classify.wgsl @@ -1,21 +1,41 @@ // Pair classification for the Stream (stream/classify.rs): the two source frames sampled on a gw x gh grid (one // bilinear sample at each cell centre), the sum over cells of the rgb absolute difference in 1/255 steps (0..765 per -// cell) and its maximum. A scene cut has a large mean, a held frame a tiny mean and maximum. The 48 x 27 grid and -// these units are what the extension measured its thresholds on. +// cell), its maximum, and the strongest coherent brightness change in an 8 x 9 tile. struct Par { gw: u32, gh: u32, _a: u32, _b: u32 }; @group(0) @binding(0) var tex_a: texture_2d; @group(0) @binding(1) var tex_b: texture_2d; @group(0) @binding(2) var samp: sampler; -@group(0) @binding(3) var stats: array, 2>; +@group(0) @binding(3) var stats: array, 3>; @group(0) @binding(4) var pp: Par; -@compute @workgroup_size(8, 8, 1) -fn main(@builtin(global_invocation_id) gid: vec3) { - if (gid.x >= pp.gw || gid.y >= pp.gh) { return; } - let uv = (vec2(f32(gid.x), f32(gid.y)) + 0.5) / vec2(f32(pp.gw), f32(pp.gh)); - let a = textureSampleLevel(tex_a, samp, uv, 0.0).rgb; - let b = textureSampleLevel(tex_b, samp, uv, 0.0).rgb; - let d = u32(dot(abs(a - b), vec3(255.0, 255.0, 255.0))); - atomicAdd(&stats[0], d); - atomicMax(&stats[1], d); +var luma_change: array; + +@compute @workgroup_size(8, 9, 1) +fn main(@builtin(global_invocation_id) gid: vec3, @builtin(local_invocation_index) i: u32) { + var luma = 0.0; + if (gid.x < pp.gw && gid.y < pp.gh) { + let uv = (vec2(gid.xy) + 0.5) / vec2(f32(pp.gw), f32(pp.gh)); + let a = textureSampleLevel(tex_a, samp, uv, 0.0).rgb; + let b = textureSampleLevel(tex_b, samp, uv, 0.0).rgb; + let delta = b - a; + let d = u32(dot(abs(delta), vec3(255.0))); + atomicAdd(&stats[0], d); + atomicMax(&stats[1], d); + luma = dot(delta, vec3(0.2126, 0.7152, 0.0722)); + } + luma_change[i] = luma; + workgroupBarrier(); + if (i == 0u) { + var signed = 0.0; + var total = 0.0; + for (var j = 0u; j < 72u; j++) { + let change = luma_change[j]; + signed += change; + total += abs(change); + } + // Motion normally makes both brighter and darker samples in a tile. A flash changes them in one direction. + if (abs(signed) >= 0.74 * total) { + atomicMax(&stats[2], u32(round(abs(signed) * 255.0 / 72.0))); + } + } } diff --git a/shaders/pan_apply.wgsl b/shaders/pan_apply.wgsl new file mode 100644 index 0000000..70c139b --- /dev/null +++ b/shaders/pan_apply.wgsl @@ -0,0 +1,37 @@ +enable f16; +// Use the translation where both warped originals still agree. Occlusions, independently moving elements and the +// revealed frame border retain the network result already in dst. +@group(0) @binding(0) var a: texture_2d; +@group(0) @binding(1) var b: texture_2d; +@group(0) @binding(2) var linear_sampler: sampler; +@group(0) @binding(3) var fit: vec4; +@group(0) @binding(4) var dst: texture_storage_2d; +struct Phase { t: f32, min_age: f32, _b: f32, _c: f32 } +@group(0) @binding(5) var phase: Phase; +@group(0) @binding(6) var ages: array; + +fn age_at(p: vec2, stride: u32) -> f32 { + return f32(ages[p.y * stride + p.x]); +} + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3) { + let size = textureDimensions(dst); + if (fit.z == 0.0 || any(id.xy >= size)) { return; } + let p = vec2(id.xy) + 0.5; + let pa = p - phase.t * fit.xy; + let pb = p + (1.0 - phase.t) * fit.xy; + let lo = vec2(0.5); + let hi = vec2(size) - lo; + if (any(pa < lo) || any(pa > hi) || any(pb < lo) || any(pb > hi)) { return; } + if (phase.min_age > 0.0) { + let stride = ((size.x + 31u) / 32u) * 32u; + if (age_at(id.xy, stride) > phase.min_age - 2.0 + || age_at(vec2(pa), stride) >= phase.min_age + || age_at(vec2(pb), stride) >= phase.min_age) { return; } + } + let ca = textureSampleLevel(a, linear_sampler, pa / vec2(size), 0.0).rgb; + let cb = textureSampleLevel(b, linear_sampler, pb / vec2(size), 0.0).rgb; + if (any(abs(ca - cb) > vec3(0.06))) { return; } + textureStore(dst, id.xy, vec4(mix(ca, cb, phase.t), 1.0)); +} diff --git a/shaders/pan_search.wgsl b/shaders/pan_search.wgsl new file mode 100644 index 0000000..92b9682 --- /dev/null +++ b/shaders/pan_search.wgsl @@ -0,0 +1,37 @@ +// Score a translation on the original textures. Each workgroup tests one candidate. +struct Search { w: u32, h: u32, width: u32, divisor: u32, initial: u32, finish: u32, _a: u32, _b: u32 } +@group(0) @binding(0) var a: texture_2d; +@group(0) @binding(1) var b: texture_2d; +@group(0) @binding(2) var linear_sampler: sampler; +@group(0) @binding(3) var fit: vec4; +@group(0) @binding(4) var errors: array; +@group(0) @binding(5) var search: Search; + +const N = 192u; +var sums: array; + +@compute @workgroup_size(64) +fn main(@builtin(workgroup_id) candidate: vec3, @builtin(local_invocation_index) lane: u32) { + let size = vec2(f32(search.w), f32(search.h)); + let spacing = max(1.0, size.y / 144.0) / f32(search.divisor); + let offset = (vec2(f32(candidate.x % search.width), f32(candidate.x / search.width)) + - f32(search.width / 2u)) * spacing; + let base = select(fit.xy, vec2(0.0), search.initial != 0u); + let delta = (base + offset) / size; + var sum = 0.0; + for (var i = lane; i < N; i += 64u) { + // Jitter the sparse grid so a periodic edge can't always land between sample rows. + let jitter = vec2(f32((i * 13u) % 17u), f32((i * 11u) % 13u)) / vec2(17.0, 13.0); + let uv = 0.12 + 0.76 * (vec2(f32(i % 16u), f32(i / 16u)) + jitter) / vec2(16.0, 12.0); + let ca = textureSampleLevel(a, linear_sampler, uv, 0.0).rgb; + let cb = textureSampleLevel(b, linear_sampler, uv + delta, 0.0).rgb; + sum += dot(abs(ca - cb), vec3(1.0 / 3.0)); + } + sums[lane] = sum; + workgroupBarrier(); + for (var step = 32u; step > 0u; step >>= 1u) { + if (lane < step) { sums[lane] += sums[lane + step]; } + workgroupBarrier(); + } + if (lane == 0u) { errors[candidate.x] = sums[0] / f32(N); } +} diff --git a/shaders/pan_select.wgsl b/shaders/pan_select.wgsl new file mode 100644 index 0000000..e94a628 --- /dev/null +++ b/shaders/pan_select.wgsl @@ -0,0 +1,25 @@ +// Retain the best candidate for the next refinement. Only a close match with a large gain over zero shift +// can replace the network's motion in the renderer. +struct Search { w: u32, h: u32, width: u32, divisor: u32, initial: u32, finish: u32, _a: u32, _b: u32 } +@group(0) @binding(0) var errors: array; +@group(0) @binding(1) var fit: vec4; +@group(0) @binding(2) var search: Search; + +@compute @workgroup_size(1) +fn main() { + let size = vec2(f32(search.w), f32(search.h)); + let count = search.width * search.width; + let center = count / 2u; + var best = center; + for (var j = 0u; j < count; j++) { + if (errors[j] < errors[best]) { best = j; } + } + let spacing = max(1.0, size.y / 144.0) / f32(search.divisor); + let offset = (vec2(f32(best % search.width), f32(best / search.width)) + - f32(search.width / 2u)) * spacing; + let shift = select(fit.xy, vec2(0.0), search.initial != 0u) + offset; + let still_error = select(fit.w, errors[center], search.initial != 0u); + let trusted = search.finish != 0u && errors[best] < 0.010 && errors[best] < 0.30 * still_error + && still_error > 0.016 && length(shift) > 1.0 && all(abs(shift) < size * 0.10); + fit = vec4(shift, select(0.0, 1.0, trusted), still_error); +} From 585cbf4a29b8dd627cffaf2837232ecd545572be Mon Sep 17 00:00:00 2001 From: monzikkkkk Date: Fri, 20 Nov 2026 03:36:18 +0200 Subject: [PATCH 2/3] Prepare FlyHigh v0.5.1 and preserve panning line details --- CHANGELOG.md | 13 +++- Cargo.lock | 12 ++-- Cargo.toml | 2 +- crates/flyhigh-engine/tests/stream.rs | 51 +++++++++++++++ shaders/pan_apply.wgsl | 91 +++++++++++++++++++++++---- shaders/pan_search.wgsl | 6 ++ shaders/pan_select.wgsl | 4 +- 7 files changed, 157 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7ce65b..f23bc6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,15 +5,26 @@ follow semantic versioning as described in [CONTRIBUTING.md](CONTRIBUTING.md). ## [Unreleased] +## [0.5.1] - 2026-11-20 + ### Added - Engine reports include live and peak GPU allocation bytes, with separate totals for frame slots, network buffers, cadence scratch, and auxiliary resources. +- Browser timing reports expose the cost of first-phase setup, frame rendering, and the total on successful samples. + +### Changed + +- Anime cadence smoothing shares model weights and transient GPU buffers across its three plans, reducing memory use. +- Low-level Rust buffer allocation APIs now return a tracked `Buffer` that dereferences to `wgpu::Buffer`. ### Fixed - Preserve the timing of abrupt flashes, including localized flashes during a pan and flashes immediately after a cut. -- Preserve thin repeated lines on coherent pans in the texture generator at repair level 2 by aligning the original frames. +- Preserve thin repeated lines and newly visible frame edges on coherent pans at repair level 2 by aligning the + original frames. Local contrast matching keeps lines intact when the two source frames have different brightness. +- Bound concurrent GPU timestamp readbacks and resolve Metal timestamps after the GPU records them. +- Attach asynchronous cadence statistics to their original interval so a late result cannot affect playback after a seek. ## [0.5.0] - 2026-11-18 diff --git a/Cargo.lock b/Cargo.lock index a539f27..2a8f3a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,7 +548,7 @@ dependencies = [ [[package]] name = "flyhigh-capi" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "flyhigh-engine", @@ -558,7 +558,7 @@ dependencies = [ [[package]] name = "flyhigh-cli" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "bytemuck", @@ -573,7 +573,7 @@ dependencies = [ [[package]] name = "flyhigh-engine" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "ash", @@ -590,7 +590,7 @@ dependencies = [ [[package]] name = "flyhigh-options" -version = "0.5.0" +version = "0.5.1" dependencies = [ "proc-macro2", "quote", @@ -599,7 +599,7 @@ dependencies = [ [[package]] name = "flyhigh-player" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "flyhigh-engine", @@ -610,7 +610,7 @@ dependencies = [ [[package]] name = "flyhigh-web" -version = "0.5.0" +version = "0.5.1" dependencies = [ "console_error_panic_hook", "flyhigh-engine", diff --git a/Cargo.toml b/Cargo.toml index 7110e5d..2fba402 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/flyhigh-options", "crates/flyhigh-engine", "crates/flyhigh-ca default-members = ["crates/flyhigh-options", "crates/flyhigh-engine", "crates/flyhigh-capi", "crates/flyhigh-cli", "examples/player"] [workspace.package] -version = "0.5.0" +version = "0.5.1" edition = "2021" license = "Apache-2.0" repository = "https://github.com/getflyhigh/flyhigh-engine" diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index 352a2da..b4f72ae 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -209,6 +209,9 @@ fn a_rigid_pan_keeps_thin_repeated_lines_aligned() { for x in 0..W as i32 { let value = if (45..210).contains(&x) && (35..165).contains(&y) && y % 9 < 2 { 216 + } else if (x < 45 || x > 210) && !(24..166).contains(&y) { + // Fine detail reaches into the strip visible in just one of the source frames. + 34 + ((x * 19 + y * 31).rem_euclid(79)) as u8 } else { let edge = x > 26 + y / 4 && y > 21 && y < 148 - x / 7; if edge { @@ -247,6 +250,54 @@ fn a_rigid_pan_keeps_thin_repeated_lines_aligned() { let interior = (24 * W * 4) as usize..((H - 24) * W * 4) as usize; let error = mae(&output[interior.clone()], &reference[interior]); assert!(error < 1.0, "moving lines should match the known midpoint ({mode:?}, fast={fast}, MAE={error:.3})"); + let strip_bytes = (4 * W * 4) as usize; + let top = mae(&output[..strip_bytes], &reference[..strip_bytes]); + let bottom = mae(&output[output.len() - strip_bytes..], &reference[reference.len() - strip_bytes..]); + assert!( + top < 1.0 && bottom < 1.0, + "pan edges should use available source ({mode:?}, fast={fast}, MAE={top:.3}/{bottom:.3})" + ); + } +} + +#[test] +#[ignore] +fn a_panned_line_with_different_contrast_stays_continuous() { + let Some(e) = engine() else { return }; + let draw = |shift: u32, value: u8| { + let mut rgba = frame(shift as f32); + for pixel in rgba.chunks_exact_mut(4) { + let background = 16 + pixel[0] / 4 + pixel[1] / 8 + pixel[2] / 8; + pixel[..3].fill(background); + } + for y in 48..140 { + for x in (80 + shift)..(84 + shift) { + let offset = ((y * W + x) * 4) as usize; + rgba[offset..offset + 3].fill(value); + } + } + rgba + }; + let mut opts = TexOptions::new(W, H); + opts.repair = 2; + opts.iw = 128; + opts.ih = 96; + opts.fast_render = true; + opts.linear_t = true; + let mut s = Stream::new(&e.gpu, &e.blob, &e.ops, opts, &StreamOptions::default(), None).unwrap(); + write(&e, &s, 0, &draw(0, 210)); + write(&e, &s, 1, &draw(8, 186)); + s.push(&e.gpu, 0, 0.0).unwrap(); + s.push(&e.gpu, 1, 41.7).unwrap(); + assert_eq!(s.generate(&e.gpu, 0.5, 0).unwrap(), Generated::Written); + let output = read_output(&e, &s, 0); + for y in 54..134 { + let offset = ((y * W + 85) * 4) as usize; + assert!( + output[offset].abs_diff(198) < 8, + "line at row {y} differs from the aligned midpoint: {}", + output[offset] + ); } } diff --git a/shaders/pan_apply.wgsl b/shaders/pan_apply.wgsl index 70c139b..0b77a56 100644 --- a/shaders/pan_apply.wgsl +++ b/shaders/pan_apply.wgsl @@ -1,6 +1,6 @@ enable f16; -// Use the translation where both warped originals still agree. Occlusions, independently moving elements and the -// revealed frame border retain the network result already in dst. +// Use the translation where the originals agree on the background motion. +// Independently moving elements retain the network result already in dst. @group(0) @binding(0) var a: texture_2d; @group(0) @binding(1) var b: texture_2d; @group(0) @binding(2) var linear_sampler: sampler; @@ -14,24 +14,89 @@ fn age_at(p: vec2, stride: u32) -> f32 { return f32(ages[p.y * stride + p.x]); } +fn rgb_peak(ca: vec3, cb: vec3) -> f32 { + let d = abs(ca - cb); + return max(max(d.r, d.g), d.b); +} + +struct Patch { mean_error: f32, max_error: f32, same_detail: bool } + +fn compare_patch(p: vec2, dims: vec2, shift_a: vec2, shift_b: vec2, + center_a: vec3, center_b: vec3, compare_detail: bool) -> Patch { + let neighbours = array, 4>( + vec2(-2.0, 0.0), vec2(2.0, 0.0), vec2(0.0, -2.0), vec2(0.0, 2.0) + ); + var sum = 0.0; + var peak = 0.0; + var detail_a = vec4(0.0); + var detail_b = vec4(0.0); + let luma = vec3(0.2126, 0.7152, 0.0722); + for (var i = 0u; i < 4u; i++) { + let q = p + neighbours[i]; + let ca = textureSampleLevel(a, linear_sampler, (q + shift_a) / dims, 0.0).rgb; + let cb = textureSampleLevel(b, linear_sampler, (q + shift_b) / dims, 0.0).rgb; + let error = rgb_peak(ca, cb); + sum += error; + peak = max(peak, error); + if (compare_detail) { + detail_a[i] = dot(center_a - ca, luma); + detail_b[i] = dot(center_b - cb, luma); + } + } + // A thin edge sampled at different subpixel positions can have different brightness in each + // source. Compare the signed local contrast pattern so it survives without accepting unrelated pixels. + let aa = dot(detail_a, detail_a); + let bb = dot(detail_b, detail_b); + let ab = dot(detail_a, detail_b); + let same_detail = min(aa, bb) > 0.02 && min(aa, bb) > 0.42 * max(aa, bb) + && ab > 0.0 && ab * ab > 0.94 * aa * bb; + return Patch(sum * 0.25, peak, same_detail); +} + @compute @workgroup_size(8, 8) fn main(@builtin(global_invocation_id) id: vec3) { let size = textureDimensions(dst); - if (fit.z == 0.0 || any(id.xy >= size)) { return; } + if (fit.z <= 0.0 || any(id.xy >= size)) { return; } + let dims = vec2(size); let p = vec2(id.xy) + 0.5; - let pa = p - phase.t * fit.xy; - let pb = p + (1.0 - phase.t) * fit.xy; + let shift_a = -phase.t * fit.xy; + let shift_b = (1.0 - phase.t) * fit.xy; + let pa = p + shift_a; + let pb = p + shift_b; let lo = vec2(0.5); - let hi = vec2(size) - lo; - if (any(pa < lo) || any(pa > hi) || any(pb < lo) || any(pb > hi)) { return; } + let hi = dims - lo; + let has_a = all(pa >= lo) && all(pa <= hi); + let has_b = all(pb >= lo) && all(pb <= hi); + let ca = textureSampleLevel(a, linear_sampler, pa / dims, 0.0).rgb; + let cb = textureSampleLevel(b, linear_sampler, pb / dims, 0.0).rgb; + if (has_a && has_b) { + // Compression and subpixel sampling can leave isolated mismatches on an otherwise aligned line. + let peak = rgb_peak(ca, cb); + if (peak > 0.06) { + if (peak > 0.16) { return; } + let local = compare_patch(p, dims, shift_a, shift_b, ca, cb, true); + let colour_match = local.mean_error <= 0.045 && local.max_error <= 0.10; + if (!colour_match && !(local.same_detail && local.max_error <= 0.13)) { return; } + } + } else { + // The pan reveals or hides a strip at the frame edge. Only one source sees those pixels. + // Check the adjacent overlap before using that source in place of a two-sided warp. + if (!has_a && !has_b) { return; } + let overlap_lo = lo - min(shift_a, shift_b) + 2.0; + let overlap_hi = hi - max(shift_a, shift_b) - 2.0; + if (any(overlap_lo > overlap_hi) + || compare_patch(clamp(p, overlap_lo, overlap_hi), dims, shift_a, shift_b, ca, cb, false).max_error > 0.045) { + return; + } + } if (phase.min_age > 0.0) { let stride = ((size.x + 31u) / 32u) * 32u; + let ia = vec2(clamp(pa, lo, hi)); + let ib = vec2(clamp(pb, lo, hi)); if (age_at(id.xy, stride) > phase.min_age - 2.0 - || age_at(vec2(pa), stride) >= phase.min_age - || age_at(vec2(pb), stride) >= phase.min_age) { return; } + || (has_a && age_at(ia, stride) >= phase.min_age) + || (has_b && age_at(ib, stride) >= phase.min_age)) { return; } } - let ca = textureSampleLevel(a, linear_sampler, pa / vec2(size), 0.0).rgb; - let cb = textureSampleLevel(b, linear_sampler, pb / vec2(size), 0.0).rgb; - if (any(abs(ca - cb) > vec3(0.06))) { return; } - textureStore(dst, id.xy, vec4(mix(ca, cb, phase.t), 1.0)); + let weight = select(select(1.0, 0.0, has_a), phase.t, has_a && has_b); + textureStore(dst, id.xy, vec4(mix(ca, cb, weight), 1.0)); } diff --git a/shaders/pan_search.wgsl b/shaders/pan_search.wgsl index 92b9682..1045cf8 100644 --- a/shaders/pan_search.wgsl +++ b/shaders/pan_search.wgsl @@ -9,9 +9,15 @@ struct Search { w: u32, h: u32, width: u32, divisor: u32, initial: u32, finish: const N = 192u; var sums: array; +var skip: u32; @compute @workgroup_size(64) fn main(@builtin(workgroup_id) candidate: vec3, @builtin(local_invocation_index) lane: u32) { + // A negative flag means the initial zero-shift comparison already ruled out a pan. + if (search.initial == 0u) { + if (lane == 0u) { skip = u32(fit.z < 0.0); } + if (workgroupUniformLoad(&skip) != 0u) { return; } + } let size = vec2(f32(search.w), f32(search.h)); let spacing = max(1.0, size.y / 144.0) / f32(search.divisor); let offset = (vec2(f32(candidate.x % search.width), f32(candidate.x / search.width)) diff --git a/shaders/pan_select.wgsl b/shaders/pan_select.wgsl index e94a628..6d4b157 100644 --- a/shaders/pan_select.wgsl +++ b/shaders/pan_select.wgsl @@ -7,6 +7,7 @@ struct Search { w: u32, h: u32, width: u32, divisor: u32, initial: u32, finish: @compute @workgroup_size(1) fn main() { + if (search.initial == 0u && fit.z < 0.0) { return; } let size = vec2(f32(search.w), f32(search.h)); let count = search.width * search.width; let center = count / 2u; @@ -21,5 +22,6 @@ fn main() { let still_error = select(fit.w, errors[center], search.initial != 0u); let trusted = search.finish != 0u && errors[best] < 0.010 && errors[best] < 0.30 * still_error && still_error > 0.016 && length(shift) > 1.0 && all(abs(shift) < size * 0.10); - fit = vec4(shift, select(0.0, 1.0, trusted), still_error); + let confidence = select(select(0.0, 1.0, trusted), -1.0, still_error <= 0.016); + fit = vec4(shift, confidence, still_error); } From 52e7484d9708350f2e67d3db9916744fe7060a7f Mon Sep 17 00:00:00 2001 From: monzikkkkk Date: Fri, 20 Nov 2026 03:40:12 +0200 Subject: [PATCH 3/3] Validate pan tests and regenerate scene-cut options docs --- crates/flyhigh-engine/src/stream/mod.rs | 4 ++-- crates/flyhigh-engine/tests/stream.rs | 4 ++-- docs/options.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/flyhigh-engine/src/stream/mod.rs b/crates/flyhigh-engine/src/stream/mod.rs index b870a1a..fa5b932 100644 --- a/crates/flyhigh-engine/src/stream/mod.rs +++ b/crates/flyhigh-engine/src/stream/mod.rs @@ -85,8 +85,8 @@ pub struct StreamOptions { /// default. Needs repair at least 1 (0 is raised to 1). #[option(values = "on, off", c = "cadence (0, 1)")] pub cadence: bool, - /// A pair whose mean per-channel difference (0 to 1, measured on a 48 x 27 grid) is above the threshold is a scene - /// cut: the interval is not interpolated, the source frames are shown. Off = every pair is motion. + /// Detects cuts from the mean per-channel difference on a 48 x 27 grid and detects abrupt brightness steps from + /// spatially coherent changes. The player shows source frames across these transitions. Off disables both checks. #[option(values = "off, or a threshold 0 to 1", c = "scene_cut (threshold, 0 = off)")] pub scene_cut: Option, /// A pair whose mean difference is below `mean` and whose most different cell is below `max` is a held frame: shown diff --git a/crates/flyhigh-engine/tests/stream.rs b/crates/flyhigh-engine/tests/stream.rs index b4f72ae..ba6601f 100644 --- a/crates/flyhigh-engine/tests/stream.rs +++ b/crates/flyhigh-engine/tests/stream.rs @@ -209,7 +209,7 @@ fn a_rigid_pan_keeps_thin_repeated_lines_aligned() { for x in 0..W as i32 { let value = if (45..210).contains(&x) && (35..165).contains(&y) && y % 9 < 2 { 216 - } else if (x < 45 || x > 210) && !(24..166).contains(&y) { + } else if !(45..=210).contains(&x) && !(24..166).contains(&y) { // Fine detail reaches into the strip visible in just one of the source frames. 34 + ((x * 19 + y * 31).rem_euclid(79)) as u8 } else { @@ -266,7 +266,7 @@ fn a_panned_line_with_different_contrast_stays_continuous() { let Some(e) = engine() else { return }; let draw = |shift: u32, value: u8| { let mut rgba = frame(shift as f32); - for pixel in rgba.chunks_exact_mut(4) { + for pixel in rgba.as_chunks_mut::<4>().0 { let background = 16 + pixel[0] / 4 + pixel[1] / 8 + pixel[2] / 8; pixel[..3].fill(background); } diff --git a/docs/options.md b/docs/options.md index 3eff359..ef581c7 100644 --- a/docs/options.md +++ b/docs/options.md @@ -52,7 +52,7 @@ How source frames with timestamps become generatable intervals (ARCHITECTURE.md) |---|---|---|---|---| | `mode` | realtime | realtime, video | Realtime: no lookahead, the in-betweens of the previous and the newest frame; for games and capture. Video: one source frame of lookahead (one frame more latency), the interval that can be generated starts two frames back; cadence re-timing needs it. | `mode (0, 1)` | | `cadence` | off | on, off | Video mode only. Anime is often drawn on twos (each drawing held for two frames) over a camera pan on every frame; with cadence on, held elements are re-timed onto a smooth path. Presented frames are then generated in-betweens, the real drawings included, except where the model could not match the frames (there the real drawing stays): big drawing steps show the generator's softness more often. A choice for the viewer, not a default. Needs repair at least 1 (0 is raised to 1). | `cadence (0, 1)` | -| `scene_cut` | threshold 0.08 | off, or a threshold 0 to 1 | Detects cuts from the mean per-channel difference on a 48 x 27 grid and detects abrupt brightness steps from spatially coherent changes. The player shows source frames across these transitions. | `scene_cut (threshold, 0 = off)` | +| `scene_cut` | threshold 0.08 | off, or a threshold 0 to 1 | Detects cuts from the mean per-channel difference on a 48 x 27 grid and detects abrupt brightness steps from spatially coherent changes. The player shows source frames across these transitions. Off disables both checks. | `scene_cut (threshold, 0 = off)` | | `held_frames` | off | off, or mean and max thresholds 0 to 1 | A pair whose mean difference is below `mean` and whose most different cell is below `max` is a held frame: shown as is and counted for the unique-frame rate, instead of a still in-between. The first change after a held frame is then shown as drawn too (animation on twos and threes is not motion), unless cadence re-timing spreads it. On for anime; the defaults 0.0033 and 0.06 stay above codec noise on a re-encoded hold. | `held_frames (0, 1), held_mean, held_max` | | `inputs` | 4 | | Input slots created up front (more with `add_input`); the Pacer's history says how many a host needs. | `inputs` | | `outputs` | 4 | | Output slots created up front (more with `add_output`). | `outputs` |