Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M4.6: GPU path converts layer texels on the frame workers, not on the UI thread

Brandon Thomas04e714510b05
diff --git a/Cargo.lock b/Cargo.lock
index f57a5227c..aca993685 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1489,6 +1489,7 @@ dependencies = [
"filmcraft-time",
"log",
"pollster 0.4.0",
+ "rayon",
"wgpu",
]
diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml
index b8bba22fe..a67452343 100644
--- a/crates/gpu/Cargo.toml
+++ b/crates/gpu/Cargo.toml
@@ -16,6 +16,7 @@ filmcraft-geom = { workspace = true }
filmcraft-render = { workspace = true }
wgpu = { version = "30", default-features = false, features = ["wgsl"] }
log = { workspace = true }
+rayon = { workspace = true }
[dev-dependencies]
pollster = "0.4"
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 83e46f795..792f8d471 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -7,11 +7,17 @@
//! registers as a native texture. Uploads are cached by pixel-buffer identity, so a paused frame or
//! a still costs nothing.
//!
+//! Layers that need converting before upload (linear f32 RGBA from CPU-rendered layers, 16-bit
+//! YUV such as ProRes) are converted to half floats by [`prepare`], which frame workers run off the
+//! UI thread; [`GpuCompositor::composite_prepared`] then only copies bytes into textures.
+//!
//! The CPU plan executor (`filmcraft_render::plan::execute_cpu`) is the oracle; tests compare.
use std::collections::HashMap;
use std::sync::Arc;
+use rayon::prelude::*;
+
use filmcraft_color::{Matrix, Range, Transfer};
use filmcraft_frame::{Chroma, PixelData, VideoFrame};
use filmcraft_render::plan::{FramePlan, PlanLayer};
@@ -88,6 +94,85 @@ pub fn f32_to_f16(v: f32) -> u16 {
h as u16
}
+/// Half-float texel data for one frame (one byte vector per plane), converted off the UI thread.
+/// 8-bit frames need no conversion and have none.
+#[derive(Clone, Debug, Default)]
+pub struct Prepared {
+ planes: Vec<Vec<u8>>,
+}
+
+impl Prepared {
+ pub fn bytes(&self) -> usize {
+ self.planes.iter().map(Vec::len).sum()
+ }
+}
+
+/// [`Prepared`] data for every layer of a plan (index-aligned with its layers), or for the
+/// fallback image of a [`FramePlan::Image`].
+#[derive(Clone, Debug, Default)]
+pub struct PreparedPlan {
+ layers: Vec<Option<Prepared>>,
+ image: Option<Prepared>,
+}
+
+impl PreparedPlan {
+ pub fn bytes(&self) -> usize {
+ self.layers.iter().flatten().chain(&self.image).map(Prepared::bytes).sum()
+ }
+}
+
+/// Values per parallel chunk when converting.
+const CHUNK: usize = 1 << 15;
+
+fn f32_to_f16_bytes(v: &[f32]) -> Vec<u8> {
+ let mut out = vec![0u8; v.len() * 2];
+ out.par_chunks_mut(CHUNK * 2).zip(v.par_chunks(CHUNK)).for_each(|(o, s)| {
+ for (o, x) in o.chunks_exact_mut(2).zip(s) {
+ o.copy_from_slice(&f32_to_f16(*x).to_le_bytes());
+ }
+ });
+ out
+}
+
+/// Half floats of `code / 2^bits` for every 16-bit code (built once per bit depth).
+fn code_table(bits: u32) -> &'static [[u8; 2]] {
+ static TABLES: [std::sync::OnceLock<Vec<[u8; 2]>>; 17] = [const { std::sync::OnceLock::new() }; 17];
+ let bits = bits.min(16);
+ TABLES[bits as usize].get_or_init(|| {
+ let scale = (1u32 << bits) as f32;
+ (0..=u16::MAX as u32).map(|c| f32_to_f16(c as f32 / scale).to_le_bytes()).collect()
+ })
+}
+
+/// `code / 2^bits` as half floats, through a per-code table (same values as converting each sample).
+fn codes_to_f16_bytes(v: &[u16], bits: u32) -> Vec<u8> {
+ let table = code_table(bits);
+ let mut out = vec![0u8; v.len() * 2];
+ out.par_chunks_mut(CHUNK * 2).zip(v.par_chunks(CHUNK)).for_each(|(o, s)| {
+ for (o, c) in o.chunks_exact_mut(2).zip(s) {
+ o.copy_from_slice(&table[*c as usize]);
+ }
+ });
+ out
+}
+
+/// Convert a frame's texels for upload (None when it uploads as it is).
+pub fn prepare_frame(f: &VideoFrame) -> Option<Prepared> {
+ match &f.data {
+ PixelData::RgbaF32(d) => Some(Prepared { planes: vec![f32_to_f16_bytes(d)] }),
+ PixelData::Yuv16 { planes, bits, .. } => Some(Prepared { planes: planes.iter().map(|p| codes_to_f16_bytes(p, *bits)).collect() }),
+ PixelData::Rgba8(_) | PixelData::Yuv8 { .. } => None,
+ }
+}
+
+/// Convert every layer of a plan for upload. Thread-safe and GPU-free: run it on a worker.
+pub fn prepare(plan: &FramePlan) -> PreparedPlan {
+ match plan {
+ FramePlan::Layers { layers, .. } => PreparedPlan { layers: layers.iter().map(|l| prepare_frame(&l.frame)).collect(), image: None },
+ FramePlan::Image(img) => PreparedPlan { layers: Vec::new(), image: Some(Prepared { planes: vec![f32_to_f16_bytes(&img.px)] }) },
+ }
+}
+
impl GpuCompositor {
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
@@ -225,8 +310,8 @@ impl GpuCompositor {
t.create_view(&Default::default())
}
- /// Upload (or reuse) the textures of a frame.
- fn upload(&mut self, f: &VideoFrame) -> (usize, u32, u32) {
+ /// Upload (or reuse) the textures of a frame, using `prep` when it was converted beforehand.
+ fn upload(&mut self, f: &VideoFrame, prep: Option<&Prepared>) -> (usize, u32, u32) {
let id = match &f.data {
PixelData::Rgba8(d) => Arc::as_ptr(d) as *const u8 as usize,
PixelData::RgbaF32(d) => Arc::as_ptr(d) as *const u8 as usize,
@@ -248,8 +333,15 @@ impl GpuCompositor {
Uploaded { views: [v, dummy(), dummy()], kind: 0, code_scale: 1.0, chroma: (w, h), last_used: self.clock }
}
PixelData::RgbaF32(d) => {
- let half: Vec<u8> = d.iter().flat_map(|v| f32_to_f16(*v).to_le_bytes()).collect();
- let v = self.plane_texture(w, h, wgpu::TextureFormat::Rgba16Float, &half, 8);
+ let owned;
+ let half = match prep {
+ Some(p) => &p.planes[0],
+ None => {
+ owned = f32_to_f16_bytes(d);
+ &owned
+ }
+ };
+ let v = self.plane_texture(w, h, wgpu::TextureFormat::Rgba16Float, half, 8);
Uploaded { views: [v, dummy(), dummy()], kind: 1, code_scale: 1.0, chroma: (w, h), last_used: self.clock }
}
PixelData::Yuv8 { planes, chroma, .. } => {
@@ -264,11 +356,17 @@ impl GpuCompositor {
let (sx, sy) = chroma.shifts();
let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy));
let scale = (1u32 << bits) as f32;
- let conv = |p: &[u16]| -> Vec<u8> { p.iter().flat_map(|v| f32_to_f16(*v as f32 / scale).to_le_bytes()).collect() };
- let (py, pu, pv) = (conv(&planes[0]), conv(&planes[1]), conv(&planes[2]));
- let y = self.plane_texture(w, h, wgpu::TextureFormat::R16Float, &py, 2);
- let u = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &pu, 2);
- let v = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &pv, 2);
+ let owned;
+ let p = match prep {
+ Some(p) => p,
+ None => {
+ owned = Prepared { planes: planes.iter().map(|p| codes_to_f16_bytes(p, *bits)).collect() };
+ &owned
+ }
+ };
+ let y = self.plane_texture(w, h, wgpu::TextureFormat::R16Float, &p.planes[0], 2);
+ let u = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &p.planes[1], 2);
+ let v = self.plane_texture(cw, ch, wgpu::TextureFormat::R16Float, &p.planes[2], 2);
let _ = Chroma::C420;
Uploaded { views: [y, u, v], kind: 2, code_scale: scale, chroma: (cw, ch), last_used: self.clock }
}
@@ -338,22 +436,41 @@ impl GpuCompositor {
/// Composite a plan; returns the output view (sRGB, over black) and its size.
pub fn composite(&mut self, plan: &FramePlan) -> (&wgpu::TextureView, (u32, u32)) {
+ self.composite_prepared(plan, None)
+ }
+
+ /// [`composite`](Self::composite) with texel conversions already done by [`prepare`] (the
+ /// result is identical; only the upload work on this thread differs).
+ pub fn composite_prepared(&mut self, plan: &FramePlan, prep: Option<&PreparedPlan>) -> (&wgpu::TextureView, (u32, u32)) {
let owned;
let (w, h, layers): (u32, u32, &[PlanLayer]) = match plan {
FramePlan::Layers { width, height, layers } => (*width as u32, *height as u32, layers.as_slice()),
FramePlan::Image(img) => {
- owned = [PlanLayer {
- frame: Arc::new(VideoFrame::rgba_f32(img.w as u32, img.h as u32, img.px.clone())),
- matrix: filmcraft_geom::Affine::IDENTITY,
- opacity: 1.0,
- }];
+ let frame = match prep.and_then(|p| p.image.as_ref()) {
+ // The texels come from `prep`; the frame only carries size and colour.
+ Some(_) => VideoFrame {
+ width: img.w as u32,
+ height: img.h as u32,
+ data: PixelData::RgbaF32(Arc::new(Vec::new())),
+ ..VideoFrame::rgba_f32(1, 1, vec![0.0; 4])
+ },
+ None => VideoFrame::rgba_f32(img.w as u32, img.h as u32, img.px.clone()),
+ };
+ owned = [PlanLayer { frame: Arc::new(frame), matrix: filmcraft_geom::Affine::IDENTITY, opacity: 1.0 }];
(img.w as u32, img.h as u32, &owned[..])
}
};
let (w, h) = (w.max(1), h.max(1));
Self::target(&self.device, &mut self.accum, w, h, ACCUM_FORMAT, wgpu::TextureUsages::empty());
Self::target(&self.device, &mut self.output, w, h, OUTPUT_FORMAT, wgpu::TextureUsages::COPY_SRC);
- let keys: Vec<(usize, u32, u32)> = layers.iter().map(|l| self.upload(&l.frame)).collect();
+ let keys: Vec<(usize, u32, u32)> = layers
+ .iter()
+ .enumerate()
+ .map(|(i, l)| {
+ let p = prep.and_then(|p| if matches!(plan, FramePlan::Image(_)) { p.image.as_ref() } else { p.layers.get(i).and_then(Option::as_ref) });
+ self.upload(&l.frame, p)
+ })
+ .collect();
let mut bind_groups = Vec::with_capacity(layers.len());
for (l, k) in layers.iter().zip(&keys) {
let u = self.uniforms(l, *k, (w, h));
diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs
index 9aacbde97..f0013da4a 100644
--- a/crates/gpu/src/tests.rs
+++ b/crates/gpu/src/tests.rs
@@ -77,3 +77,51 @@ fn half_float_conversion() {
assert!((d - v).abs() <= v.abs() * 1e-3 + 1e-6, "{v} → {d}");
}
}
+
+#[test]
+fn prepared_upload_matches_inline_conversion() {
+ let Some((dev, q)) = device() else {
+ eprintln!("no GPU adapter; skipping");
+ return;
+ };
+ let (w, h) = (64u32, 36u32);
+ let yuv16 = Arc::new(VideoFrame {
+ width: w,
+ height: h,
+ data: PixelData::Yuv16 {
+ planes: [
+ Arc::new((0..w * h).map(|i| (64 + (i * 7) % 876) as u16).collect()),
+ Arc::new((0..w * h / 2).map(|i| (64 + (i * 13) % 896) as u16).collect()),
+ Arc::new((0..w * h / 2).map(|i| (960 - (i * 5) % 896) as u16).collect()),
+ ],
+ chroma: Chroma::C422,
+ bits: 10,
+ alpha: None,
+ },
+ color: filmcraft_color::ColorInfo::REC709,
+ par: (1, 1),
+ pts: Default::default(),
+ });
+ let f32_layer: Vec<f32> = (0..w * h * 4).map(|i| ((i * 37) % 1000) as f32 / 1000.0 * if i % 4 == 3 { 1.0 } else { 0.6 }).collect();
+ let rgbaf = Arc::new(VideoFrame::rgba_f32(w, h, f32_layer.clone()));
+ let layers = FramePlan::Layers {
+ width: w as usize,
+ height: h as usize,
+ layers: vec![
+ PlanLayer { frame: yuv16, matrix: Affine::IDENTITY, opacity: 1.0 },
+ PlanLayer { frame: rgbaf, matrix: Affine::scale(0.5, 0.5), opacity: 0.8 },
+ ],
+ };
+ let image = FramePlan::Image(filmcraft_render::Image { w: w as usize, h: h as usize, px: f32_layer });
+ for plan in [layers, image] {
+ let mut a = GpuCompositor::new(&dev, &q);
+ a.composite(&plan);
+ let inline = a.read_output().expect("readback");
+ let mut b = GpuCompositor::new(&dev, &q);
+ let prep = prepare(&plan);
+ assert!(prep.bytes() > 0);
+ b.composite_prepared(&plan, Some(&prep));
+ let prepared = b.read_output().expect("readback");
+ assert!(inline == prepared, "prepared upload differs");
+ }
+}
diff --git a/crates/ui-egui/examples/bench_playback.rs b/crates/ui-egui/examples/bench_playback.rs
index cbeb73dcb..26379b2b8 100644
--- a/crates/ui-egui/examples/bench_playback.rs
+++ b/crates/ui-egui/examples/bench_playback.rs
@@ -177,7 +177,7 @@ impl Display {
&& self.last != Some(k)
{
let before = comp.uploaded_bytes;
- let _ = comp.composite(&plan);
+ let _ = comp.composite_prepared(&plan.plan, Some(&plan.prepared));
// Wait for the GPU so the time includes the upload and the draw.
let _ = dev.poll(eframe::wgpu::PollType::wait_indefinitely());
self.uploaded += comp.uploaded_bytes - before;
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs
index 7d9ff912c..46dbdbe7f 100644
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@ -61,7 +61,7 @@ struct Shared {
queue: Mutex<VecDeque<Job>>,
cv: Condvar,
done: Mutex<Cache>,
- plans: Mutex<HashMap<FrameKey, (Arc<filmcraft_render::plan::FramePlan>, u64)>>,
+ plans: Mutex<PlanCache>,
/// Running jobs: key, cancel flag, prefetch.
in_flight: Mutex<Vec<(FrameKey, Arc<std::sync::atomic::AtomicBool>, bool)>>,
/// Per-job timings, collected while profiling is on (benchmarks, `ui.inspect`).
@@ -160,6 +160,65 @@ impl filmcraft_render::SourceProvider for JobProvider {
}
}
+/// A GPU frame plan with its layers' texel conversions already done (off the UI thread).
+pub struct GpuPlan {
+ pub plan: filmcraft_render::plan::FramePlan,
+ pub prepared: filmcraft_gpu::PreparedPlan,
+}
+
+impl GpuPlan {
+ /// Bytes this plan keeps alive (layer frames + converted texels).
+ fn bytes(&self) -> usize {
+ let frames = match &self.plan {
+ filmcraft_render::plan::FramePlan::Layers { layers, .. } => layers.iter().map(|l| l.frame.byte_size()).sum(),
+ filmcraft_render::plan::FramePlan::Image(img) => img.px.len() * 4,
+ };
+ frames + self.prepared.bytes()
+ }
+}
+
+/// Finished plans, bounded by count and bytes (oldest use evicted first).
+#[derive(Default)]
+struct PlanCache {
+ map: HashMap<FrameKey, (Arc<GpuPlan>, u64, usize)>,
+ clock: u64,
+ bytes: usize,
+}
+
+impl PlanCache {
+ const MAX: usize = 96;
+ const BUDGET: usize = 1 << 30;
+
+ fn get(&mut self, k: &FrameKey) -> Option<Arc<GpuPlan>> {
+ self.clock += 1;
+ let clock = self.clock;
+ self.map.get_mut(k).map(|(p, used, _)| {
+ *used = clock;
+ p.clone()
+ })
+ }
+
+ fn insert(&mut self, k: FrameKey, p: GpuPlan) {
+ self.clock += 1;
+ let b = p.bytes();
+ self.bytes += b;
+ if let Some((_, _, old)) = self.map.insert(k, (Arc::new(p), self.clock, b)) {
+ self.bytes -= old;
+ }
+ if self.map.len() > Self::MAX || self.bytes > Self::BUDGET {
+ let mut v: Vec<(u64, FrameKey, usize)> = self.map.iter().map(|(k, v)| (v.1, *k, v.2)).collect();
+ v.sort_unstable_by_key(|x| x.0);
+ for (_, k, b) in v {
+ if self.map.len() <= Self::MAX && self.bytes <= Self::BUDGET {
+ break;
+ }
+ self.map.remove(&k);
+ self.bytes -= b;
+ }
+ }
+ }
+}
+
struct Cache {
map: HashMap<FrameKey, (Arc<Rgba>, u64)>,
bytes: usize,
@@ -208,7 +267,7 @@ impl FrameServer {
queue: Mutex::new(VecDeque::new()),
cv: Condvar::new(),
done: Mutex::new(Cache { map: HashMap::new(), bytes: 0, budget: 768 << 20, clock: 0 }),
- plans: Mutex::new(HashMap::new()),
+ plans: Mutex::new(PlanCache::default()),
in_flight: Mutex::new(Vec::new()),
profiling: AtomicBool::new(false),
records: Mutex::new(Vec::new()),
@@ -260,24 +319,24 @@ impl FrameServer {
})
}
- pub fn get_plan(&self, k: &FrameKey) -> Option<Arc<filmcraft_render::plan::FramePlan>> {
- self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).get(k).map(|(p, _)| p.clone())
+ pub fn get_plan(&self, k: &FrameKey) -> Option<Arc<GpuPlan>> {
+ self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).get(k)
}
/// Whether the exact frame (image or plan) is ready.
pub fn is_ready(&self, k: &FrameKey) -> bool {
match k.target {
- Target::SequencePlan(_) => self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).contains_key(k),
+ Target::SequencePlan(_) => self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(k),
_ => self.shared.done.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(k),
}
}
/// Nearest cached plan at or before `frame`.
- pub fn nearest_plan(&self, key: FrameKey, max_back: i64) -> Option<(FrameKey, Arc<filmcraft_render::plan::FramePlan>)> {
- let g = self.shared.plans.lock().unwrap_or_else(|e| e.into_inner());
+ pub fn nearest_plan(&self, key: FrameKey, max_back: i64) -> Option<(FrameKey, Arc<GpuPlan>)> {
+ let mut g = self.shared.plans.lock().unwrap_or_else(|e| e.into_inner());
(0..=max_back).find_map(|d| {
let k = FrameKey { frame: key.frame - d, ..key };
- g.get(&k).map(|(p, _)| (k, p.clone()))
+ g.get(&k).map(|p| (k, p))
})
}
@@ -288,7 +347,7 @@ impl FrameServer {
fn request_job(&self, key: FrameKey, time: Tick, scale: f32, project: &Arc<Project>, prio: u32, prefetch: bool) {
if self.shared.done.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(&key)
- || self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&key)
+ || self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).map.contains_key(&key)
{
return;
}
@@ -369,7 +428,8 @@ impl FrameServer {
if let Some(job) = job {
if let Target::SequencePlan(seq) = job.key.target {
let (plan, _) = plan_job(&job, seq, &self.pool, &self.services, &self.previews, false);
- self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, (Arc::new(plan), 0));
+ let prepared = filmcraft_gpu::prepare(&plan);
+ self.shared.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });
} else {
let (img, _) = render_job(&job, &self.pool, &self.services, &self.previews, false);
self.shared.done.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, Arc::new(img));
@@ -471,16 +531,9 @@ fn worker(
if let Target::SequencePlan(seq) = job.key.target {
let (plan, pv) = plan_job(&job, seq, &pool, &services, &previews, profiling);
if !job.cancel.load(Ordering::Relaxed) {
- let mut g = sh.plans.lock().unwrap_or_else(|e| e.into_inner());
- let clock = g.values().map(|v| v.1).max().unwrap_or(0) + 1;
- g.insert(job.key, (Arc::new(plan), clock));
- if g.len() > 96 {
- let mut v: Vec<(u64, FrameKey)> = g.iter().map(|(k, v)| (v.1, *k)).collect();
- v.sort_unstable_by_key(|x| x.0);
- for (_, k) in v.into_iter().take(g.len() - 96) {
- g.remove(&k);
- }
- }
+ // Convert texels for upload here, not on the UI thread when the frame is shown.
+ let prepared = filmcraft_gpu::prepare(&plan);
+ sh.plans.lock().unwrap_or_else(|e| e.into_inner()).insert(job.key, GpuPlan { plan, prepared });
}
pv
} else {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 64c9a7b0e..689580be3 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -144,7 +144,7 @@ impl FilmcraftApp {
}
/// Composite a plan on the GPU and return the egui texture showing it.
- pub fn gpu_present(&mut self, key: FrameKey, plan: &filmcraft_render::plan::FramePlan) -> Option<(egui::TextureId, (u32, u32))> {
+ pub fn gpu_present(&mut self, key: FrameKey, plan: &frames::GpuPlan) -> Option<(egui::TextureId, (u32, u32))> {
let g = self.gpu.as_mut()?;
if g.last_key == Some(key)
&& let Some(t) = g.texture
@@ -152,7 +152,7 @@ impl FilmcraftApp {
return Some((t, g.size));
}
let t0 = std::time::Instant::now();
- let (view, size) = g.compositor.composite(plan);
+ let (view, size) = g.compositor.composite_prepared(&plan.plan, Some(&plan.prepared));
let view = view.clone();
g.last_ms = t0.elapsed().as_secs_f32() * 1000.0;
let mut renderer = g.render_state.renderer.write();