Skip to content

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

#965: HDR and wide-gamut media play on the GPU path

JordyUSA2d4422f408f5
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs
index 2ad1fa5f2..ce3340162 100644
--- a/crates/color/src/lib.rs
+++ b/crates/color/src/lib.rs
@@ -20,7 +20,7 @@ pub use grade::GradeSpace;
pub use log::LogCurve;
pub use lut::{Lut, Lut1d, Lut3d, LutFormat};
pub use spaces::{ColorPipeline, ColorSpace, Curve, Gamut, WorkingSpace};
-pub use transform::{DecodeTable, InputTransform, OutputTransform, REFERENCE_WHITE_NITS, ToneMap};
+pub use transform::{DecodeTable, GpuCurve, GpuInputParams, InputTransform, OutputTransform, REFERENCE_WHITE_NITS, ToneMap};
/// YUV ↔ RGB matrix coefficients.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
diff --git a/crates/color/src/transform.rs b/crates/color/src/transform.rs
index 52788d443..99aac66e4 100644
--- a/crates/color/src/transform.rs
+++ b/crates/color/src/transform.rs
@@ -259,6 +259,54 @@ impl InputTransform {
pub fn convert(&self, rgb: [f32; 3]) -> [f32; 3] {
self.apply(rgb.map(|v| self.table.lookup(v)))
}
+
+ /// The transform as plain numbers for a shader, which evaluates the curve and the BT.2390
+ /// EETF directly instead of sampling the tables. `None` for what a shader does not do: log
+ /// curves and the camera-gamut compression.
+ pub fn gpu_params(&self) -> Option<GpuInputParams> {
+ let curve = match self.source.curve() {
+ Curve::Sdr | Curve::Srgb => GpuCurve::Sdr,
+ Curve::Linear => GpuCurve::Linear,
+ Curve::Pq => GpuCurve::Pq,
+ Curve::Hlg => GpuCurve::Hlg,
+ Curve::Log(_) => return None,
+ };
+ if self.compress {
+ return None;
+ }
+ Some(GpuInputParams {
+ curve,
+ hlg: self.hlg,
+ matrix: (!self.identity_matrix).then_some(self.matrix),
+ tone: self.tone.as_ref().map(|t| (t.src_peak_nits as f32, t.dst_peak_nits as f32)),
+ desaturate: self.desaturate,
+ })
+ }
+}
+
+/// How a shader decodes a channel ([`decode_channel`] without the table): SDR with the sRGB curve,
+/// linear, PQ in working units (cd/m² over [`REFERENCE_WHITE_NITS`]), HLG to scene light.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum GpuCurve {
+ Sdr,
+ Linear,
+ Pq,
+ Hlg,
+}
+
+/// [`InputTransform`] for a shader ([`InputTransform::gpu_params`]), stage by stage as
+/// [`InputTransform::apply`] runs them.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct GpuInputParams {
+ pub curve: GpuCurve,
+ /// HLG OOTF: BT.2020 luma weights and the scale to working units.
+ pub hlg: Option<([f32; 3], f32)>,
+ /// Into the working primaries (row-major), when they differ.
+ pub matrix: Option<[[f32; 3]; 3]>,
+ /// BT.2390 tone mapping (source peak, target peak) in cd/m², on max(R,G,B) as a ratio.
+ pub tone: Option<(f32, f32)>,
+ /// Luma weights to desaturate into the working gamut with ([`desaturate_into_gamut`]).
+ pub desaturate: Option<[f32; 3]>,
}
/// Whether gamut `a` lies inside gamut `b` (so no compression is needed going a → b).
@@ -462,6 +510,25 @@ mod tests {
}
}
+ #[test]
+ fn gpu_params_cover_display_referred_media_only() {
+ // HLG / PQ / BT.2020 into Rec. 709: every stage the shader has (#965)
+ let p = |cs| InputTransform::new(cs, Range::Limited, &ColorPipeline::REC709, None).gpu_params();
+ let hlg = p(ColorSpace::Rec2100Hlg).unwrap();
+ assert_eq!(hlg.curve, GpuCurve::Hlg);
+ assert!(hlg.hlg.is_some() && hlg.matrix.is_some() && hlg.desaturate.is_some());
+ assert_eq!(hlg.tone, Some((HDR_PEAK_NITS as f32, REFERENCE_WHITE_NITS as f32)));
+ let pq = InputTransform::new(ColorSpace::Rec2100Pq, Range::Limited, &ColorPipeline::REC709, Some(4000.0)).gpu_params().unwrap();
+ assert_eq!((pq.curve, pq.hlg, pq.tone), (GpuCurve::Pq, None, Some((4000.0, REFERENCE_WHITE_NITS as f32))));
+ let sdr2020 = p(ColorSpace::Rec2020).unwrap();
+ assert_eq!((sdr2020.curve, sdr2020.tone), (GpuCurve::Sdr, None));
+ assert!(sdr2020.matrix.is_some() && sdr2020.desaturate.is_some());
+ // log curves and camera-gamut compression stay on the CPU
+ for cs in ColorSpace::ALL.into_iter().filter(|c| c.is_log()) {
+ assert_eq!(p(cs), None, "{cs:?}");
+ }
+ }
+
#[test]
fn sdr_in_hdr_keeps_values_and_display_tone_maps() {
let pipe = hdr(WorkingSpace::Rec2100Pq);
diff --git a/crates/gpu/src/blend_tests.rs b/crates/gpu/src/blend_tests.rs
index 40b575229..a21c5a2b7 100644
--- a/crates/gpu/src/blend_tests.rs
+++ b/crates/gpu/src/blend_tests.rs
@@ -162,14 +162,15 @@ fn gpu_blend_modes_match_cpu() {
layers: vec![
// opaque YUV on the left, a partially transparent ramp on the right; the top-right
// corner stays empty (destination alpha 0)
- PlanLayer { frame: yuv_frame(640, 360), matrix: Affine::scale(0.35, 0.5), opacity: 1.0, blend: Blend::Normal, fx: None },
- PlanLayer { frame: base.clone(), matrix: Affine::translate(200.0, 40.0), opacity: 0.9, blend: Blend::Normal, fx: None },
+ PlanLayer { frame: yuv_frame(640, 360), matrix: Affine::scale(0.35, 0.5), opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
+ PlanLayer { frame: base.clone(), matrix: Affine::translate(200.0, 40.0), opacity: 0.9, blend: Blend::Normal, fx: None, input: None },
PlanLayer {
frame: top.clone(),
matrix: Affine::motion(Vec2::new(170.0, 95.0), Vec2::new(1.1, 1.1), 17.0, Vec2::new(80.0, 60.0)),
opacity: 0.8,
blend: mode,
fx: None,
+ input: None,
},
PlanLayer {
frame: demo.clone(),
@@ -177,6 +178,7 @@ fn gpu_blend_modes_match_cpu() {
opacity: 0.6,
blend: mode,
fx: None,
+ input: None,
},
],
};
@@ -235,8 +237,8 @@ fn gpu_blend_edge_cases_match_cpu() {
width: n,
height: n,
layers: vec![
- PlanLayer { frame: back.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None },
- PlanLayer { frame: src.clone(), matrix: Affine::IDENTITY, opacity, blend: mode, fx: None },
+ PlanLayer { frame: back.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
+ PlanLayer { frame: src.clone(), matrix: Affine::IDENTITY, opacity, blend: mode, fx: None, input: None },
],
};
let cpu = execute_cpu(&plan);
@@ -276,8 +278,8 @@ fn gpu_dissolve_pattern_is_exact() {
width: w,
height: h,
layers: vec![
- PlanLayer { frame: red.clone(), matrix: Affine::scale(w as f64, h as f64), opacity: 1.0, blend: Blend::Normal, fx: None },
- PlanLayer { frame: white.clone(), matrix: Affine::scale(w as f64, h as f64), opacity: op, blend: Blend::Dissolve, fx: None },
+ PlanLayer { frame: red.clone(), matrix: Affine::scale(w as f64, h as f64), opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
+ PlanLayer { frame: white.clone(), matrix: Affine::scale(w as f64, h as f64), opacity: op, blend: Blend::Dissolve, fx: None, input: None },
],
};
let cpu = execute_cpu(&plan).over_black_rgba8();
@@ -303,7 +305,7 @@ fn normal_fast_path_and_blend_layers_off_output() {
};
let mut c = GpuCompositor::new(&dev, &q);
let grey = Arc::new(VideoFrame::rgba_f32(4, 4, vec![0.2; 64]));
- let layer = |m: Affine, blend: Blend| PlanLayer { frame: grey.clone(), matrix: m, opacity: 1.0, blend, fx: None };
+ let layer = |m: Affine, blend: Blend| PlanLayer { frame: grey.clone(), matrix: m, opacity: 1.0, blend, fx: None, input: None };
let normal = FramePlan::Layers { width: 32, height: 16, layers: vec![layer(Affine::scale(8.0, 4.0), Blend::Normal)] };
c.composite(&normal);
assert!(c.backdrop.is_none());
@@ -329,7 +331,14 @@ fn normal_fast_path_and_blend_layers_off_output() {
#[test]
fn quad_bounds_clamps_and_handles_non_finite() {
- let l = |m: Affine| PlanLayer { frame: Arc::new(VideoFrame::rgba_f32(10, 10, vec![0.0; 400])), matrix: m, opacity: 1.0, blend: Blend::Screen, fx: None };
+ let l = |m: Affine| PlanLayer {
+ frame: Arc::new(VideoFrame::rgba_f32(10, 10, vec![0.0; 400])),
+ matrix: m,
+ opacity: 1.0,
+ blend: Blend::Screen,
+ fx: None,
+ input: None,
+ };
assert_eq!(quad_bounds(&l(Affine::translate(5.0, 5.0)), 100, 100), Some((4, 4, 12, 12)));
assert_eq!(quad_bounds(&l(Affine::translate(-5.0, 95.0)), 100, 100), Some((0, 94, 6, 6)));
assert_eq!(quad_bounds(&l(Affine::translate(f64::NAN, 0.0)), 100, 100), Some((0, 0, 100, 100)));
diff --git a/crates/gpu/src/composite.wgsl b/crates/gpu/src/composite.wgsl
index c2eb10440..9e6372d00 100644
--- a/crates/gpu/src/composite.wgsl
+++ b/crates/gpu/src/composite.wgsl
@@ -15,6 +15,13 @@ struct U {
p1: vec4<f32>, // y_off y_scale c_off c_scale (code units)
p2: vec4<f32>, // kr kb code_scale footprint
p3: vec4<f32>, // blend mode, alpha-plane scale (0: none), effect-source integer decimation, unused
+ // Colour management of HDR / wide-gamut Y'CbCr (`filmcraft_color::InputTransform`, #965):
+ q0: vec4<f32>, // on, curve (0 sdr, 1 linear, 2 pq, 3 hlg), HLG OOTF scale (0: none), reference white cd/m²
+ q1: vec4<f32>, // HLG OOTF luma weights, gamut matrix on
+ q2: vec4<f32>, // gamut matrix row 0, tone mapping on
+ q3: vec4<f32>, // gamut matrix row 1, tone-mapping source peak cd/m²
+ q4: vec4<f32>, // gamut matrix row 2, tone-mapping target peak cd/m²
+ q5: vec4<f32>, // desaturation luma weights, desaturation on
};
@group(0) @binding(0) var<uniform> u: U;
@@ -85,6 +92,82 @@ fn to_linear(v: vec3<f32>) -> vec3<f32> {
return srgb_to_linear(clamp(v, vec3(0.0), vec3(1.0)));
}
+// ---- colour management (`filmcraft_color::transform`), for `u.q0.x` = 1
+
+// SMPTE ST 2084 on a 0..1 scale (1 = 10 000 cd/m²) and back.
+fn pq1(e: f32) -> f32 {
+ let m1 = 0.1593017578125; let m2 = 78.84375; let c1 = 0.8359375; let c2 = 18.8515625; let c3 = 18.6875;
+ let p = pow(max(e, 0.0), 1.0 / m2);
+ return pow(max(p - c1, 0.0) / (c2 - c3 * p), 1.0 / m1);
+}
+fn pq1_inv(y: f32) -> f32 {
+ let m1 = 0.1593017578125; let m2 = 78.84375; let c1 = 0.8359375; let c2 = 18.8515625; let c3 = 18.6875;
+ let p = pow(clamp(y, 0.0, 1.0), m1);
+ return pow((c1 + c2 * p) / (1.0 + c3 * p), m2);
+}
+
+// ITU-R BT.2390 EETF (`bt2390_eetf`), source peak s to target peak d, in cd/m².
+fn eetf(nits: f32, s: f32, d: f32) -> f32 {
+ if d >= s || nits <= 0.0 { return clamp(nits, 0.0, max(s, d)); }
+ let smax = pq1_inv(s / 10000.0);
+ let e1 = min(pq1_inv(nits / 10000.0) / smax, 1.0);
+ let max_lum = pq1_inv(d / 10000.0) / smax;
+ let ks = 1.5 * max_lum - 0.5;
+ var e2 = e1;
+ if e1 >= ks {
+ let t = (e1 - ks) / (1.0 - ks);
+ let t2 = t * t; let t3 = t2 * t;
+ e2 = (2.0 * t3 - 3.0 * t2 + 1.0) * ks + (t3 - 2.0 * t2 + t) * (1.0 - ks) + (-2.0 * t3 + 3.0 * t2) * max_lum;
+ }
+ return pq1(e2 * smax) * 10000.0;
+}
+
+// Signal → working linear: `InputTransform::convert` (curve, HLG OOTF, gamut matrix, tone
+// mapping, desaturation into the working gamut). The CPU's decode tables clamp the signal to 0..1.
+fn managed(rgb: vec3<f32>) -> vec3<f32> {
+ let v = clamp(rgb, vec3(0.0), vec3(1.0));
+ let curve = u32(u.q0.y);
+ let white = u.q0.w;
+ var c = v;
+ if curve == 0u { c = srgb_to_linear(v); }
+ if curve == 2u { c = vec3(pq1(v.r), pq1(v.g), pq1(v.b)) * (10000.0 / white); }
+ if curve == 3u { c = hlg_inv(v); }
+ if u.q0.z > 0.0 {
+ let ys = max(dot(u.q1.xyz, c), 0.0);
+ var g = 0.0;
+ if ys > 0.0 { g = u.q0.z * pow(ys, 0.2); }
+ c = c * g;
+ }
+ if u.q1.w > 0.5 {
+ c = vec3(dot(u.q2.xyz, c), dot(u.q3.xyz, c), dot(u.q4.xyz, c));
+ }
+ if u.q2.w > 0.5 {
+ let m = max(max(c.r, c.g), c.b);
+ if m > 0.0 {
+ let nits = m * white;
+ var k = 1.0;
+ if nits >= u.q3.w {
+ k = u.q4.w / white / m;
+ } else if nits > 1e-6 {
+ k = eetf(nits, u.q3.w, u.q4.w) / nits;
+ }
+ c = c * k;
+ }
+ }
+ if u.q5.w > 0.5 {
+ let mn = min(min(c.r, c.g), c.b);
+ if mn < 0.0 {
+ let y = dot(u.q5.xyz, c);
+ if y <= 0.0 {
+ c = vec3(0.0);
+ } else {
+ c = max(y + (c - y) * (y / (y - mn)), vec3(0.0));
+ }
+ }
+ }
+ return c;
+}
+
// One linear premultiplied sample at source position p.
fn sample(p: vec2<f32>) -> vec4<f32> {
let kind = u32(u.p0.y);
@@ -113,7 +196,9 @@ fn sample(p: vec2<f32>) -> vec4<f32> {
if u.p3.y > 0.0 {
a = clamp(load4(tex3, p).r * u.p3.y, 0.0, 1.0);
}
- return vec4(to_linear(vec3(R, G, B)) * a, a);
+ var lin = to_linear(vec3(R, G, B));
+ if u.q0.x > 0.5 { lin = managed(vec3(R, G, B)); }
+ return vec4(lin * a, a);
}
// The layer's premultiplied linear colour at this pixel, opacity applied.
diff --git a/crates/gpu/src/fx_tests.rs b/crates/gpu/src/fx_tests.rs
index 6cd1a1d9b..8a63022e9 100644
--- a/crates/gpu/src/fx_tests.rs
+++ b/crates/gpu/src/fx_tests.rs
@@ -578,6 +578,7 @@ fn gpu_effect_layers_match_cpu_plan() {
opacity: 1.0,
blend: Blend::Normal,
fx: Some(Arc::new(LayerFx { size: (320, 180), decimation: 2, ops: ops(&chain_c, 320, 180, 0.5) })),
+ input: None,
},
PlanLayer {
frame: ramp.clone(),
@@ -585,6 +586,7 @@ fn gpu_effect_layers_match_cpu_plan() {
opacity: 0.8,
blend: mode,
fx: Some(Arc::new(LayerFx { size: (160, 120), decimation: 1, ops: ops(&chain_a, 160, 120, 1.0) })),
+ input: None,
},
PlanLayer::new(ramp.clone(), Affine::translate(10.0, 20.0), 0.5, Blend::Normal),
PlanLayer {
@@ -593,6 +595,7 @@ fn gpu_effect_layers_match_cpu_plan() {
opacity: 0.7,
blend: mode,
fx: Some(Arc::new(LayerFx { size: (320, 180), decimation: 1, ops: ops(&chain_b, 320, 180, 1.0) })),
+ input: None,
},
],
};
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index d57c53e5b..6daf61bfe 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -586,10 +586,11 @@ impl GpuCompositor {
chroma: up.chroma,
size: (f.width, f.height),
color: f.color,
+ input: None,
})
}
- fn uniforms(src: &SrcInfo, m: &filmcraft_geom::Affine, opacity: f32, blend: Blend, out: (u32, u32)) -> [f32; 28] {
+ fn uniforms(src: &SrcInfo, m: &filmcraft_geom::Affine, opacity: f32, blend: Blend, out: (u32, u32)) -> [f32; UNIFORM_FLOATS] {
let (kr, kb) = src.color.matrix.kr_kb();
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) {
@@ -609,7 +610,31 @@ impl GpuCompositor {
let footprint = (1.0 / sx.min(sy).max(1e-6)) as f32;
let taps = if footprint > 1.25 { footprint.ceil().min(4.0) } else { 1.0 };
let _ = Matrix::Bt709;
- [
+ // colour management (q0..q5), stage by stage as `InputTransform::apply`
+ let q = src.input.map_or([0.0; 24], |p| {
+ let curve = match p.curve {
+ filmcraft_color::GpuCurve::Sdr => 0.0,
+ filmcraft_color::GpuCurve::Linear => 1.0,
+ filmcraft_color::GpuCurve::Pq => 2.0,
+ filmcraft_color::GpuCurve::Hlg => 3.0,
+ };
+ let (hl, hk) = p.hlg.unwrap_or(([0.0; 3], 0.0));
+ let mx = p.matrix.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]);
+ let (sp, dp) = p.tone.unwrap_or((0.0, 0.0));
+ let dl = p.desaturate.unwrap_or([0.0; 3]);
+ let on = |b: bool| if b { 1.0 } else { 0.0 };
+ #[rustfmt::skip]
+ let q = [
+ 1.0, curve, hk, filmcraft_color::REFERENCE_WHITE_NITS as f32,
+ hl[0], hl[1], hl[2], on(p.matrix.is_some()),
+ mx[0][0], mx[0][1], mx[0][2], on(p.tone.is_some()),
+ mx[1][0], mx[1][1], mx[1][2], sp,
+ mx[2][0], mx[2][1], mx[2][2], dp,
+ dl[0], dl[1], dl[2], on(p.desaturate.is_some()),
+ ];
+ q
+ });
+ let base = [
m.a as f32,
m.b as f32,
m.c as f32,
@@ -638,10 +663,14 @@ impl GpuCompositor {
src.alpha,
0.0,
0.0,
- ]
+ ];
+ let mut u = [0.0; UNIFORM_FLOATS];
+ u[..28].copy_from_slice(&base);
+ u[28..].copy_from_slice(&q);
+ u
}
- fn uniform_buffer(&self, u: &[f32; 28]) -> wgpu::Buffer {
+ fn uniform_buffer(&self, u: &[f32; UNIFORM_FLOATS]) -> wgpu::Buffer {
let bytes: Vec<u8> = u.iter().flat_map(|v| v.to_le_bytes()).collect();
let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("layer-u"),
@@ -679,7 +708,8 @@ impl GpuCompositor {
},
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, blend: Blend::Normal, fx: None }];
+ owned =
+ [PlanLayer { frame: Arc::new(frame), matrix: filmcraft_geom::Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None }];
(img.w as u32, img.h as u32, &owned[..])
}
FramePlan::Composite { width, height, steps } => return self.composite_steps(*width, *height, steps, prep),
@@ -736,7 +766,10 @@ impl GpuCompositor {
chroma: (1, 1),
size: (l.frame.width, l.frame.height),
color: l.frame.color,
+ input: None,
});
+ // HDR / wide-gamut Y'CbCr: the planner's input transform, in the shader (#965)
+ let src = SrcInfo { input: l.input.as_ref().filter(|_| src.kind == 2).and_then(|t| t.gpu_params()), ..src };
let views = self.uploads.get(k).map_or_else(|| std::array::from_fn(|_| self.dummy.clone()), |up| up.views.clone());
let job = match &l.fx {
Some(lfx) => {
@@ -768,7 +801,8 @@ 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, code_levels: 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, input: None };
(Self::uniforms(&s, &l.matrix, l.opacity, l.blend, (w, h)), [j.result.clone(), self.dummy.clone(), self.dummy.clone(), self.dummy.clone()])
}
None => {
@@ -1108,8 +1142,13 @@ struct SrcInfo {
chroma: (u32, u32),
size: (u32, u32),
color: filmcraft_color::ColorInfo,
+ /// Colour management beyond the default decode (a Y'CbCr layer's [`PlanLayer::input`]).
+ input: Option<filmcraft_color::GpuInputParams>,
}
+/// Floats in a layer's uniform block (`U` in `composite.wgsl`: 13 vec4).
+const UNIFORM_FLOATS: usize = 52;
+
/// A render pass drawing into the accumulator.
fn accum_pass<'e>(enc: &'e mut wgpu::CommandEncoder, view: &wgpu::TextureView, load: wgpu::LoadOp<wgpu::Color>) -> wgpu::RenderPass<'e> {
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs
index b7807aa63..034333ee3 100644
--- a/crates/gpu/src/tests.rs
+++ b/crates/gpu/src/tests.rs
@@ -23,6 +23,7 @@ fn yuv_code_range_uniforms() {
chroma: (1, 1),
size: (1, 1),
color: filmcraft_color::ColorInfo { range, ..filmcraft_color::ColorInfo::REC709 },
+ input: None,
};
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).
@@ -122,13 +123,14 @@ fn gpu_matches_cpu_plan() {
width: w,
height: h,
layers: vec![
- PlanLayer { frame: yuv_frame(640, 360), matrix: Affine::scale(0.5, 0.5), opacity: 1.0, blend: Blend::Normal, fx: None },
+ PlanLayer { frame: yuv_frame(640, 360), matrix: Affine::scale(0.5, 0.5), opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
PlanLayer {
frame: rgba,
matrix: Affine::motion(Vec2::new(200.0, 100.0), Vec2::new(0.4, 0.4), 12.0, Vec2::new(160.0, 90.0)),
opacity: 0.7,
blend: Blend::Normal,
fx: None,
+ input: None,
},
],
};
@@ -287,8 +289,8 @@ fn prepared_upload_matches_inline_conversion() {
width: w as usize,
height: h as usize,
layers: vec![
- PlanLayer { frame: yuv16, matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None },
- PlanLayer { frame: rgbaf, matrix: Affine::scale(0.5, 0.5), opacity: 0.8, blend: Blend::Normal, fx: None },
+ PlanLayer { frame: yuv16, matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
+ PlanLayer { frame: rgbaf, matrix: Affine::scale(0.5, 0.5), opacity: 0.8, blend: Blend::Normal, fx: None, input: None },
],
};
let image = FramePlan::Image(filmcraft_render::Image { w: w as usize, h: h as usize, px: f32_layer });
@@ -317,8 +319,11 @@ fn upload_cache_keeps_buffers_alive() {
let mut c = GpuCompositor::new(&dev, &q);
let px = Arc::new(vec![200u8; 16 * 8 * 4]);
let frame = Arc::new(VideoFrame { width: 16, height: 8, data: PixelData::Rgba8(px.clone()), ..(*yuv_frame(16, 8)).clone() });
- let plan =
- FramePlan::Layers { width: 16, height: 8, layers: vec![PlanLayer { frame, matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None }] };
+ let plan = FramePlan::Layers {
+ width: 16,
+ height: 8,
+ layers: vec![PlanLayer { frame, matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None }],
+ };
c.composite(&plan);
drop(plan);
assert!(Arc::strong_count(&px) > 1, "cached upload must own its pixel buffer");
@@ -467,8 +472,8 @@ fn gpu_draws_yuv_alpha_plane_like_the_cpu() {
width: w,
height: h,
layers: vec![
- PlanLayer { frame: background.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None },
- PlanLayer { frame: yuv_alpha_frame(320, 180, bits), matrix: Affine::IDENTITY, opacity: 0.9, blend: Blend::Normal, fx: None },
+ PlanLayer { frame: background.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None },
+ PlanLayer { frame: yuv_alpha_frame(320, 180, bits), matrix: Affine::IDENTITY, opacity: 0.9, blend: Blend::Normal, fx: None, input: None },
],
};
let cpu = execute_cpu(&plan).over_black_rgba8();
@@ -484,7 +489,7 @@ fn gpu_draws_yuv_alpha_plane_like_the_cpu() {
let bg = execute_cpu(&FramePlan::Layers {
width: w,
height: h,
- layers: vec![PlanLayer { frame: background.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None }],
+ layers: vec![PlanLayer { frame: background.clone(), matrix: Affine::IDENTITY, opacity: 1.0, blend: Blend::Normal, fx: None, input: None }],
})
.over_black_rgba8();
let (l, r, b0) = (at(&gpu, 1), at(&gpu, w - 2), at(&bg, 1));
@@ -500,3 +505,50 @@ fn fast_half_float_conversion_matches_the_reference_for_every_value() {
assert!(fast.to_bits() == slow.to_bits() || (fast.is_nan() && slow.is_nan()), "{h:#06x}: {fast} vs {slow}");
}
}
+
+/// HDR and wide-gamut Y'CbCr on a Rec. 709 sequence (#965): the shader's colour management
+/// (curve, HLG OOTF, BT.2020 → 709 matrix, BT.2390 tone mapping, desaturation) matches the CPU
+/// running the same `InputTransform`.
+#[test]
+fn hdr_input_gpu_matches_cpu() {
+ use filmcraft_color::{ColorInfo, ColorPipeline, ColorSpace, InputTransform, Matrix, Primaries, Transfer};
+ let Some((dev, q)) = device() else {
+ eprintln!("no GPU adapter; skipping");
+ return;
+ };
+ let mut c = GpuCompositor::new(&dev, &q);
+ // a 10-bit luma ramp (to the top code) under neutral, saturated and extreme chroma, 4:4:4
+ let (w, h) = (256u32, 6u32);
+ let chroma = [(512, 512), (300, 760), (760, 300), (64, 512), (960, 960), (512, 64)];
+ let y: Vec<u16> = (0..h).flat_map(|_| (0..w).map(|x| (64 + x * 876 / 255) as u16)).collect();
+ let cb: Vec<u16> = (0..h).flat_map(|r| std::iter::repeat_n(chroma[r as usize].0, w as usize)).collect();
+ let cr: Vec<u16> = (0..h).flat_map(|r| std::iter::repeat_n(chroma[r as usize].1, w as usize)).collect();
+ let data = PixelData::Yuv16 { planes: [Arc::new(y), Arc::new(cb), Arc::new(cr)], chroma: Chroma::C444, bits: 10, alpha: None };
+ let hdr = |transfer| ColorInfo { matrix: Matrix::Bt2020Ncl, transfer, primaries: Primaries::Bt2020, range: Range::Limited };
+ let cases = [
+ ("HLG", hdr(Transfer::Hlg), None),
+ ("PQ", hdr(Transfer::Pq), None),
+ ("PQ 4000 cd/m²", hdr(Transfer::Pq), Some(4000.0)),
+ ("BT.2020 SDR", ColorInfo { primaries: Primaries::Bt2020, ..ColorInfo::REC709 }, None),
+ ];
+ for (name, color, peak) in cases {
+ let frame = Arc::new(VideoFrame { width: w, height: h, data: data.clone(), color, par: (1, 1), pts: Default::default() });
+ let cs = ColorSpace::from_info(&color);
+ let t = Arc::new(InputTransform::new(cs, color.range, &ColorPipeline::REC709, peak));
+ assert!(t.gpu_params().is_some(), "{name}");
+ let layer = PlanLayer { input: Some(t), ..PlanLayer::new(frame.clone(), Affine::IDENTITY, 1.0, Blend::Normal) };
+ let plan = FramePlan::Layers { width: w as usize, height: h as usize, layers: vec![layer] };
+ let cpu = execute_cpu(&plan).over_black_rgba8();
+ c.composite(&plan);
+ let (_, _, gpu) = c.read_output().expect("readback");
+ let error = cpu.iter().zip(&gpu).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
+ // and the stage does something: the default decode of the same frame is far off
+ let plain = FramePlan::Layers { width: w as usize, height: h as usize, layers: vec![PlanLayer::new(frame, Affine::IDENTITY, 1.0, Blend::Normal)] };
+ c.composite(&plain);
+ let (_, _, unmanaged) = c.read_output().expect("readback");
+ let apart = cpu.iter().zip(&unmanaged).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
+ eprintln!("{name}: max error {error}, unmanaged differs by up to {apart}");
+ assert!(error <= 2, "{name}: GPU differs from the CPU by up to {error} codes");
+ assert!(apart > 20, "{name}: colour management changed nothing ({apart})");
+ }
+}
diff --git a/crates/render/src/colorman.rs b/crates/render/src/colorman.rs
index 06a7afea1..e645b9c3a 100644
--- a/crates/render/src/colorman.rs
+++ b/crates/render/src/colorman.rs
@@ -3,7 +3,10 @@
//! transform. The maths lives in `filmcraft_color::transform`.
//!
//! A sequence whose pipeline is "plain" (Rec. 709 working space without wide gamut) and media
-//! whose metadata says Rec. 709 / sRGB / linear take the original fast path unchanged.
+//! whose metadata says Rec. 709 / sRGB / linear take the original fast path unchanged. On such a
+//! sequence, display-referred HDR and wide-gamut Y'CbCr (PQ, HLG, BT.2020, P3) stays on the GPU
+//! path as well, with its input transform run in the compositor's shader ([`gpu_input`]); log
+//! media and the other pipelines are converted here, on the CPU.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
@@ -51,6 +54,18 @@ pub fn input_transform(cs: ColorSpace, range: Range, pipe: &ColorPipeline, peak_
t
}
+/// The input transform of a frame the GPU compositor can colour manage itself (#965): a Y'CbCr
+/// frame of display-referred HDR or wide-gamut media (PQ, HLG, BT.2020, P3) on a plain pipeline,
+/// whose working → monitor transform is the identity. None for log media (camera-gamut
+/// compression), RGB frames and other pipelines, which [`decode`] converts on the CPU.
+pub fn gpu_input(project: &Project, item: ItemId, pipe: &ColorPipeline, cs: ColorSpace, frame: &VideoFrame) -> Option<Arc<InputTransform>> {
+ if !pipe.is_plain() || !matches!(frame.data, filmcraft_frame::PixelData::Yuv8 { .. } | filmcraft_frame::PixelData::Yuv16 { .. }) {
+ return None;
+ }
+ let t = input_transform(cs, frame.color.range, pipe, source_peak_nits(project, item));
+ t.gpu_params().map(|_| t)
+}
+
/// Decode a frame of `item` (box-decimated by `n`) into the working space of `pipe`.
pub fn decode(project: &Project, item: ItemId, frame: &VideoFrame, n: usize, pipe: &ColorPipeline) -> Image {
let cs = source_space(project, item, frame);
diff --git a/crates/render/src/plan.rs b/crates/render/src/plan.rs
index 4dd0d4d0e..166b615bc 100644
--- a/crates/render/src/plan.rs
+++ b/crates/render/src/plan.rs
@@ -39,6 +39,10 @@ pub struct PlanLayer {
pub blend: Blend,
/// Standard effects to run on the frame before it is placed (None: draw the frame directly).
pub fx: Option<Arc<LayerFx>>,
+ /// Colour management of a Y'CbCr frame that needs more than the default decode (HDR, BT.2020,
+ /// P3 media on a Rec. 709 sequence; [`crate::colorman::gpu_input`]): run on the GPU as on the
+ /// CPU. None: the default decode.
+ pub input: Option<Arc<filmcraft_color::InputTransform>>,
}
/// The GPU effect stage of a layer: the frame is decoded into a working image of `size` (the
@@ -54,7 +58,7 @@ pub struct LayerFx {
impl PlanLayer {
/// A layer drawing `frame` directly.
pub fn new(frame: Arc<VideoFrame>, matrix: Affine, opacity: f32, blend: Blend) -> Self {
- Self { frame, matrix, opacity, blend, fx: None }
+ Self { frame, matrix, opacity, blend, fx: None, input: None }
}
/// Size of the picture the matrix places: the working image with effects, else the frame.
@@ -408,10 +412,13 @@ fn push_item(
let time = crate::video_source_time(item, t, src.info().frame_rate());
let Ok(frame) = src.video_frame(FrameRequest { time, scale: want }) else { return };
let cs = crate::colorman::source_space(project, item.item, &frame);
- // log / HDR / wide-gamut media is converted on the CPU (below), and so are blended
+ // HDR and wide-gamut media on a Rec. 709 sequence is converted on the GPU too (#965); log
+ // media and other pipelines are converted on the CPU (below), and so are blended
// in-between frames (Frame Blending / Optical Flow on speed-changed clips)
+ let pipe = &seq.settings.color;
+ let input = if crate::colorman::needs_management(pipe, cs, &frame) { crate::colorman::gpu_input(project, item.item, pipe, cs, &frame) } else { None };
let plain =
- !crate::colorman::needs_management(&seq.settings.color, cs, &frame) && crate::interpolation_blend(item, t, src.info().frame_rate()).is_none();
+ (input.is_some() || !crate::colorman::needs_management(pipe, cs, &frame)) && crate::interpolation_blend(item, t, src.info().frame_rate()).is_none();
if plain && !chain.is_empty() {
// GPU effect stage: the working image the CPU would decode (`base_layer`), the
// effects evaluated for it, placed as `item_layer` places it
@@ -435,7 +442,7 @@ fn push_item(
.then_apply(&motion)
.then_apply(&Affine::scale(1.0 / px_scale as f64, 1.0 / px_scale as f64));
let fx = LayerFx { size: (lw as u32, lh as u32), decimation: n as u32, ops };
- out.push(PlanLayer { frame, matrix: m, opacity: op * extra_opacity, blend: bl, fx: Some(Arc::new(fx)) });
+ out.push(PlanLayer { frame, matrix: m, opacity: op * extra_opacity, blend: bl, fx: Some(Arc::new(fx)), input });
return;
}
} else if plain {
@@ -450,7 +457,7 @@ fn push_item(
};
let px_scale = frame.width as f64 / size.0.max(1) as f64;
let m = Affine::scale(opts.scale as f64, opts.scale as f64).then_apply(&motion).then_apply(&Affine::scale(1.0 / px_scale, 1.0 / px_scale));
- out.push(PlanLayer::new(frame, m, op * extra_opacity, bl));
+ out.push(PlanLayer { input, ..PlanLayer::new(frame, m, op * extra_opacity, bl) });
return;
}
}
@@ -468,8 +475,12 @@ fn near_identity(m: &Affine) -> bool {
/// A layer's working image with its effects applied, on the CPU (the reference for the GPU
/// effect stage).
pub fn effect_image(frame: &VideoFrame, fx: &LayerFx) -> crate::Image {
- let (w, h, px) = frame.to_linear_f32_decimated(fx.decimation.max(1) as usize);
- let mut img = crate::Image { w, h, px };
+ effect_image_with(frame, fx, None)
+}
+
+/// [`effect_image`] of a colour-managed layer ([`PlanLayer::input`]).
+pub fn effect_image_with(frame: &VideoFrame, fx: &LayerFx, input: Option<&filmcraft_color::InputTransform>) -> crate::Image {
+ let mut img = linear_image(frame, fx.decimation.max(1) as usize, input);
for op in &fx.ops {
op.apply(&mut img);
}
@@ -506,12 +517,23 @@ pub fn execute_cpu(plan: &FramePlan) -> crate::Image {
}
}
+/// A layer's frame (box-decimated by `n`) as a linear working image: the default decode, or
+/// `input`'s table and pixel stage as `colorman::decode` runs them.
+fn linear_image(frame: &VideoFrame, n: usize, input: Option<&filmcraft_color::InputTransform>) -> crate::Image {
+ let (w, h, px) = frame.to_linear_f32_decimated_with(n, input.map(|t| &t.table));
+ let mut img = crate::Image { w, h, px };
+ if let Some(t) = input.filter(|t| t.has_pixel_stage()) {
+ img.map_rgb(|c, _, _| t.apply(c));
+ }
+ img
+}
+
fn execute_layers(canvas: &mut crate::Image, layers: &[PlanLayer]) {
let (width, height) = (canvas.w, canvas.h);
for l in layers {
let src = match &l.fx {
- Some(fx) => effect_image(&l.frame, fx),
- None => crate::Image { w: l.frame.width as usize, h: l.frame.height as usize, px: l.frame.to_linear_f32() },
+ Some(fx) => effect_image_with(&l.frame, fx, l.input.as_deref()),
+ None => linear_image(&l.frame, 1, l.input.as_deref()),
};
let placed = if l.matrix == Affine::scale(width as f64, height as f64) && src.w == 1 && src.h == 1 {
crate::Image::filled(width, height, src.get(0, 0))
diff --git a/crates/render/src/region_tests.rs b/crates/render/src/region_tests.rs
index 822fa5518..fd0e7f9bf 100644
--- a/crates/render/src/region_tests.rs
+++ b/crates/render/src/region_tests.rs
@@ -299,3 +299,28 @@ fn a_region_layer_expands_to_the_whole_layer() {
assert_eq!(full.px.iter().filter(|v| **v == 1.0).count(), 2 * 2 * 4);
assert!(full.px[..(2 * 6 + 4) * 4].iter().all(|v| *v == 0.0));
}
+
+/// HDR and wide-gamut Y'CbCr on a Rec. 709 sequence is planned as a GPU layer carrying its input
+/// transform, not converted to a float image on the CPU (#965: 4K HLG / PQ playback fell to a
+/// third of real time), and the plan still renders what the reference renderer does.
+#[test]
+fn hdr_media_is_planned_for_the_gpu_with_its_colour_management() {
+ use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
+ let hdr = |transfer| ColorInfo { matrix: Matrix::Bt2020Ncl, transfer, primaries: Primaries::Bt2020, range: Range::Limited };
+ for (name, color) in
+ [("HLG", hdr(Transfer::Hlg)), ("PQ", hdr(Transfer::Pq)), ("BT.2020 SDR", ColorInfo { primaries: Primaries::Bt2020, ..ColorInfo::REC709 })]
+ {
+ let f = Arc::new(VideoFrame { color, ..(*camera(W, H)).clone() });
+ let (p, seq, map) = scene(&[Spec::new(f)]);
+ let opts = RenderOptions::default();
+ let plan = plan::plan_frame(&p, seq, Tick::ZERO, opts, &map);
+ let plan::FramePlan::Layers { layers, .. } = &plan else { panic!("{name}: not a layer plan") };
+ assert_eq!(layers.len(), 1, "{name}");
+ assert!(matches!(layers[0].frame.data, PixelData::Yuv8 { .. }), "{name}: converted on the CPU");
+ assert!(layers[0].input.is_some(), "{name}: no colour management for the GPU");
+ let reference = render_sequence(&p, seq, Tick::ZERO, opts, &map);
+ let got = plan::execute_cpu(&plan);
+ let max = got.px.iter().zip(&reference.px).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
+ assert!(max < 1e-4, "{name}: plan differs from the reference by {max}");
+ }
+}
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs
index c8db19cdd..65db9d57f 100644
--- a/crates/ui-egui/src/frames.rs
+++ b/crates/ui-egui/src/frames.rs
@@ -914,7 +914,7 @@ fn plan_job(job: &Job, seq: ItemId, pool: &Arc<MediaPool>, services: &Arc<dyn Se
// captions (they are not part of the preview hash), so captions are layered on live.
let (w, h) = filmcraft_render::output_size(q, job.scale);
let matrix = filmcraft_geom::Affine::scale(w as f64 / frame.width.max(1) as f64, h as f64 / frame.height.max(1) as f64);
- let mut layers = vec![filmcraft_render::plan::PlanLayer { frame, matrix, opacity: 1.0, blend: filmcraft_render::Blend::Normal, fx: None }];
+ let mut layers = vec![filmcraft_render::plan::PlanLayer { frame, matrix, opacity: 1.0, blend: filmcraft_render::Blend::Normal, fx: None, input: None }];
for o in filmcraft_render::caption_overlays(q, job.time, w, h) {
layers.push(filmcraft_render::plan::PlanLayer {
frame: Arc::new(filmcraft_frame::VideoFrame::rgba_f32(o.w as u32, o.h as u32, o.px)),
@@ -922,6 +922,7 @@ fn plan_job(job: &Job, seq: ItemId, pool: &Arc<MediaPool>, services: &Arc<dyn Se
opacity: 1.0,
blend: filmcraft_render::Blend::Normal,
fx: None,
+ input: None,
});
}
return (filmcraft_render::plan::FramePlan::Layers { width: w, height: h, layers }, true);
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 438112a29..9e2216c34 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2115,8 +2115,14 @@ mod gpu_fallback_tests {
#[test]
fn plan_side_covers_output_and_every_layer() {
let frame = |w: u32, h: u32| std::sync::Arc::new(filmcraft_frame::VideoFrame::rgba_f32(w, h, vec![0.0; (w * h * 4) as usize]));
- let layer =
- |w, h| PlanLayer { frame: frame(w, h), matrix: filmcraft_geom::Affine::IDENTITY, opacity: 1.0, blend: filmcraft_render::Blend::Normal, fx: None };
+ let layer = |w, h| PlanLayer {
+ frame: frame(w, h),
+ matrix: filmcraft_geom::Affine::IDENTITY,
+ opacity: 1.0,
+ blend: filmcraft_render::Blend::Normal,
+ fx: None,
+ input: None,
+ };
// a 4K source in an HD sequence still needs a 3840-wide texture on the GPU
let p = FramePlan::Layers { width: 1920, height: 1080, layers: vec![layer(64, 64), layer(3840, 2160)] };
assert_eq!(super::plan_side(&p), 3840);