Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(poc-native): the WGSL compositor on native wgpu — pipe-bound at 31 fps

Etienne Lescot0c4e47a3df51
diff --git a/docs/architecture/rendering-architecture.md b/docs/architecture/rendering-architecture.md
index 9f101632c..d088dda79 100644
--- a/docs/architecture/rendering-architecture.md
+++ b/docs/architecture/rendering-architecture.md
@@ -674,6 +674,66 @@ multiple encoder instances, not a deeper queue on one), not the shader's.
---
+## Annex D — The native POC (Rust + wgpu), measured 2026-07-17
+
+Built at the product owner's insistence: forget Electron, measure the most native,
+most performant path. `poc-native/` — Rust, wgpu (Vulkan on the reference AMD
+iGPU), the AMD hardware encoder via ffmpeg `h264_amf`. No browser, no WebCodecs.
+
+**D.1 — The compositor is portable, proven.** wgpu runs `composite.wgsl`
+**unchanged** — the only edits are the two the web platform forces and native
+lacks (`texture_external` → `texture_2d`, `textureSampleBaseClampToEdge` →
+`textureSampleLevel`). The native frame at t=0.5s is pixel-identical to the web
+POC: padded recording, analytic erf shadow, circular webcam, rimmed cursor. §12's
+portability bet — "WGSL + evaluate move to native unchanged" — is now demonstrated,
+not asserted. This is the single most important native result: the product's
+substance is host-agnostic.
+
+**D.2 — Encoder ceilings, native, no browser (ffmpeg, `-benchmark`):**
+
+| path | throughput |
+|---|---:|
+| `h264_amf`, CPU-decoded frames | ~180 fps |
+| `d3d11va` decode → `h264_amf`, frames stay on GPU | **256 fps** |
+
+The hardware encoder is not the wall — 256 fps at 1080p when the frame never
+leaves the GPU.
+
+**D.3 — The naive native pipeline is 31 fps, and that is PIPE-BOUND, not native.**
+Stream-decode both sources, composite each on wgpu, encode with `h264_amf`, real
+animated timeline: **31 fps** — slower than the web POC's 79. But the cause was
+measured before it was concluded (this project punishes the reverse):
+
+- with encode pipe 31.2 fps; without it 31.7 fps → the encoder is not the wall;
+- **the decode pipe alone** (ffmpeg → /dev/null, 180 frames) is **30 fps**, 3.9 s
+ of it system time — 8 MB/frame × 180 = 1.4 GB of *uncompressed* pixels shoved
+ between subprocesses.
+
+So the wall is the **subprocess raw-RGBA pipes**, an artifact of reaching ffmpeg
+as a child process — not the descent, not the compositor (1.9 ms), not the encoder
+(256 fps). The browser wins *today* only because WebCodecs keeps frames in-process
+(`VideoFrame`s in memory), which no raw pipe crosses. **The 31 fps must never be
+quoted as "native loses."**
+
+**D.4 — What the native ceiling actually needs, still unbuilt:**
+1. **In-process codecs** (libavcodec via `ffmpeg-next`, or Media Foundation) — no
+ raw-frame pipes. Removes the 1.4 GB IPC that caps D.3.
+2. **Zero-descent GPU → encoder** — the composited wgpu texture handed to the
+ hardware encoder without the CPU readback, via Vulkan Video encode or
+ D3D12↔D3D11/AMF shared textures. This is the unmeasured §12 G-A premise, and
+ the only path that can turn the 256 fps encoder ceiling into real throughput.
+ It is deep unsafe interop (days, not hours).
+
+**The standing conclusion is unchanged but now grounded on both sides:** the web
+platform (WebCodecs) hands you the on-device fast path for free (79 fps, no interop
+written); native offers a much higher ceiling (256 fps encoder) but only behind
+hard, unbuilt interop. The compositor — the product's actual substance — runs
+either place unchanged. So ship on the web platform, keep WGSL + evaluate portable
+(done), and open the native core only if a §12 gate fires, now with the spike's two
+concrete steps named above.
+
+---
+
**Step-0 note (data loss, §13).** The record's reference project `os_parity`
(`proj_de6ffaaa…openscreen`) was found corrupted with exactly the §13 signature:
a complete, valid save (updatedAt 2026-07-16T18:00:26Z) followed by the tail of a
diff --git a/poc-native/.gitignore b/poc-native/.gitignore
new file mode 100644
index 000000000..95466d85b
--- /dev/null
+++ b/poc-native/.gitignore
@@ -0,0 +1,5 @@
+/target
+*.rgba
+*.bmp
+out-preview.png
+out.mp4
diff --git a/poc-native/Cargo.toml b/poc-native/Cargo.toml
new file mode 100644
index 000000000..9d2430b14
--- /dev/null
+++ b/poc-native/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "poc-native"
+version = "0.1.0"
+edition = "2021"
+
+# Native full-shader compositor POC. No browser, no Electron, no WebCodecs:
+# wgpu runs the same WGSL as the web POC (adapted from texture_external to plain
+# 2D textures, a WebGPU-only feature that native wgpu does not have), and the
+# hardware H.264 encoder is reached natively. This is the "most performant and
+# native possible" path the web POC could not measure.
+
+[dependencies]
+wgpu = "22"
+pollster = "0.3"
+bytemuck = { version = "1", features = ["derive"] }
+
+[profile.release]
+opt-level = 3
diff --git a/poc-native/src/bin/throughput.rs b/poc-native/src/bin/throughput.rs
new file mode 100644
index 000000000..6b79485a8
--- /dev/null
+++ b/poc-native/src/bin/throughput.rs
@@ -0,0 +1,288 @@
+// Native throughput POC: stream-decode both sources, composite every frame with
+// the WGSL shader on wgpu, encode with the AMD hardware H.264 encoder (h264_amf).
+// No browser, no WebCodecs. Reports the honest native throughput.
+//
+// This path DOES read the composited frame back to the CPU to pipe it into
+// ffmpeg — the "descent" the architecture doc names as the killer. That is
+// deliberate: it is the tractable native baseline. If it already beats the web
+// platform's 79 fps, native wins even carrying the descent; the zero-descent
+// GPU→encoder interop (the real §12 G-A prize) is the next step, and this is the
+// number it must beat.
+
+use std::io::{Read, Write};
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+const OUT_W: u32 = 1920;
+const OUT_H: u32 = 1080;
+const FPS: u32 = 30;
+const SCREEN_W: u32 = 1920;
+const SCREEN_H: u32 = 1032;
+const WEBCAM_W: u32 = 640;
+const WEBCAM_H: u32 = 480;
+const FRAMES: u32 = 180; // 6 s
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct Uniforms {
+ a: [f32; 4],
+ screen: [f32; 4],
+ webcam: [f32; 4],
+ fx: [f32; 4],
+ b: [f32; 4],
+ mb: [f32; 4],
+ cursor: [f32; 4],
+ cursor_fx: [f32; 4],
+}
+
+#[derive(Clone, Copy)]
+struct Rect { x: f32, y: f32, w: f32, h: f32 }
+
+fn ease(x: f32) -> f32 {
+ if x < 0.5 { 4.0 * x * x * x } else { 1.0 - (-2.0 * x + 2.0).powi(3) / 2.0 }
+}
+fn region_strength(t: f32, start: f32, end: f32, ramp: f32) -> f32 {
+ if t <= start || t >= end { return 0.0; }
+ let in_r = ((t - start) / ramp).min(1.0);
+ let out_r = ((end - t) / ramp).min(1.0);
+ ease(in_r.min(out_r))
+}
+fn lerp(a: f32, b: f32, t: f32) -> f32 { a + (b - a) * t }
+
+// evaluate(): zoom + layout animation + motion blur, ported from the web POC.
+fn evaluate(t: f32, prev: Option<(f32, f32, f32, f32)>) -> (Uniforms, (f32, f32, f32, f32)) {
+ let padding = 45.0;
+ let s = 1.0 - (padding / 100.0) * 0.4;
+ let bw = OUT_W as f32 * s;
+ let bh = OUT_H as f32 * s;
+ let base_screen = Rect { x: (OUT_W as f32 - bw) / 2.0, y: (OUT_H as f32 - bh) / 2.0, w: bw, h: bh };
+ let size = (OUT_H as f32 * 0.22).round();
+ let margin = (OUT_H as f32 * 0.04).round();
+ let base_webcam = Rect { x: OUT_W as f32 - size - margin, y: OUT_H as f32 - size - margin, w: size, h: size };
+
+ // zoom: strongest region wins
+ let zooms = [(1.0, 3.2, 1.7, 0.62, 0.42, 0.55), (4.4, 6.5, 2.3, 0.3, 0.7, 0.5)];
+ let (mut zoom, mut fxn, mut fyn, mut strength) = (1.0f32, 0.5f32, 0.5f32, 0.0f32);
+ for (st, en, sc, cx, cy, ramp) in zooms {
+ let str_ = region_strength(t, st, en, ramp);
+ if str_ > strength { strength = str_; zoom = lerp(1.0, sc, str_); fxn = cx; fyn = cy; }
+ }
+ let fx = base_screen.x + base_screen.w * fxn;
+ let fy = base_screen.y + base_screen.h * fyn;
+ let screen = Rect {
+ x: fx - (fx - base_screen.x) * zoom,
+ y: fy - (fy - base_screen.y) * zoom,
+ w: base_screen.w * zoom,
+ h: base_screen.h * zoom,
+ };
+
+ // layout move: webcam grows into a panel, shape morphs
+ let mut mv = 0.0f32;
+ mv = mv.max(region_strength(t, 2.4, 5.0, 0.6));
+ let panel_w = (OUT_W as f32 * 0.34).round();
+ let panel_h = (panel_w * 0.75).round();
+ let panel = Rect { x: OUT_W as f32 - panel_w - margin, y: OUT_H as f32 - panel_h - margin, w: panel_w, h: panel_h };
+ let webcam = Rect {
+ x: lerp(base_webcam.x, panel.x, mv),
+ y: lerp(base_webcam.y, panel.y, mv),
+ w: lerp(base_webcam.w, panel.w, mv),
+ h: lerp(base_webcam.h, panel.h, mv),
+ };
+ let webcam_radius = lerp(base_webcam.w.min(base_webcam.h) / 2.0, 26.0, mv);
+
+ // motion blur vector from centre delta
+ let cx = screen.x + screen.w / 2.0;
+ let cy = screen.y + screen.h / 2.0;
+ let (mut sbx, mut sby) = (0.0f32, 0.0f32);
+ if let Some((pcx, pcy, _, _)) = prev {
+ let k = 0.9;
+ sbx = ((cx - pcx) * k).clamp(-22.0, 22.0);
+ sby = ((cy - pcy) * k).clamp(-22.0, 22.0);
+ }
+
+ let cam_aspect = WEBCAM_W as f32 / WEBCAM_H as f32;
+ let cur_x = screen.x + 0.52 * screen.w;
+ let cur_y = screen.y + 0.90 * screen.h;
+ let u = Uniforms {
+ a: [OUT_W as f32, OUT_H as f32, t, 28.0],
+ screen: [screen.x, screen.y, screen.w, screen.h],
+ webcam: [webcam.x, webcam.y, webcam.w, webcam.h],
+ fx: [0.7, 0.0, 16.0, 22.0],
+ b: [webcam_radius, 0.0, cam_aspect, 0.0],
+ mb: [sbx, sby, 0.0, 0.0],
+ cursor: [cur_x, cur_y, OUT_H as f32 * 0.05, 1.0],
+ cursor_fx: [0.0, 0.0, 1.0, 0.0],
+ };
+ (u, (cx, cy, screen.w, screen.h))
+}
+
+fn spawn_decode(path: &str) -> std::process::Child {
+ // Force 30 fps so screen (60) and webcam decode align frame-to-frame.
+ Command::new("ffmpeg")
+ .args(["-hide_banner", "-loglevel", "error", "-i", path, "-vf", "fps=30", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
+ .stdout(Stdio::piped())
+ .spawn()
+ .expect("ffmpeg decode spawn")
+}
+
+fn read_frame(r: &mut impl Read, buf: &mut [u8]) -> bool {
+ let mut filled = 0;
+ while filled < buf.len() {
+ match r.read(&mut buf[filled..]) {
+ Ok(0) => return false,
+ Ok(n) => filled += n,
+ Err(_) => return false,
+ }
+ }
+ true
+}
+
+fn upload(queue: &wgpu::Queue, tex: &wgpu::Texture, w: u32, h: u32, rgba: &[u8]) {
+ queue.write_texture(
+ wgpu::ImageCopyTexture { texture: tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ rgba,
+ wgpu::ImageDataLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
+ );
+}
+
+fn tex2d(device: &wgpu::Device, w: u32, h: u32, label: &str) -> wgpu::Texture {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
+ mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ })
+}
+
+fn main() {
+ // --- decoders + encoder ---
+ let mut dec_s = spawn_decode("../poc/media/screen.mp4");
+ let mut dec_w = spawn_decode("../poc/media/webcam.mp4");
+ let mut sout = dec_s.stdout.take().unwrap();
+ let mut wout = dec_w.stdout.take().unwrap();
+
+ let mut enc = Command::new("ffmpeg")
+ .args([
+ "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "rawvideo", "-pixel_format", "rgba", "-video_size", &format!("{OUT_W}x{OUT_H}"), "-framerate", &FPS.to_string(), "-i", "-",
+ "-c:v", "h264_amf", "-b:v", "8M", "-usage", "transcoding", "out.mp4",
+ ])
+ .stdin(Stdio::piped())
+ .spawn()
+ .expect("ffmpeg encode spawn");
+ let mut ein = enc.stdin.take().unwrap();
+
+ // --- wgpu ---
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default()
+ })).expect("adapter");
+ println!("native gpu: {} (backend {:?})", adapter.get_info().name, adapter.get_info().backend);
+ let (device, queue) = pollster::block_on(adapter.request_device(
+ &wgpu::DeviceDescriptor { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::default(), memory_hints: wgpu::MemoryHints::Performance }, None,
+ )).expect("device");
+
+ let screen_tex = tex2d(&device, SCREEN_W, SCREEN_H, "screen");
+ let webcam_tex = tex2d(&device, WEBCAM_W, WEBCAM_H, "webcam");
+ let screen_view = screen_tex.create_view(&Default::default());
+ let webcam_view = webcam_tex.create_view(&Default::default());
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() });
+
+ let ubuf = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: std::mem::size_of::<Uniforms>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(include_str!("../composite.wgsl").into()) });
+ let format = wgpu::TextureFormat::Rgba8Unorm;
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: None, layout: None,
+ vertex: wgpu::VertexState { module: &shader, entry_point: "vs", buffers: &[], compilation_options: Default::default() },
+ fragment: Some(wgpu::FragmentState { module: &shader, entry_point: "fs", targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })], compilation_options: Default::default() }),
+ primitive: Default::default(), depth_stencil: None, multisample: Default::default(), multiview: None, cache: None,
+ });
+ let target = device.create_texture(&wgpu::TextureDescriptor {
+ label: None, size: wgpu::Extent3d { width: OUT_W, height: OUT_H, depth_or_array_layers: 1 },
+ mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[],
+ });
+ let target_view = target.create_view(&Default::default());
+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None, layout: &pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler) },
+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&screen_view) },
+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&webcam_view) },
+ ],
+ });
+ let bpr = ((OUT_W * 4 + 255) & !255) as u64;
+ let rbuf = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bpr * OUT_H as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
+
+ let mut screen_rgba = vec![0u8; (SCREEN_W * SCREEN_H * 4) as usize];
+ let mut webcam_rgba = vec![0u8; (WEBCAM_W * WEBCAM_H * 4) as usize];
+ let mut have_webcam = false;
+ let mut tight = vec![0u8; (OUT_W * OUT_H * 4) as usize];
+ let mut prev = None;
+ let warm = FRAMES / 4;
+ let mut warm_t = Instant::now();
+ let mut done = 0u32;
+
+ for i in 0..FRAMES {
+ if i == warm { warm_t = Instant::now(); }
+ if !read_frame(&mut sout, &mut screen_rgba) { break; }
+ if read_frame(&mut wout, &mut webcam_rgba) { have_webcam = true; } // else reuse last
+ let _ = have_webcam;
+
+ let t = i as f32 / FPS as f32;
+ let (u, memo) = evaluate(t, prev);
+ prev = Some(memo);
+
+ upload(&queue, &screen_tex, SCREEN_W, SCREEN_H, &screen_rgba);
+ upload(&queue, &webcam_tex, WEBCAM_W, WEBCAM_H, &webcam_rgba);
+ queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&u));
+
+ let mut e = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = e.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &target_view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store } })],
+ depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bind, &[]);
+ pass.draw(0..3, 0..1);
+ }
+ e.copy_texture_to_buffer(
+ wgpu::ImageCopyTexture { texture: &target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ wgpu::ImageCopyBuffer { buffer: &rbuf, layout: wgpu::ImageDataLayout { offset: 0, bytes_per_row: Some(bpr as u32), rows_per_image: Some(OUT_H) } },
+ wgpu::Extent3d { width: OUT_W, height: OUT_H, depth_or_array_layers: 1 },
+ );
+ queue.submit([e.finish()]);
+
+ // The descent: map the composited frame to the CPU, un-pad, pipe to encoder.
+ let slice = rbuf.slice(..);
+ slice.map_async(wgpu::MapMode::Read, |_| {});
+ device.poll(wgpu::Maintain::Wait);
+ {
+ let mapped = slice.get_mapped_range();
+ for y in 0..OUT_H {
+ let src = (y as u64 * bpr) as usize;
+ let dst = (y * OUT_W * 4) as usize;
+ tight[dst..dst + (OUT_W * 4) as usize].copy_from_slice(&mapped[src..src + (OUT_W * 4) as usize]);
+ }
+ }
+ rbuf.unmap();
+ if std::env::args().nth(1).as_deref() != Some("no-encode") { ein.write_all(&tight).expect("pipe to encoder"); }
+ done = i + 1;
+ }
+
+ drop(ein);
+ let _ = enc.wait();
+ let _ = dec_s.kill();
+ let _ = dec_w.kill();
+
+ let warm_frames = done.saturating_sub(warm);
+ let secs = warm_t.elapsed().as_secs_f32();
+ let fps = warm_frames as f32 / secs;
+ println!("native throughput: {:.1} fps ({warm_frames} frames after warm-up in {secs:.2}s, incl. descent + h264_amf)", fps);
+}
diff --git a/poc-native/src/composite.wgsl b/poc-native/src/composite.wgsl
new file mode 100644
index 000000000..129b028b6
--- /dev/null
+++ b/poc-native/src/composite.wgsl
@@ -0,0 +1,177 @@
+// Native compositor — the same WGSL as the web POC, adapted for native wgpu.
+//
+// Two changes only, both because `texture_external` is a WebGPU-only feature that
+// native wgpu does not have:
+// texture_external -> texture_2d<f32>
+// textureSampleBaseClampToEdge -> textureSampleLevel(..., 0.0)
+// Everything else — the geometry, the erf Gaussian shadow, the cursor SDF — is
+// byte-for-byte the browser shader. That is the portability the whole bet rests
+// on: the product's substance moves to native unchanged.
+//
+// Single pass here (not the web POC's 6 culled quads): natively the compositor is
+// nowhere near the bottleneck, so the quad-culling buys nothing and the one
+// fragment shader is simpler.
+
+struct U {
+ // stage.xy | time | screenRadius
+ a : vec4f,
+ // screenRect x,y,w,h (carries zoom)
+ screen : vec4f,
+ // webcamRect x,y,w,h (carries layout animation)
+ webcam : vec4f,
+ // shadowIntensity | bgBlurPx(unused native) | shadowOffsetY | shadowSigma
+ fx : vec4f,
+ // webcamRadius | motionBlur baked elsewhere | webcamCoverScale | unused
+ b : vec4f,
+ // screenBlur.xy | webcamBlur.xy
+ mb : vec4f,
+ // cursor x | y | size | opacity
+ cursor : vec4f,
+ // cursorBlur.xy | clickScale | unused
+ cursorFx : vec4f,
+};
+
+@group(0) @binding(0) var<uniform> u : U;
+@group(0) @binding(1) var samp : sampler;
+@group(0) @binding(2) var screenTex : texture_2d<f32>;
+@group(0) @binding(3) var webcamTex : texture_2d<f32>;
+
+struct VsOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+@vertex
+fn vs(@builtin(vertex_index) i : u32) -> VsOut {
+ var out : VsOut;
+ let x = f32((i << 1u) & 2u);
+ let y = f32(i & 2u);
+ out.uv = vec2f(x, y);
+ out.pos = vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
+ return out;
+}
+
+fn sdRoundBox(p : vec2f, half : vec2f, r : f32) -> f32 {
+ let rr = min(r, min(half.x, half.y));
+ let q = abs(p) - half + vec2f(rr);
+ return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - rr;
+}
+fn cover(d : f32) -> f32 { return clamp(0.5 - d, 0.0, 1.0); }
+fn over(dst : vec3f, src : vec3f, a : f32) -> vec3f { return mix(dst, src, clamp(a, 0.0, 1.0)); }
+
+// ---- background: computed gradient ----
+fn gradient(uv : vec2f) -> vec3f {
+ let a = vec3f(0.06, 0.11, 0.24);
+ let b = vec3f(0.35, 0.12, 0.42);
+ let c = vec3f(0.02, 0.35, 0.38);
+ let w = 0.5 + 0.5 * sin(uv.x * 2.0);
+ return mix(mix(a, b, uv.y), c, w * 0.45);
+}
+
+// ---- shadow: analytic Gaussian (erf), same as web ----
+const SQRT_2PI = 2.5066282746310002;
+const INV_SQRT_2 = 0.7071067811865476;
+fn gauss1(x : f32, sigma : f32) -> f32 { return exp(-(x * x) / (2.0 * sigma * sigma)) / (SQRT_2PI * sigma); }
+fn erf2(x : vec2f) -> vec2f {
+ let s = sign(x); let a = abs(x);
+ var r = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
+ r = r * r; return s - s / (r * r);
+}
+fn shadowRowX(x : f32, y : f32, sigma : f32, corner : f32, half : vec2f) -> f32 {
+ let d = min(half.y - corner - abs(y), 0.0);
+ let curved = half.x - corner + sqrt(max(0.0, corner * corner - d * d));
+ let integral = 0.5 + 0.5 * erf2((x + vec2f(-curved, curved)) * (INV_SQRT_2 / sigma));
+ return integral.y - integral.x;
+}
+fn shadowAt(px : vec2f, rect : vec4f, radius : f32, intensity : f32) -> f32 {
+ if (intensity <= 0.0) { return 0.0; }
+ let sigma = max(u.fx.w, 0.5);
+ let half = rect.zw * 0.5;
+ let corner = min(radius, min(half.x, half.y));
+ let p = px - (rect.xy + half + vec2f(0.0, u.fx.z));
+ let low = p.y - half.y; let high = p.y + half.y;
+ let start = clamp(-3.0 * sigma, low, high);
+ let end = clamp(3.0 * sigma, low, high);
+ let step = (end - start) / 4.0;
+ var y = start + step * 0.5; var value = 0.0;
+ for (var i = 0; i < 4; i = i + 1) {
+ value = value + shadowRowX(p.x, p.y - y, sigma, corner, half) * gauss1(y, sigma) * step;
+ y = y + step;
+ }
+ return clamp(value, 0.0, 1.0) * intensity;
+}
+
+// ---- sources ----
+fn sampleScreen(px : vec2f, blur : vec2f) -> vec3f {
+ let uv0 = (px - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
+ if (length(blur) < 0.5) {
+ return textureSampleLevel(screenTex, samp, clamp(uv0, vec2f(0.0), vec2f(1.0)), 0.0).rgb;
+ }
+ var acc = vec3f(0.0); let taps = 7;
+ for (var i = 0; i < taps; i = i + 1) {
+ let t = (f32(i) / f32(taps - 1)) - 0.5;
+ let uv = ((px + blur * t) - u.screen.xy) / max(u.screen.zw, vec2f(1.0));
+ acc = acc + textureSampleLevel(screenTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).rgb;
+ }
+ return acc / f32(taps);
+}
+fn sampleWebcam(px : vec2f, centre : vec2f) -> vec3f {
+ var uv = (px - centre) / max(u.webcam.zw, vec2f(1.0));
+ uv = uv * vec2f(u.b.z, 1.0) + vec2f(0.5);
+ return textureSampleLevel(webcamTex, samp, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).rgb;
+}
+
+// ---- cursor: arrow polygon SDF ----
+fn sdCursor(p : vec2f) -> f32 {
+ var v = array<vec2f, 7>(
+ vec2f(0.00, 0.00), vec2f(0.00, 1.00), vec2f(0.24, 0.76),
+ vec2f(0.40, 1.14), vec2f(0.56, 1.07), vec2f(0.39, 0.69), vec2f(0.70, 0.69),
+ );
+ var d = dot(p - v[0], p - v[0]); var s = 1.0;
+ for (var i = 0; i < 7; i = i + 1) {
+ let j = (i + 6) % 7;
+ let e = v[j] - v[i]; let w = p - v[i];
+ let b = w - e * clamp(dot(w, e) / dot(e, e), 0.0, 1.0);
+ d = min(d, dot(b, b));
+ let c0 = p.y >= v[i].y; let c1 = p.y < v[j].y; let c2 = e.x * w.y > e.y * w.x;
+ if ((c0 && c1 && c2) || (!c0 && !c1 && !c2)) { s = -s; }
+ }
+ return s * sqrt(d);
+}
+fn cursorFill(px : vec2f, shrink : f32) -> f32 {
+ let s = u.cursor.z / 1.2;
+ let local = (px - u.cursor.xy) / max(s, 1.0) / u.cursorFx.z;
+ return cover((sdCursor(local) * s * u.cursorFx.z) - shrink);
+}
+
+@fragment
+fn fs(in : VsOut) -> @location(0) vec4f {
+ let px = in.uv * u.a.xy;
+
+ // 1. background
+ var colour = gradient(in.uv);
+
+ // 2. screen shadow (analytic Gaussian)
+ colour = over(colour, vec3f(0.0), shadowAt(px, u.screen, u.a.w, u.fx.x));
+
+ // 3. screen (zoom + motion blur + rounded mask)
+ let sc = cover(sdRoundBox(px - (u.screen.xy + u.screen.zw * 0.5), u.screen.zw * 0.5, u.a.w));
+ if (sc > 0.0) { colour = over(colour, sampleScreen(px, u.mb.xy), sc); }
+
+ // 4. webcam shadow + webcam (shape morphs via radius)
+ colour = over(colour, vec3f(0.0), shadowAt(px, u.webcam, u.b.x, u.fx.x * 0.8));
+ let centre = u.webcam.xy + u.webcam.zw * 0.5;
+ let wc = cover(sdRoundBox(px - centre, u.webcam.zw * 0.5, u.b.x));
+ if (wc > 0.0) { colour = over(colour, sampleWebcam(px, centre), wc); }
+
+ // 5. cursor: white fill + black rim, motion-blurred, click-bounced
+ let outline = max(u.cursor.z * 0.05, 1.5);
+ let fill = cursorFill(px, 0.0);
+ let edge = cursorFill(px, outline);
+ if (edge > 0.001) {
+ let rgb = vec3f(fill / max(edge, 1e-4));
+ colour = over(colour, rgb, edge * u.cursor.w);
+ }
+
+ return vec4f(colour, 1.0);
+}
diff --git a/poc-native/src/main.rs b/poc-native/src/main.rs
new file mode 100644
index 000000000..04979ba6a
--- /dev/null
+++ b/poc-native/src/main.rs
@@ -0,0 +1,295 @@
+// Native full-shader compositor POC — milestone 1: prove wgpu runs the WGSL and
+// composites a real frame, natively, no browser.
+//
+// Decode one real frame from each source with ffmpeg (to raw RGBA), upload as
+// wgpu textures, run the SAME shader as the web POC (adapted for native), render
+// to an offscreen 1080p target, read it back, write a BMP. If the picture matches
+// the web POC at the same t, the compositor has moved to native unchanged.
+
+use std::fs;
+use std::process::Command;
+
+const OUT_W: u32 = 1920;
+const OUT_H: u32 = 1080;
+const SCREEN_W: u32 = 1920;
+const SCREEN_H: u32 = 1032;
+const WEBCAM_W: u32 = 640;
+const WEBCAM_H: u32 = 480;
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct Uniforms {
+ a: [f32; 4],
+ screen: [f32; 4],
+ webcam: [f32; 4],
+ fx: [f32; 4],
+ b: [f32; 4],
+ mb: [f32; 4],
+ cursor: [f32; 4],
+ cursor_fx: [f32; 4],
+}
+
+struct Rect {
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+}
+
+// evaluate(), ported from the web POC. At t=0.5s: no zoom (starts 1.0), no layout
+// move (starts 2.4), so the recording sits padded and the webcam is a docked
+// circle — the frame where background + shadow + rounded corners are all visible.
+fn base_layout(padding: f32) -> (Rect, Rect) {
+ let s = 1.0 - (padding / 100.0) * 0.4;
+ let w = OUT_W as f32 * s;
+ let h = OUT_H as f32 * s;
+ let screen = Rect {
+ x: (OUT_W as f32 - w) / 2.0,
+ y: (OUT_H as f32 - h) / 2.0,
+ w,
+ h,
+ };
+ let size = (OUT_H as f32 * 0.22).round();
+ let margin = (OUT_H as f32 * 0.04).round();
+ let webcam = Rect {
+ x: OUT_W as f32 - size - margin,
+ y: OUT_H as f32 - size - margin,
+ w: size,
+ h: size,
+ };
+ (screen, webcam)
+}
+
+fn decode_frame(path: &str, t: &str, w: u32, h: u32, out: &str) -> Vec<u8> {
+ // One real frame → raw RGBA. ffmpeg is the native hardware/software decoder;
+ // this is the decode seam. For the compositor milestone it runs once.
+ let status = Command::new("ffmpeg")
+ .args([
+ "-hide_banner", "-loglevel", "error", "-y", "-ss", t, "-i", path, "-frames:v", "1",
+ "-f", "rawvideo", "-pix_fmt", "rgba", out,
+ ])
+ .status()
+ .expect("ffmpeg failed to run");
+ assert!(status.success(), "ffmpeg decode failed for {path}");
+ let data = fs::read(out).expect("read decoded frame");
+ assert_eq!(data.len(), (w * h * 4) as usize, "unexpected frame size for {path}");
+ data
+}
+
+fn make_texture(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ w: u32,
+ h: u32,
+ rgba: &[u8],
+ label: &str,
+) -> wgpu::TextureView {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &tex,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ rgba,
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(w * 4),
+ rows_per_image: Some(h),
+ },
+ wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
+ );
+ tex.create_view(&wgpu::TextureViewDescriptor::default())
+}
+
+fn write_bmp(path: &str, w: u32, h: u32, rgba: &[u8]) {
+ // 24-bit BMP, bottom-up. No image crate: keeps the native POC's deps to wgpu.
+ let row = (w * 3 + 3) & !3; // 4-byte aligned
+ let size = 54 + row * h;
+ let mut f = Vec::with_capacity(size as usize);
+ f.extend_from_slice(b"BM");
+ f.extend_from_slice(&size.to_le_bytes());
+ f.extend_from_slice(&0u32.to_le_bytes());
+ f.extend_from_slice(&54u32.to_le_bytes());
+ f.extend_from_slice(&40u32.to_le_bytes());
+ f.extend_from_slice(&(w as i32).to_le_bytes());
+ f.extend_from_slice(&(h as i32).to_le_bytes());
+ f.extend_from_slice(&1u16.to_le_bytes());
+ f.extend_from_slice(&24u16.to_le_bytes());
+ f.extend_from_slice(&[0u8; 24]);
+ for y in (0..h).rev() {
+ let mut written = 0u32;
+ for x in 0..w {
+ let i = ((y * w + x) * 4) as usize;
+ f.push(rgba[i + 2]);
+ f.push(rgba[i + 1]);
+ f.push(rgba[i]);
+ written += 3;
+ }
+ while written < row {
+ f.push(0);
+ written += 1;
+ }
+ }
+ fs::write(path, f).expect("write bmp");
+}
+
+fn main() {
+ let t = 0.5f32;
+ let padding = 45.0f32;
+
+ // --- decode one real frame from each source ---
+ let screen_rgba = decode_frame("../poc/media/screen.mp4", "0.5", SCREEN_W, SCREEN_H, "screen.rgba");
+ let webcam_rgba = decode_frame("../poc/media/webcam.mp4", "0.5", WEBCAM_W, WEBCAM_H, "webcam.rgba");
+
+ // --- wgpu init (native: Vulkan/D3D12/Metal under the hood) ---
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ ..Default::default()
+ }))
+ .expect("no GPU adapter");
+ let info = adapter.get_info();
+ println!("native gpu: {} ({:?}, backend {:?})", info.name, info.device_type, info.backend);
+ let (device, queue) = pollster::block_on(adapter.request_device(
+ &wgpu::DeviceDescriptor { label: None, required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::default(), memory_hints: wgpu::MemoryHints::Performance },
+ None,
+ ))
+ .expect("no device");
+
+ let screen_view = make_texture(&device, &queue, SCREEN_W, SCREEN_H, &screen_rgba, "screen");
+ let webcam_view = make_texture(&device, &queue, WEBCAM_W, WEBCAM_H, &webcam_rgba, "webcam");
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+
+ // --- uniforms: evaluate() at t=0.5 ---
+ let (screen, webcam) = base_layout(padding);
+ let cam_aspect = WEBCAM_W as f32 / WEBCAM_H as f32;
+ let cur_x = screen.x + 0.52 * screen.w;
+ let cur_y = screen.y + 0.90 * screen.h;
+ let cur_size = OUT_H as f32 * 0.05;
+ let uniforms = Uniforms {
+ a: [OUT_W as f32, OUT_H as f32, t, 28.0],
+ screen: [screen.x, screen.y, screen.w, screen.h],
+ webcam: [webcam.x, webcam.y, webcam.w, webcam.h],
+ fx: [0.7, 0.0, 16.0, 22.0],
+ b: [webcam.w.min(webcam.h) / 2.0, 0.0, cam_aspect, 0.0],
+ mb: [0.0, 0.0, 0.0, 0.0],
+ cursor: [cur_x, cur_y, cur_size, 1.0],
+ cursor_fx: [0.0, 0.0, 1.0, 0.0],
+ };
+ let ubuf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("uniforms"),
+ size: std::mem::size_of::<Uniforms>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uniforms));
+
+ // --- pipeline ---
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("composite"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("composite.wgsl").into()),
+ });
+ let format = wgpu::TextureFormat::Rgba8Unorm;
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("composite"),
+ layout: None,
+ vertex: wgpu::VertexState { module: &shader, entry_point: "vs", buffers: &[], compilation_options: Default::default() },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs",
+ targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
+ let target = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("target"),
+ size: wgpu::Extent3d { width: OUT_W, height: OUT_H, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
+
+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &pipeline.get_bind_group_layout(0),
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: ubuf.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler) },
+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&screen_view) },
+ wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&webcam_view) },
+ ],
+ });
+
+ // --- render ---
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
+ {
+ let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &target_view,
+ resolve_target: None,
+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bind, &[]);
+ pass.draw(0..3, 0..1);
+ }
+
+ // --- readback → BMP ---
+ let bpr = ((OUT_W * 4 + 255) & !255) as u64; // 256-aligned
+ let rbuf = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("readback"),
+ size: bpr * OUT_H as u64,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ enc.copy_texture_to_buffer(
+ wgpu::ImageCopyTexture { texture: &target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
+ wgpu::ImageCopyBuffer { buffer: &rbuf, layout: wgpu::ImageDataLayout { offset: 0, bytes_per_row: Some(bpr as u32), rows_per_image: Some(OUT_H) } },
+ wgpu::Extent3d { width: OUT_W, height: OUT_H, depth_or_array_layers: 1 },
+ );
+ queue.submit([enc.finish()]);
+
+ let slice = rbuf.slice(..);
+ slice.map_async(wgpu::MapMode::Read, |r| r.unwrap());
+ device.poll(wgpu::Maintain::Wait);
+ let mapped = slice.get_mapped_range();
+ // Un-pad the 256-aligned rows into tight RGBA.
+ let mut tight = vec![0u8; (OUT_W * OUT_H * 4) as usize];
+ for y in 0..OUT_H {
+ let src = (y as u64 * bpr) as usize;
+ let dst = (y * OUT_W * 4) as usize;
+ tight[dst..dst + (OUT_W * 4) as usize].copy_from_slice(&mapped[src..src + (OUT_W * 4) as usize]);
+ }
+ write_bmp("out.bmp", OUT_W, OUT_H, &tight);
+ println!("wrote out.bmp — composited natively at t={t}s");
+}