Skip to content

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

fix(gpu): separate YUV code ranges from texture scaling

WavJaby4d74065aa654
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index f71db2b67..a704a817b 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -505,15 +505,28 @@ impl GpuCompositor {
/// The source description of an uploaded frame.
fn src_info(&self, f: &VideoFrame, key: (usize, u32, u32)) -> Option<SrcInfo> {
let up = self.uploads.get(&key)?;
- Some(SrcInfo { kind: up.kind, code_scale: up.code_scale, alpha: up.alpha_scale, chroma: up.chroma, size: (f.width, f.height), color: f.color })
+ let code_levels = match &f.data {
+ PixelData::Yuv8 { .. } => 256.0,
+ PixelData::Yuv16 { bits, .. } => (*bits as f32).exp2(),
+ _ => 1.0,
+ };
+ Some(SrcInfo {
+ kind: up.kind,
+ code_scale: up.code_scale,
+ code_levels,
+ alpha: up.alpha_scale,
+ chroma: up.chroma,
+ size: (f.width, f.height),
+ color: f.color,
+ })
}
fn uniforms(src: &SrcInfo, m: &filmcraft_geom::Affine, opacity: f32, blend: Blend, out: (u32, u32)) -> [f32; 28] {
let (kr, kb) = src.color.matrix.kr_kb();
- let bits_scale = src.code_scale / 255.0; // code units relative to 8-bit
+ let bits_scale = src.code_levels / 256.0; // 2^(bits - 8), independent of texture encoding
let (yo, ys, co, cs) = match (src.color.range, src.kind) {
(Range::Limited, 2) => (16.0 * bits_scale, 219.0 * bits_scale, 128.0 * bits_scale, 224.0 * bits_scale),
- (Range::Full, 2) => (0.0, src.code_scale - 1.0, src.code_scale / 2.0, src.code_scale - 1.0),
+ (Range::Full, 2) => (0.0, src.code_levels - 1.0, src.code_levels / 2.0, src.code_levels - 1.0),
_ => (0.0, 1.0, 0.0, 1.0),
};
let transfer = match src.color.transfer {
@@ -645,6 +658,7 @@ impl GpuCompositor {
let src = self.src_info(&l.frame, *k).unwrap_or(SrcInfo {
kind: 1,
code_scale: 1.0,
+ code_levels: 1.0,
alpha: 0.0,
chroma: (1, 1),
size: (l.frame.width, l.frame.height),
@@ -678,7 +692,7 @@ impl GpuCompositor {
// what the layer draws: the effect result (linear premultiplied RGBA) or the frame
let (u, tex) = match &job {
Some(j) => {
- let s = SrcInfo { kind: 1, code_scale: 1.0, alpha: 0.0, chroma: l.size(), size: l.size(), color: l.frame.color };
+ let s = SrcInfo { kind: 1, code_scale: 1.0, code_levels: 1.0, alpha: 0.0, chroma: l.size(), size: l.size(), color: l.frame.color };
(Self::uniforms(&s, &l.matrix, l.opacity, l.blend, (w, h)), [j.result.clone(), self.dummy.clone(), self.dummy.clone(), self.dummy.clone()])
}
None => {
@@ -884,11 +898,13 @@ impl GpuCompositor {
}
}
-/// What a layer's shader samples: the texture kind (0 RGBA8 sRGB, 1 linear premultiplied RGBA
-/// float, 2 YUV planes), code scale, chroma plane size, picture size and colour description.
+/// Shader source: kind (0 RGBA8 sRGB, 1 linear premultiplied RGBA, 2 YUV), sampling scales, dimensions, color.
struct SrcInfo {
kind: u32,
+ /// Texture sample -> code units: 255 for R8Unorm, 2^bits for R16Float.
code_scale: f32,
+ /// YUV quantization levels: 2^bits; R8Unorm's decoding scale is one less.
+ code_levels: f32,
/// Alpha texture sample → alpha (0: the frame has no alpha plane).
alpha: f32,
chroma: (u32, u32),
diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs
index a11cef8b1..e8f6f361d 100644
--- a/crates/gpu/src/tests.rs
+++ b/crates/gpu/src/tests.rs
@@ -9,6 +9,83 @@ fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()
}
+#[test]
+fn yuv_code_range_uniforms() {
+ let mut mismatches = Vec::new();
+ for bits in [8, 10, 12, 16] {
+ let levels = (1u32 << bits) as f32;
+ for range in [Range::Full, Range::Limited] {
+ let src = SrcInfo {
+ kind: 2,
+ code_scale: if bits == 8 { 255.0 } else { levels },
+ code_levels: levels,
+ alpha: 0.0,
+ chroma: (1, 1),
+ size: (1, 1),
+ color: filmcraft_color::ColorInfo { range, ..filmcraft_color::ColorInfo::REC709 },
+ };
+ let u = GpuCompositor::uniforms(&src, &Affine::IDENTITY, 1.0, Blend::Normal, (1, 1));
+ // Full: 0..2^bits-1, neutral 2^(bits-1). Limited: BT.709 8-bit codes * 2^(bits-8).
+ let expected = match range {
+ Range::Full => [0.0, levels - 1.0, levels / 2.0, levels - 1.0],
+ Range::Limited => [16.0, 219.0, 128.0, 224.0].map(|v| v * (1u32 << (bits - 8)) as f32),
+ };
+ if u[16..20] != expected {
+ mismatches.push(format!("{bits}-bit {range:?}: {:?} != {expected:?}", &u[16..20]));
+ }
+ }
+ }
+ assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
+}
+
+#[test]
+fn yuv_code_range_gpu_matches_cpu() {
+ let Some((dev, q)) = device() else {
+ eprintln!("no GPU adapter; skipping");
+ return;
+ };
+ let mut c = GpuCompositor::new(&dev, &q);
+ let mut prepared_compositor = GpuCompositor::new(&dev, &q);
+ for bits in [8, 10, 12, 16] {
+ let scale = 1u32 << (bits - 8);
+ for range in [Range::Full, Range::Limited] {
+ // Constant chroma isolates range normalization from CPU/GPU chroma reconstruction.
+ for (u, v) in [(128, 128), (64, 192), (192, 64)] {
+ let y = (0..=255).map(|code| (code * scale) as u16).collect::<Vec<_>>();
+ let planes = [Arc::new(y), Arc::new(vec![(u * scale) as u16; 256]), Arc::new(vec![(v * scale) as u16; 256])];
+ let data = if bits == 8 {
+ PixelData::Yuv8 { planes: planes.map(|p| Arc::new(p.iter().map(|v| *v as u8).collect())), chroma: Chroma::C444, alpha: None }
+ } else {
+ PixelData::Yuv16 { planes, chroma: Chroma::C444, bits, alpha: None }
+ };
+ let frame = Arc::new(VideoFrame {
+ width: 256,
+ height: 1,
+ data,
+ color: filmcraft_color::ColorInfo { range, ..filmcraft_color::ColorInfo::REC709 },
+ par: (1, 1),
+ pts: Default::default(),
+ });
+ let cpu = frame.to_rgba8();
+ let plan = FramePlan::Layers { width: 256, height: 1, layers: vec![PlanLayer::new(frame, Affine::IDENTITY, 1.0, Blend::Normal)] };
+ c.composite(&plan);
+ let (w, h, gpu) = c.read_output().expect("readback");
+ assert_eq!((w, h, gpu.len()), (256, 1, cpu.len()));
+ let error = cpu.iter().zip(&gpu).map(|(a, b)| a.abs_diff(*b)).max().expect("pixels");
+ // One output-code tolerance: CPU f32 vs GPU f16 accumulator quantization.
+ assert!(error <= 1, "{bits}-bit {range:?} U={u} V={v}: max error {error}");
+ if u == 128 && v == 128 {
+ assert!(gpu.chunks_exact(4).all(|p| p[0] == p[1] && p[1] == p[2]), "neutral tint: {bits}-bit {range:?}");
+ }
+ let prepared = prepare(&plan);
+ prepared_compositor.composite_prepared(&plan, Some(&prepared));
+ assert_eq!(prepared_compositor.read_output().expect("prepared readback").2, gpu, "prepared: {bits}-bit {range:?}");
+ eprintln!("range gate: {bits}-bit {range:?} U={u} V={v}, max error={error}, prepared=inline");
+ }
+ }
+ }
+}
+
fn yuv_frame(w: u32, h: u32) -> Arc<VideoFrame> {
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
let y: Vec<u8> = (0..w * h).map(|i| (16 + ((i % w) * 219 / w)) as u8).collect();