Composite grouped/nested video on the GPU path

Imported video is a Group[Video, Audio] that rendered as a Vello-baked
Vector layer, re-uploading the full frame to Vello's image atlas every
frame (~17ms/frame at 1080p, hitting playback and export alike). Extract
video frames out of the Group/clip scene recursion into
VideoRenderInstances so they composite via the GPU Video path; mixed
video+vector containers fall back to Vello (correct, unaccelerated).

Also route video through hardware sRGB decode: upload raw sRGB bytes to an
Rgba8UnormSrgb texture and blit with a non-unpremultiplying shader variant
(blit_straight), removing the per-frame per-pixel CPU sRGB->linear pass.
Add an F3 GPU-timestamp timer and a per-frame video texture cache.

Drops the live composite of a 1080p video from ~17ms to ~2-3ms.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Skyler Lehmkuhl
2026-06-22 17:38:30 -04:00
co-authored by Claude Opus 4.8
parent ce151ffd61
commit 5844a0f070
8 changed files with 637 additions and 86 deletions
@@ -75,3 +75,25 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let tinted = base + tint - base * tint;
return vec4<f32>(tinted, masked_a);
}
// Variant for sources that are ALREADY straight-alpha linear — notably a video
// frame uploaded to an `Rgba8UnormSrgb` texture, where the hardware decodes
// sRGB→linear on sample and leaves alpha untouched. No unpremultiply (the source
// was never premultiplied), so we skip the divide entirely. The compositor wants
// straight-alpha linear, which is exactly what the sample already is.
@fragment
fn fs_main_straight(in: VertexOutput) -> @location(0) vec4<f32> {
let m = mat3x3<f32>(transform.col0.xyz, transform.col1.xyz, transform.col2.xyz);
let canvas_uv = (m * vec3<f32>(in.uv.x, in.uv.y, 1.0)).xy;
if canvas_uv.x < 0.0 || canvas_uv.x > 1.0
|| canvas_uv.y < 0.0 || canvas_uv.y > 1.0 {
return vec4<f32>(0.0, 0.0, 0.0, 0.0);
}
let c = textureSample(canvas_tex, canvas_sampler, canvas_uv);
let mask = textureSample(mask_tex, mask_sampler, canvas_uv).r;
let tint = vec3<f32>(transform.col0.w, transform.col1.w, transform.col2.w);
let tinted = c.rgb + tint - c.rgb * tint;
return vec4<f32>(tinted, c.a * mask);
}
@@ -45,6 +45,89 @@ fn upload_pixmap_to_texture(queue: &wgpu::Queue, texture: &wgpu::Texture, pixmap
/// Set to true to use the new pipeline, false for legacy single-scene rendering
const USE_HDR_COMPOSITING: bool = true; // Enabled for testing
/// Caches GPU textures for decoded video frames, keyed by the frame buffer's `Arc`
/// identity. A static/paused video then costs ~nothing per repaint (cache hit → no
/// per-pixel CPU sRGB→linear conversion, no texture allocation, no upload). The
/// cached texture holds premultiplied-linear RGBA8 — exactly what `canvas_blit`
/// expects. During playback each new decoded frame is a fresh `Arc` → one
/// conversion+upload per frame (not per repaint).
struct CachedVideoFrame {
/// Keep the source buffer alive so its pointer (our cache key) can't be reused.
_keep: std::sync::Arc<Vec<u8>>,
texture: wgpu::Texture,
last_seen: u64,
}
struct VideoFrameTexCache {
entries: std::collections::HashMap<usize, CachedVideoFrame>,
frame: u64,
}
impl VideoFrameTexCache {
fn new() -> Self {
Self { entries: std::collections::HashMap::new(), frame: 0 }
}
fn begin_frame(&mut self) {
self.frame = self.frame.wrapping_add(1);
}
/// View of the cached (or freshly converted+uploaded) texture for `rgba`.
fn texture_view(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
rgba: &std::sync::Arc<Vec<u8>>,
w: u32,
h: u32,
) -> wgpu::TextureView {
let key = std::sync::Arc::as_ptr(rgba) as usize;
let frame = self.frame;
if let Some(e) = self.entries.get_mut(&key) {
e.last_seen = frame;
return e.texture.create_view(&wgpu::TextureViewDescriptor::default());
}
// Miss: upload the raw sRGB straight-alpha bytes verbatim into an sRGB
// texture. The GPU decodes sRGB→linear on sample (free), so there is no
// per-pixel CPU conversion — the cost that used to dominate playback/export.
// Blit this with `blit_straight` (it must NOT unpremultiply).
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("video_frame_tex"),
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::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
rgba,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(w * 4),
rows_per_image: Some(h),
},
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.entries.insert(key, CachedVideoFrame { _keep: rgba.clone(), texture, last_seen: frame });
view
}
/// Drop textures not used in the last couple of frames (bounds VRAM).
fn evict_stale(&mut self) {
let frame = self.frame;
self.entries.retain(|_, e| e.last_seen + 2 >= frame);
}
}
/// Shared Vello resources (created once, reused by all Stage panes)
struct SharedVelloResources {
renderer: Arc<Mutex<vello::Renderer>>,
@@ -72,6 +155,11 @@ struct SharedVelloResources {
/// True when Vello is running its CPU software renderer (either forced or GPU fallback).
/// Used to select cheaper antialiasing — Msaa16 on CPU costs 16× as much as Area.
is_cpu_renderer: bool,
/// GPU timestamp timer for the composite section (F3 debug). Lazily created on
/// the first frame (needs the device/queue); `None` if unsupported.
gpu_timer: Mutex<Option<crate::gpu_timer::FrameGpuTimer>>,
/// Per-frame video texture cache (skips re-converting/uploading a static frame).
video_frame_cache: Mutex<VideoFrameTexCache>,
}
/// Per-instance Vello resources (created for each Stage pane)
@@ -302,6 +390,8 @@ impl SharedVelloResources {
gpu_brush: Mutex::new(gpu_brush),
canvas_blit,
is_cpu_renderer: use_cpu || is_cpu_renderer,
gpu_timer: Mutex::new(None),
video_frame_cache: Mutex::new(VideoFrameTexCache::new()),
})
}
}
@@ -1079,6 +1169,25 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// HDR buffer spec for linear buffers
let hdr_spec = BufferSpec::new(width, height, BufferFormat::Rgba16Float);
// F3: bracket the composite section with a GPU timestamp (lazily create the
// timer; no-op when the adapter lacks timestamp support).
let ts_supported = device
.features()
.contains(crate::gpu_timer::FrameGpuTimer::required_features());
{
let mut tg = shared.gpu_timer.lock().unwrap();
if tg.is_none() && ts_supported {
*tg = crate::gpu_timer::FrameGpuTimer::new(device, queue);
}
if let Some(t) = tg.as_ref() {
t.start(device, queue);
}
}
shared.video_frame_cache.lock().unwrap().begin_frame();
// F3: CPU breakdown of the composite (the GPU idles waiting on these).
let mut cput = crate::debug_overlay::CompositeCpuBreakdown::default();
// First, render background and composite it
// The background scene contains only a rectangle at document bounds,
// so we use TRANSPARENT base_color to not fill the whole viewport
@@ -1097,6 +1206,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
antialiasing_method: aa_method,
};
let _t = std::time::Instant::now();
if let Some(pixmap) = &composite_result.background_cpu {
if let Some(tex) = buffer_pool.get_texture(bg_srgb_handle) {
upload_pixmap_to_texture(queue, tex, pixmap);
@@ -1104,13 +1214,18 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
} else if let Ok(mut renderer) = shared.renderer.lock() {
renderer.render_to_texture(device, queue, &composite_result.background, bg_srgb_view, &bg_render_params).ok();
}
cput.vello_ms += _t.elapsed().as_secs_f64() * 1000.0;
// Convert sRGB to linear HDR
let mut convert_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("bg_srgb_to_linear_encoder"),
});
let _t = std::time::Instant::now();
shared.srgb_to_linear.convert(device, &mut convert_encoder, bg_srgb_view, bg_hdr_view);
cput.convert_ms += _t.elapsed().as_secs_f64() * 1000.0;
let _t = std::time::Instant::now();
queue.submit(Some(convert_encoder.finish()));
cput.submit_ms += _t.elapsed().as_secs_f64() * 1000.0;
// Composite background onto HDR texture (first layer, clears to dark gray for stage area)
let bg_compositor_layer = lightningbeam_core::gpu::CompositorLayer::normal(bg_hdr_handle, 1.0);
@@ -1120,6 +1235,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
// Clear to dark gray (stage background outside document bounds)
// Note: stage_bg values are already in linear space for HDR compositing
let stage_bg = [45.0 / 255.0, 45.0 / 255.0, 48.0 / 255.0, 1.0];
let _t = std::time::Instant::now();
shared.compositor.composite(
device,
queue,
@@ -1129,7 +1245,10 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
hdr_view,
Some(stage_bg),
);
cput.composite_ms += _t.elapsed().as_secs_f64() * 1000.0;
let _t = std::time::Instant::now();
queue.submit(Some(encoder.finish()));
cput.submit_ms += _t.elapsed().as_secs_f64() * 1000.0;
}
buffer_pool.release(bg_srgb_handle);
buffer_pool.release(bg_hdr_handle);
@@ -1351,6 +1470,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
buffer_pool.get_view(hdr_layer_handle),
&instance_resources.hdr_texture_view,
) {
let _t_vello = std::time::Instant::now();
if let Some(pixmap) = &rendered_layer.cpu_pixmap {
if let Some(tex) = buffer_pool.get_texture(srgb_handle) {
upload_pixmap_to_texture(queue, tex, pixmap);
@@ -1358,6 +1478,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
} else if let Ok(mut renderer) = shared.renderer.lock() {
renderer.render_to_texture(device, queue, &rendered_layer.scene, srgb_view, &layer_render_params).ok();
}
cput.vello_ms += _t_vello.elapsed().as_secs_f64() * 1000.0;
let mut convert_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("layer_srgb_to_linear_encoder"),
});
@@ -1555,7 +1676,7 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
}
}
RenderedLayerType::Video { instances } => {
// Video layer — per-instance: upload decoded frame → blit → composite.
// Video layer — per-instance: (cached) frame texture → blit → composite.
for inst in instances {
if inst.rgba_data.is_empty() { continue; }
let hdr_layer_handle = buffer_pool.acquire(device, hdr_spec);
@@ -1563,40 +1684,20 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
buffer_pool.get_view(hdr_layer_handle),
&instance_resources.hdr_texture_view,
) {
// Convert sRGB straight-alpha → linear premultiplied.
let linear: Vec<u8> = inst.rgba_data.chunks_exact(4).flat_map(|p| {
let a = p[3] as f32 / 255.0;
let lin = |c: u8| -> f32 {
let f = c as f32 / 255.0;
if f <= 0.04045 { f / 12.92 } else { ((f + 0.055) / 1.055).powf(2.4) }
};
let r = (lin(p[0]) * a * 255.0 + 0.5) as u8;
let g = (lin(p[1]) * a * 255.0 + 0.5) as u8;
let b = (lin(p[2]) * a * 255.0 + 0.5) as u8;
[r, g, b, p[3]]
}).collect();
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("video_frame_tex"),
size: wgpu::Extent3d { width: inst.width, height: inst.height, 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::TexelCopyTextureInfo { texture: &tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&linear,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(inst.width * 4), rows_per_image: Some(inst.height) },
wgpu::Extent3d { width: inst.width, height: inst.height, depth_or_array_layers: 1 },
);
let tex_view = tex.create_view(&wgpu::TextureViewDescriptor::default());
// Reuse the GPU texture for this frame if it's unchanged (a
// static/paused video → no CPU conversion, alloc, or upload).
// Timed into `blit_ms` (incl the cache lookup + per-frame view).
let _t = std::time::Instant::now();
let tex_view = shared
.video_frame_cache
.lock()
.unwrap()
.texture_view(device, queue, &inst.rgba_data, inst.width, inst.height);
let bt = crate::gpu_brush::BlitTransform::new(
inst.transform, inst.width, inst.height, width, height,
);
shared.canvas_blit.blit(device, queue, &tex_view, hdr_layer_view, &bt, None);
shared.canvas_blit.blit_straight(device, queue, &tex_view, hdr_layer_view, &bt, None);
cput.blit_ms += _t.elapsed().as_secs_f64() * 1000.0;
let compositor_layer = lightningbeam_core::gpu::CompositorLayer::new(
hdr_layer_handle,
@@ -1606,10 +1707,14 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("video_composite_encoder"),
});
let _t = std::time::Instant::now();
shared.compositor.composite(
device, queue, &mut encoder, &[compositor_layer], &buffer_pool, hdr_view, None,
);
cput.composite_ms += _t.elapsed().as_secs_f64() * 1000.0;
let _t = std::time::Instant::now();
queue.submit(Some(encoder.finish()));
cput.submit_ms += _t.elapsed().as_secs_f64() * 1000.0;
}
buffer_pool.release(hdr_layer_handle);
}
@@ -1841,6 +1946,23 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
buffer_pool.next_frame();
drop(buffer_pool);
// F3: close the GPU timestamp bracket + publish the composite measurement.
{
let layers = composite_result.layers.len() as u32;
// Submits aren't counted per-site; estimate from the per-layer pattern
// (bg ~3 + ~2 per layer). Drops toward ~1 once the passes are batched.
let submits_est = 3 + 2 * layers;
let mut tg = shared.gpu_timer.lock().unwrap();
if let Some(t) = tg.as_mut() {
t.end(device, queue);
crate::debug_overlay::update_gpu_composite(true, t.last_ms(), layers, submits_est);
} else {
crate::debug_overlay::update_gpu_composite(false, 0.0, layers, submits_est);
}
}
crate::debug_overlay::update_composite_cpu(cput);
shared.video_frame_cache.lock().unwrap().evict_stale();
// --- Frame timing report ---
let _t_end = std::time::Instant::now();
let total_ms = (_t_end - _t_prepare_start).as_secs_f64() * 1000.0;