From 15015e645a39282908398af9f08617c77deddbd6 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 14:00:48 -0800 Subject: [PATCH] feat(engine): implement 14 OCIO, Layer, Metadata, MultiText & Utility built-ins Assisted-by: claude-sonnet-5.5 --- crates/engine/src/eval/color_lut.rs | 10 +- crates/engine/src/eval/color_lut/color_fx.rs | 2 +- .../engine/src/eval/color_lut/colorimetry.rs | 78 ++-- crates/engine/src/eval/color_lut/lut_io.rs | 2 +- crates/engine/src/eval/layer_ocio.rs | 318 +++++++++++++ .../src/eval/layer_ocio/file_transform.rs | 287 ++++++++++++ crates/engine/src/eval/layer_ocio/layers.rs | 135 ++++++ crates/engine/src/eval/layer_ocio/ocio.rs | 247 ++++++++++ crates/engine/src/eval/layer_ocio/pattern.rs | 139 ++++++ .../src/eval/layer_ocio/swizzle_fields.rs | 162 +++++++ crates/engine/src/eval/layer_ocio/tests.rs | 432 ++++++++++++++++++ crates/engine/src/eval/layer_ocio/utility.rs | 215 +++++++++ crates/engine/src/eval/mod.rs | 21 + crates/engine/src/shaders/color_lut.wgsl | 27 +- crates/engine/src/shaders/layer_ocio.wgsl | 269 +++++++++++ 15 files changed, 2295 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/eval/layer_ocio.rs create mode 100644 crates/engine/src/eval/layer_ocio/file_transform.rs create mode 100644 crates/engine/src/eval/layer_ocio/layers.rs create mode 100644 crates/engine/src/eval/layer_ocio/ocio.rs create mode 100644 crates/engine/src/eval/layer_ocio/pattern.rs create mode 100644 crates/engine/src/eval/layer_ocio/swizzle_fields.rs create mode 100644 crates/engine/src/eval/layer_ocio/tests.rs create mode 100644 crates/engine/src/eval/layer_ocio/utility.rs create mode 100644 crates/engine/src/shaders/layer_ocio.wgsl diff --git a/crates/engine/src/eval/color_lut.rs b/crates/engine/src/eval/color_lut.rs index 59ea7d755ea979dc5fb131ae3028699d27819d1d..036af4a89c96da0c4a51383cb901943f5d2dfc54 100644 --- a/crates/engine/src/eval/color_lut.rs +++ b/crates/engine/src/eval/color_lut.rs @@ -6,8 +6,8 @@ //! `textureLoad`, outputs are `WriteOnly` storage textures, and 3D LUTs are packed //! into 2D `Rgba32Float` textures for 100% WebGPU / `wasm32` parity. -mod color_fx; -mod colorimetry; +pub(in crate::eval) mod color_fx; +pub(in crate::eval) mod colorimetry; mod cst_gamut; mod film_look; pub mod lut_io; @@ -23,7 +23,7 @@ const COLOR_LUT_WGSL: &str = include_str!("../shaders/color_lut.wgsl"); const CL_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; #[derive(Clone, Copy)] -pub(self) enum ColorLutOp { +pub(in crate::eval) enum ColorLutOp { ColorMatrix, SetCanvasColor, ChromaticAdaptation, @@ -182,7 +182,7 @@ impl ColorLutPipelines { (chunk_idx, offset) } - pub(self) fn get_or_upload_lut_rgba32f( + pub(in crate::eval) fn get_or_upload_lut_rgba32f( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, @@ -355,7 +355,7 @@ impl Engine { } #[allow(clippy::too_many_arguments)] - pub(self) fn dispatch_cl( + pub(in crate::eval) fn dispatch_cl( &self, enc: &mut wgpu::CommandEncoder, op: ColorLutOp, diff --git a/crates/engine/src/eval/color_lut/color_fx.rs b/crates/engine/src/eval/color_lut/color_fx.rs index 4cd6b030c97d038a5f168c2ce52f610a2dbe5ae6..2dd4b7b34cefa09175844eab351852dfd5e4a079 100644 --- a/crates/engine/src/eval/color_lut/color_fx.rs +++ b/crates/engine/src/eval/color_lut/color_fx.rs @@ -196,7 +196,7 @@ fn parse_cdl_triplet(s: &str, def: [f32; 3]) -> [f32; 3] { } } -pub(super) fn parse_cdl_xml( +pub(in crate::eval) fn parse_cdl_xml( text: &str, ccc_id: &str, ) -> Option<([f32; 3], [f32; 3], [f32; 3], f32)> { diff --git a/crates/engine/src/eval/color_lut/colorimetry.rs b/crates/engine/src/eval/color_lut/colorimetry.rs index b79c4eca37588b6f3da6b5fb26a525c3fb142a5a..f8e0ff9435a9d74300613c47d9063742755d0acd 100644 --- a/crates/engine/src/eval/color_lut/colorimetry.rs +++ b/crates/engine/src/eval/color_lut/colorimetry.rs @@ -3,33 +3,33 @@ use model::{Comp, ExprEngine, Node}; -pub(super) const D60: [f64; 2] = [0.32168, 0.33767]; -pub(super) const D65: [f64; 2] = [0.3127, 0.3290]; -pub(super) const D50: [f64; 2] = [0.34567, 0.35850]; -pub(super) const DCI_W: [f64; 2] = [0.3140, 0.3510]; +pub(in crate::eval) const D60: [f64; 2] = [0.32168, 0.33767]; +pub(in crate::eval) const D65: [f64; 2] = [0.3127, 0.3290]; +pub(in crate::eval) const D50: [f64; 2] = [0.34567, 0.35850]; +pub(in crate::eval) const DCI_W: [f64; 2] = [0.3140, 0.3510]; -pub(super) type Primaries = [[f64; 2]; 4]; +pub(in crate::eval) type Primaries = [[f64; 2]; 4]; -pub(super) const P_REC709: Primaries = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65]; -pub(super) const P_REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65]; -pub(super) const P_P3_D65: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65]; -pub(super) const P_P3_D60: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D60]; -pub(super) const P_P3_DCI: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], DCI_W]; -pub(super) const P_AP0: Primaries = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], D60]; -pub(super) const P_AP1: Primaries = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60]; -pub(super) const P_DWG: Primaries = [[0.8000, 0.3130], [0.1682, 0.9877], [0.0790, -0.1155], D65]; -pub(super) const P_AWG3: Primaries = [[0.6840, 0.3130], [0.2210, 0.8480], [0.0861, -0.1020], D65]; -pub(super) const P_AWG4: Primaries = [[0.7347, 0.2653], [0.1424, 0.8576], [0.0991, -0.0308], D65]; -pub(super) const P_SGAMUT3: Primaries = [[0.730, 0.280], [0.140, 0.855], [0.100, -0.050], D65]; -pub(super) const P_SGAMUT3_CINE: Primaries = [[0.766, 0.275], [0.225, 0.800], [0.089, -0.087], D65]; -pub(super) const P_RWG: Primaries = [[0.780308, 0.304253], [0.121595, 1.493994], [0.095612, -0.084589], D65]; -pub(super) const P_ADOBE: Primaries = [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06], D65]; -pub(super) const P_VGAMUT: Primaries = [[0.730, 0.280], [0.165, 0.840], [0.100, -0.030], D65]; -pub(super) const P_CGAMUT: Primaries = [[0.740, 0.270], [0.170, 1.140], [0.080, -0.100], D65]; -pub(super) const P_BMDWG5: Primaries = [[0.7177215, 0.3171181], [0.2280410, 0.8615690], [0.1005841, -0.0820452], D65]; +pub(in crate::eval) const P_REC709: Primaries = [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65]; +pub(in crate::eval) const P_REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65]; +pub(in crate::eval) const P_P3_D65: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65]; +pub(in crate::eval) const P_P3_D60: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D60]; +pub(in crate::eval) const P_P3_DCI: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], DCI_W]; +pub(in crate::eval) const P_AP0: Primaries = [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], D60]; +pub(in crate::eval) const P_AP1: Primaries = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], D60]; +pub(in crate::eval) const P_DWG: Primaries = [[0.8000, 0.3130], [0.1682, 0.9877], [0.0790, -0.1155], D65]; +pub(in crate::eval) const P_AWG3: Primaries = [[0.6840, 0.3130], [0.2210, 0.8480], [0.0861, -0.1020], D65]; +pub(in crate::eval) const P_AWG4: Primaries = [[0.7347, 0.2653], [0.1424, 0.8576], [0.0991, -0.0308], D65]; +pub(in crate::eval) const P_SGAMUT3: Primaries = [[0.730, 0.280], [0.140, 0.855], [0.100, -0.050], D65]; +pub(in crate::eval) const P_SGAMUT3_CINE: Primaries = [[0.766, 0.275], [0.225, 0.800], [0.089, -0.087], D65]; +pub(in crate::eval) const P_RWG: Primaries = [[0.780308, 0.304253], [0.121595, 1.493994], [0.095612, -0.084589], D65]; +pub(in crate::eval) const P_ADOBE: Primaries = [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06], D65]; +pub(in crate::eval) const P_VGAMUT: Primaries = [[0.730, 0.280], [0.165, 0.840], [0.100, -0.030], D65]; +pub(in crate::eval) const P_CGAMUT: Primaries = [[0.740, 0.270], [0.170, 1.140], [0.080, -0.100], D65]; +pub(in crate::eval) const P_BMDWG5: Primaries = [[0.7177215, 0.3171181], [0.2280410, 0.8615690], [0.1005841, -0.0820452], D65]; #[derive(Clone, Copy, PartialEq, Eq)] -pub(super) enum CatMethod { +pub(in crate::eval) enum CatMethod { Bradford, Cat02, VonKries, @@ -39,7 +39,7 @@ pub(super) enum CatMethod { } impl CatMethod { - pub(super) fn matrix(self) -> [[f64; 3]; 3] { + pub(in crate::eval) fn matrix(self) -> [[f64; 3]; 3] { match self { Self::Bradford => [ [0.8951, 0.2664, -0.1614], @@ -71,7 +71,7 @@ impl CatMethod { } } -pub(super) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] { +pub(in crate::eval) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] { let [a, b, c] = m[0]; let [d, e, f] = m[1]; let [g, h, i] = m[2]; @@ -84,15 +84,15 @@ pub(super) fn mat3_inv(m: [[f64; 3]; 3]) -> [[f64; 3]; 3] { ] } -pub(super) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] { +pub(in crate::eval) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] { std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum())) } -pub(super) fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] { +pub(in crate::eval) fn mat3_vec(m: [[f64; 3]; 3], v: [f64; 3]) -> [f64; 3] { std::array::from_fn(|r| (0..3).map(|c| m[r][c] * v[c]).sum()) } -pub(super) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> { +pub(in crate::eval) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> { let mut a = [[0.0_f64; 8]; 4]; for r in 0..4 { for c in 0..4 { @@ -127,19 +127,19 @@ pub(super) fn mat4_inv(m: [[f64; 4]; 4]) -> Option<[[f64; 4]; 4]> { Some(std::array::from_fn(|r| std::array::from_fn(|c| a[r][4 + c]))) } -pub(super) fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { +pub(in crate::eval) fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { let y = xy[1].max(1e-6); [xy[0] / y, 1.0, (1.0 - xy[0] - xy[1]) / y] } -pub(super) fn primaries_to_xyz(p: Primaries) -> [[f64; 3]; 3] { +pub(in crate::eval) fn primaries_to_xyz(p: Primaries) -> [[f64; 3]; 3] { let [xr, xg, xb, xw] = [xy_to_xyz(p[0]), xy_to_xyz(p[1]), xy_to_xyz(p[2]), xy_to_xyz(p[3])]; let base = [[xr[0], xg[0], xb[0]], [xr[1], xg[1], xb[1]], [xr[2], xg[2], xb[2]]]; let s = mat3_vec(mat3_inv(base), xw); std::array::from_fn(|r| std::array::from_fn(|c| base[r][c] * s[c])) } -pub(super) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMethod) -> [[f64; 3]; 3] { +pub(in crate::eval) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMethod) -> [[f64; 3]; 3] { if (src_wp[0] - dst_wp[0]).abs() <= 1e-7 && (src_wp[1] - dst_wp[1]).abs() <= 1e-7 { return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; } @@ -154,7 +154,7 @@ pub(super) fn cat_xyz_matrix(src_wp: [f64; 2], dst_wp: [f64; 2], method: CatMeth mat3_mul(mat3_inv(m_cat), mat3_mul(diag, m_cat)) } -pub(super) fn rgb_to_rgb_matrix( +pub(in crate::eval) fn rgb_to_rgb_matrix( src: Option, dst: Option, white_adapt: bool, @@ -183,7 +183,7 @@ pub(super) fn rgb_to_rgb_matrix( } /// Kang et al. (2002) Planckian locus chromaticity `xy(T)` for `1667K..50000K` + green-magenta tint. -pub(super) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] { +pub(in crate::eval) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] { let t = kelvin.clamp(1667.0, 25000.0); let x = if t <= 4000.0 { -0.2661239e9 / (t * t * t) - 0.2343589e6 / (t * t) + 0.8776956e3 / t + 0.179910 @@ -202,7 +202,7 @@ pub(super) fn kelvin_tint_to_xy(kelvin: f64, tint: f64) -> [f64; 2] { [x.clamp(0.05, 0.75), (y + duv).clamp(0.05, 0.75)] } -pub(super) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> { +pub(in crate::eval) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> { let s: String = raw .to_ascii_lowercase() .chars() @@ -236,7 +236,7 @@ pub(super) fn parse_illuminant_xy(raw: &str) -> Option<[f64; 2]> { } } -pub(super) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> CatMethod { +pub(in crate::eval) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> CatMethod { if let Some(raw) = node.static_str("CATMethod").or_else(|| node.static_str("Method")) { let s: String = raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect(); if s.contains("bradford") { return CatMethod::Bradford; } @@ -258,7 +258,7 @@ pub(super) fn parse_cat_method(comp: &Comp, node: &Node, time: f64, expr: &ExprE } /// Returns `Some(Primaries)` for RGB spaces, or `None` for CIE XYZ. -pub(super) fn parse_color_space(raw: Option<&str>) -> Option { +pub(in crate::eval) fn parse_color_space(raw: Option<&str>) -> Option { let s_raw = raw.unwrap_or("REC709_COLORSPACE"); let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect(); let s = s.strip_suffix("colorspace").unwrap_or(&s); @@ -319,7 +319,7 @@ pub(super) fn parse_color_space(raw: Option<&str>) -> Option { Some(P_REC709) } -pub(super) fn parse_gamma_id(raw: Option<&str>) -> i32 { +pub(in crate::eval) fn parse_gamma_id(raw: Option<&str>) -> i32 { let s_raw = raw.unwrap_or("LINEAR_GAMMA"); let s: String = s_raw.to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect(); let s = s.strip_suffix("gamma").unwrap_or(&s); @@ -392,7 +392,7 @@ pub(super) fn parse_gamma_id(raw: Option<&str>) -> i32 { 0 } -pub(super) fn parse_tm_mode(raw: Option<&str>) -> i32 { +pub(in crate::eval) fn parse_tm_mode(raw: Option<&str>) -> i32 { let s: String = raw.unwrap_or("TM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect(); match s.as_str() { "tmclip" | "clip" => 1, @@ -403,7 +403,7 @@ pub(super) fn parse_tm_mode(raw: Option<&str>) -> i32 { } } -pub(super) fn parse_gm_mode(raw: Option<&str>) -> i32 { +pub(in crate::eval) fn parse_gm_mode(raw: Option<&str>) -> i32 { let s: String = raw.unwrap_or("GM_NONE").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect(); match s.as_str() { "gmrcm1" | "saturationcompression" | "compress" | "aces" => 1, diff --git a/crates/engine/src/eval/color_lut/lut_io.rs b/crates/engine/src/eval/color_lut/lut_io.rs index dbdb7b0712b3a12c0086a792d157eab60a63353a..f22cef8e1463e25ea769fed114586de52e3e1f80 100644 --- a/crates/engine/src/eval/color_lut/lut_io.rs +++ b/crates/engine/src/eval/color_lut/lut_io.rs @@ -17,7 +17,7 @@ pub struct ParsedLut { pub content_hash: u64, } -fn hash_lut_data(is_3d: bool, size: u32, dmin: [f32; 3], dmax: [f32; 3], rgba: &[f32]) -> u64 { +pub(in crate::eval) fn hash_lut_data(is_3d: bool, size: u32, dmin: [f32; 3], dmax: [f32; 3], rgba: &[f32]) -> u64 { let mut h = DefaultHasher::new(); "ParsedLut".hash(&mut h); is_3d.hash(&mut h); diff --git a/crates/engine/src/eval/layer_ocio.rs b/crates/engine/src/eval/layer_ocio.rs new file mode 100644 index 0000000000000000000000000000000000000000..2a98a56d62c2c9a03221099936ac264a6026d16d --- /dev/null +++ b/crates/engine/src/eval/layer_ocio.rs @@ -0,0 +1,318 @@ +//! OCIO, Layer, Metadata, Generator & Utility built-ins: +//! - `OCIOColorSpace`, `OCIODisplay`, `OCIOFileTransform` +//! - `LayerMuxer`, `LayerRegex`, `LayerRemover`, `Swizzler` +//! - `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC`, `Dummy` +//! - `MultiText`, `Fields`, `KeyStretcher`, `ChromaticAberrationRemoval` +//! +//! Colour tools reuse the `color_lut` colorimetry, transfer-curve and LUT/CDL pipelines; the ops +//! with no existing equivalent live in `layer_ocio.wgsl` (`filterable: false` + `textureLoad`, +//! WriteOnly storage output patched per format, no `read_write` storage textures). + +mod file_transform; +mod layers; +mod ocio; +mod pattern; +mod swizzle_fields; +#[cfg(test)] +mod tests; +mod utility; + +use super::*; +use std::num::NonZeroU64; + +const LAYER_OCIO_WGSL: &str = include_str!("../shaders/layer_ocio.wgsl"); +const LO_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; +const ENTRY_POINTS: [&str; 4] = ["ocio_display_op", "swizzler_op", "fields_op", "chroma_aberration_op"]; + +#[derive(Clone, Copy)] +enum LayerOcioOp { + OcioDisplay, + Swizzler, + Fields, + ChromaAberration, +} + +struct LayerOcioFormatPipelines { + bgl: wgpu::BindGroupLayout, + ops: [wgpu::ComputePipeline; ENTRY_POINTS.len()], +} + +pub(crate) struct LayerOcioPipelines { + uniform_stride: u32, + uniform_chunks: Vec, + uniform_cursor: u32, + by_format: HashMap<(wgpu::TextureFormat, bool), LayerOcioFormatPipelines>, +} + +fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + } +} + +fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String { + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + let mut src = LAYER_OCIO_WGSL.replace( + "texture_storage_2d", + &format!("texture_storage_2d<{storage_fmt}, write>"), + ); + if hdr_float { + src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); + } + src +} + +impl LayerOcioPipelines { + pub(super) fn new(device: &wgpu::Device) -> Self { + let uniform_size = std::mem::size_of::() as u32; + let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); + Self { + uniform_stride: uniform_size.div_ceil(min_align) * min_align, + uniform_chunks: Vec::new(), + uniform_cursor: 0, + by_format: HashMap::new(), + } + } + + pub(super) fn reset_uniform_cursor(&mut self) { + self.uniform_cursor = 0; + } + + pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { + self.uniform_cursor = 0; + self.uniform_chunks.truncate(max_chunks); + } + + fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { + let slot = self.uniform_cursor; + let chunk_idx = (slot / LO_UNIFORM_SLOTS_PER_CHUNK) as usize; + while chunk_idx >= self.uniform_chunks.len() { + self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("layer-ocio-params-ring"), + size: u64::from(LO_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride), + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + let offset = (slot % LO_UNIFORM_SLOTS_PER_CHUNK) * self.uniform_stride; + queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); + self.uniform_cursor = slot + 1; + (chunk_idx, offset) + } + + fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { + if self.by_format.contains_key(&(format, hdr_float)) { + return; + } + let u_size = std::mem::size_of::() as u64; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("layer-ocio-bgl"), + entries: &[ + unfilterable_tex_entry(0), + unfilterable_tex_entry(1), + unfilterable_tex_entry(2), + unfilterable_tex_entry(3), + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(u_size), + }, + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("layer-ocio-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("layer-ocio-wgsl"), + source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()), + }); + let ops = ENTRY_POINTS.map(|entry| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&pl), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }); + self.by_format.insert((format, hdr_float), LayerOcioFormatPipelines { bgl, ops }); + } + + #[allow(clippy::too_many_arguments)] + fn dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + op: LayerOcioOp, + views: [&wgpu::TextureView; 4], + dst: &CachedTexture, + params: &UniformParams, + ) { + let hdr_float = dst.depth.is_float(); + self.ensure_format(device, dst.format, hdr_float); + let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); + let fp = &self.by_format[&(dst.format, hdr_float)]; + let mut entries: Vec = views + .iter() + .enumerate() + .map(|(i, v)| wgpu::BindGroupEntry { binding: i as u32, resource: wgpu::BindingResource::TextureView(v) }) + .collect(); + entries.push(wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }); + entries.push(wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniform_chunks[chunk_idx], + offset: 0, + size: NonZeroU64::new(std::mem::size_of::() as u64), + }), + }); + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("layer-ocio-bg"), + layout: &fp.bgl, + entries: &entries, + }); + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("layer-ocio-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(&fp.ops[op as usize]); + pass.set_bind_group(0, &bg, &[offset]); + pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); + } +} + +/// Blend / EffectMask / Process* state shared by every colour or spatial filter. +struct Effect { + blend: f32, + mbm: bool, + mask: Option, + mask_inv: bool, + skip: [f32; 4], +} + +fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { + keys.iter() + .find(|&&k| node.inputs.contains_key(k)) + .map_or(default, |&k| comp.eval_number(node, k, time, default, expr)) +} + +fn str_any<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { + keys.iter().find_map(|k| node.static_str(k)) +} + +fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option { + ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) +} + +/// Lowercased alphanumerics only, so `"Rec.709 (sRGB)"` matches `"rec709srgb"`. +fn squash(s: &str) -> String { + s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect() +} + +impl Engine { + fn layer_ocio_pipelines(&self) -> &RefCell { + self.layer_ocio.get_or_init(|| RefCell::new(LayerOcioPipelines::new(&self.device))) + } + + /// Resolves `Blend` and the EffectMask for `src`; `Err(src)` when the effect is an identity + /// (`Blend == 0` without `MultiplyByMask`). A masked source is cropped to the canvas so mask UVs line up. + #[allow(clippy::too_many_arguments)] + fn effect_prologue( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + src: CachedTexture, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> Result<(CachedTexture, Effect), CachedTexture> { + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let mbm = self.multiplies_by_mask(comp, node, time); + if blend <= 1e-6 && !mbm { + return Err(src); + } + let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src }; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let skip = self.process_skip(comp, node, time); + Ok((src, Effect { blend, mbm, mask, mask_inv, skip })) + } + + /// Dispatches one `layer_ocio.wgsl` op over `src` (binding 0) with `b` (binding 1, `src` when `None`) + /// and `z` (binding 2, a dummy when `None`); the result keeps `src`'s DoD and aux channels. + #[allow(clippy::too_many_arguments)] + fn run_lo_filter( + &mut self, + node: &Node, + tag: &'static str, + op: LayerOcioOp, + src: &CachedTexture, + b: Option<&CachedTexture>, + z: Option<&wgpu::TextureView>, + fx: &Effect, + depth: BitDepth, + mut u: UniformParams, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + u.p[14] = [fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)]; + u.p[15] = fx.skip; + let b_hash = b.map_or(0, |t| t.content_hash); + let mask_hash = fx.mask.as_ref().map_or(0, |m| m.content_hash); + let key = self.make_key(node, tag, src.size, &[src.content_hash, b_hash, mask_hash, depth as u64], bytemuck::cast_slice(&u.p)); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mut dst = self.alloc_tex_like(src, depth, key); + let views = [ + &src.view, + b.map_or(&src.view, |t| &t.view), + z.unwrap_or(&self.dummy.view), + fx.mask.as_ref().map_or(&self.dummy.view, |m| &m.view), + ]; + self.layer_ocio_pipelines() + .borrow_mut() + .dispatch(&self.device, &self.queue, enc, op, views, &dst, &u); + dst.set_aux(src.aux.clone()); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +fn b2f(v: bool) -> f32 { + if v { 1.0 } else { 0.0 } +} diff --git a/crates/engine/src/eval/layer_ocio/file_transform.rs b/crates/engine/src/eval/layer_ocio/file_transform.rs new file mode 100644 index 0000000000000000000000000000000000000000..7a9dd72b860f0d3be7d98d99daa73bae4a66c278 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/file_transform.rs @@ -0,0 +1,287 @@ +//! `OCIOFileTransform` — `.cube` / `.3dl` LUTs, `.clf` (first `ASC_CDL`, `LUT3D` or `LUT1D` node) and +//! `.cc` / `.ccc` / `.cdl` CDL files, applied through the `FileLUT` and `OCIOCDLTransform` GPU ops. + +use super::*; +use crate::eval::color_lut::ColorLutOp; +use crate::eval::color_lut::color_fx::parse_cdl_xml; +use crate::eval::color_lut::lut_io::{ParsedLut, hash_lut_data, load_lut_from_spec, pack_3d_lut_rgba}; + +const INVERSE_ITERATIONS: usize = 12; + +enum FileTransform { + Lut(ParsedLut), + Cdl { slope: [f32; 3], offset: [f32; 3], power: [f32; 3], sat: f32, reverse: bool }, +} + +fn xml_attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let rest = &tag[tag.find(&format!("{name}=\""))? + name.len() + 2..]; + Some(&rest[..rest.find('"')?]) +} + +/// Scale taking a CLF integer bit-depth attribute (`"10i"`) to normalized floats; float depths are 1. +fn bit_depth_scale(depth: Option<&str>) -> f32 { + match depth.and_then(|d| d.strip_suffix('i')).and_then(|d| d.parse::().ok()) { + Some(bits) => 1.0 / ((1_u64 << bits.min(32)) - 1) as f32, + None => 1.0, + } +} + +fn clf_lut(text: &str) -> Option { + let (is_3d, open) = match (text.find(" (true, i), + (None, Some(i)) => (false, i), + _ => return None, + }; + let node = &text[open..]; + let tag = &node[..node.find('>')?]; + let array = &node[node.find("')?]; + let body = &array[array_tag.len() + 1..array.find("")?]; + let scale = bit_depth_scale(xml_attr(tag, "outBitDepth")); + let values: Vec = body.split_whitespace().filter_map(|t| t.parse::().ok()).map(|v| v * scale).collect(); + let dim: Vec = xml_attr(array_tag, "dim")?.split_whitespace().filter_map(|t| t.parse().ok()).collect(); + if is_3d { + let n = *dim.first()?; + if dim.len() < 4 || values.len() != n * n * n * 3 { + return None; + } + // CLF varies B fastest; the packed layout varies R fastest. + let mut entries = vec![[0.0_f32; 3]; n * n * n]; + for (i, rgb) in values.chunks_exact(3).enumerate() { + let (r, g, b) = (i / (n * n), (i / n) % n, i % n); + entries[r + n * (g + n * b)] = [rgb[0], rgb[1], rgb[2]]; + } + lut_3d(n as u32, [0.0; 3], [1.0; 3], &entries) + } else { + let n = *dim.first()?; + let channels = *dim.get(1)?; + if n < 2 || (channels != 1 && channels != 3) || values.len() != n * channels { + return None; + } + let rows: Vec<[f32; 3]> = values + .chunks_exact(channels) + .map(|v| if channels == 1 { [v[0]; 3] } else { [v[0], v[1], v[2]] }) + .collect(); + Some(lut_1d([0.0; 3], [1.0; 3], &rows)) + } +} + +fn lut_3d(n: u32, dmin: [f32; 3], dmax: [f32; 3], entries: &[[f32; 3]]) -> Option { + let (tiles_x, tex_size, rgba_f32) = pack_3d_lut_rgba(n, entries).ok()?; + let content_hash = hash_lut_data(true, n, dmin, dmax, &rgba_f32); + Some(ParsedLut { is_3d: true, size: n, tiles_x, tex_size, domain_min: dmin, domain_max: dmax, rgba_f32, content_hash }) +} + +fn lut_1d(dmin: [f32; 3], dmax: [f32; 3], rows: &[[f32; 3]]) -> ParsedLut { + let n = rows.len() as u32; + let rgba_f32: Vec = rows.iter().flat_map(|[r, g, b]| [*r, *g, *b, 1.0]).collect(); + let content_hash = hash_lut_data(false, n, dmin, dmax, &rgba_f32); + ParsedLut { is_3d: false, size: n, tiles_x: 1, tex_size: [n, 1], domain_min: dmin, domain_max: dmax, rgba_f32, content_hash } +} + +fn cdl_from_xml(text: &str, ccc_id: &str) -> Option { + let (slope, offset, power, sat) = parse_cdl_xml(text, ccc_id)?; + let reverse = text.find("').unwrap_or(0)]; + xml_attr(tag, "style").is_some_and(|s| s.to_ascii_lowercase().starts_with("rev")) + }); + Some(FileTransform::Cdl { slope, offset, power, sat, reverse }) +} + +/// Loads `spec` as inline text or a file path; `None` when empty, unreadable or unsupported. +fn load_file_transform(spec: &str, ccc_id: &str) -> Option { + let spec = spec.trim(); + let lower = spec.to_ascii_lowercase(); + let xml_ext = [".clf", ".ctf", ".cc", ".ccc", ".cdl"].iter().any(|e| lower.ends_with(e)); + if !xml_ext && !spec.starts_with('<') { + return load_lut_from_spec(spec).map(FileTransform::Lut); + } + let text = if spec.starts_with('<') { + spec.to_owned() + } else { + #[cfg(not(target_arch = "wasm32"))] + { + std::fs::read_to_string(spec).ok()? + } + #[cfg(target_arch = "wasm32")] + { + return None; + } + }; + if text.contains("") { + return cdl_from_xml(&text, ccc_id); + } + clf_lut(&text).map(FileTransform::Lut) +} + +fn sample_lut_3d(l: &ParsedLut, rgb: [f32; 3]) -> [f32; 3] { + let n = l.size as usize; + let at = |r: usize, g: usize, b: usize| { + let (tx, ty) = (b % l.tiles_x as usize, b / l.tiles_x as usize); + let i = ((ty * n + g) * l.tex_size[0] as usize + tx * n + r) * 4; + [l.rgba_f32[i], l.rgba_f32[i + 1], l.rgba_f32[i + 2]] + }; + let pos: [f32; 3] = std::array::from_fn(|c| { + ((rgb[c] - l.domain_min[c]) / (l.domain_max[c] - l.domain_min[c]).max(1e-6)).clamp(0.0, 1.0) * (n - 1) as f32 + }); + let i0: [usize; 3] = pos.map(|p| (p.floor() as usize).min(n - 2)); + let f: [f32; 3] = std::array::from_fn(|c| pos[c] - i0[c] as f32); + let mut out = [0.0_f32; 3]; + for corner in 0..8 { + let (dr, dg, db) = (corner & 1, (corner >> 1) & 1, corner >> 2); + let w = [dr, dg, db].iter().zip(f).map(|(&d, f)| if d == 1 { f } else { 1.0 - f }).product::(); + let v = at(i0[0] + dr, i0[1] + dg, i0[2] + db); + for c in 0..3 { + out[c] += w * v[c]; + } + } + out +} + +/// Inverts `l` over its own domain: 3D by fixed-point iteration on the forward lookup, 1D by a +/// monotone (non-decreasing) per-channel search. `None` for degenerate LUTs. +fn invert_lut(l: &ParsedLut) -> Option { + let n = l.size as usize; + if n < 2 { + return None; + } + let (dmin, dmax) = (l.domain_min, l.domain_max); + let node = |i: usize, c: usize| dmin[c] + i as f32 / (n - 1) as f32 * (dmax[c] - dmin[c]); + if l.is_3d { + let mut entries = vec![[0.0_f32; 3]; n * n * n]; + for (idx, entry) in entries.iter_mut().enumerate() { + let target = [node(idx % n, 0), node((idx / n) % n, 1), node(idx / (n * n), 2)]; + let mut x = target; + for _ in 0..INVERSE_ITERATIONS { + let fx = sample_lut_3d(l, x); + x = std::array::from_fn(|c| (x[c] + target[c] - fx[c]).clamp(dmin[c], dmax[c])); + } + *entry = x; + } + return lut_3d(l.size, dmin, dmax, &entries); + } + let mut rows = vec![[0.0_f32; 3]; n]; + for c in 0..3 { + let forward: Vec = (0..n).map(|i| l.rgba_f32[i * 4 + c]).collect(); + for (j, row) in rows.iter_mut().enumerate() { + let y = node(j, c); + let hi = forward.partition_point(|&v| v < y).clamp(1, n - 1); + let (a, b) = (forward[hi - 1], forward[hi]); + let t = if (b - a).abs() > 1e-9 { ((y - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 }; + row[c] = node(hi - 1, c) + t * (node(hi, c) - node(hi - 1, c)); + } + } + Some(lut_1d(dmin, dmax, &rows)) +} + +fn parse_interpolation(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { + match str_any(node, &["Interpolation"]).map(squash).as_deref() { + Some("nearest") => 2.0, + Some("linear" | "trilinear") => 1.0, + Some(_) => 0.0, + None if node.inputs.contains_key("Interpolation") => { + match comp.eval_number(node, "Interpolation", time, 1.0, expr).round() as i32 { + 0 => 1.0, + 2 => 2.0, + _ => 0.0, + } + } + None => 0.0, + } +} + +impl Engine { + /// `OCIOFileTransform` — applies `File` (`Direction` Forward/Inverse, `Interpolation` Linear/Tetrahedral/Nearest). + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_ocio_file_transform( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let masked = fx.mbm && fx.mask.is_some(); + let file_key = ["File", "FileName", "LUTFile"].into_iter().find(|k| node.inputs.contains_key(*k)).unwrap_or("File"); + let spec = comp.eval_text(node, file_key, time, "", &self.expr); + let ccc_id = comp.eval_text(node, "CCCID", time, "", &self.expr); + let inverse = match str_any(node, &["Direction"]).map(squash).as_deref() { + Some(d) => matches!(d, "inverse" | "reverse" | "backward"), + None => comp.eval_number(node, "Direction", time, 0.0, &self.expr) > 0.5, + }; + let Some(transform) = load_file_transform(&spec, &ccc_id) else { + return if masked { self.mask_only(node, &src, &fx, frame_i, enc, stats) } else { src }; + }; + let mask_flags = [b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)]; + + match transform { + FileTransform::Cdl { slope, offset, power, sat, reverse } => { + let mut u = UniformParams::default(); + u.p[0] = [slope[0], slope[1], slope[2], sat]; + u.p[1] = [offset[0], offset[1], offset[2], b2f(inverse != reverse)]; + u.p[2] = [power[0], power[1], power[2], fx.blend]; + u.p[3] = [mask_flags[0], mask_flags[1], mask_flags[2], 0.0]; + u.p[4] = fx.skip; + self.run_cl_filter(node, "OCIOFileCDL", ColorLutOp::OcioCdl, &src, None, fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats) + } + FileTransform::Lut(lut) => { + let Some(lut) = (if inverse { invert_lut(&lut) } else { Some(lut) }) else { + return src; + }; + let mut u = UniformParams::default(); + u.p[0] = [lut.domain_min[0], lut.domain_min[1], lut.domain_min[2], if lut.is_3d { 3.0 } else { 1.0 }]; + u.p[1] = [lut.domain_max[0], lut.domain_max[1], lut.domain_max[2], lut.size as f32]; + u.p[2] = [lut.tiles_x as f32, 1.0, 1.0, 1.0]; + u.p[4] = [fx.blend, mask_flags[0], mask_flags[1], mask_flags[2]]; + u.p[5] = fx.skip; + u.p[6] = [0.0, parse_interpolation(comp, node, time, &self.expr), 0.0, 0.0]; + let view = self + .color_lut_pipelines() + .borrow_mut() + .get_or_upload_lut_rgba32f(&self.device, &self.queue, lut.content_hash, lut.tex_size, &lut.rgba_f32); + self.run_cl_filter(node, "OCIOFileLUT", ColorLutOp::FileLut, &src, Some((&view, lut.content_hash)), fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn invert_lut_undoes_3d_and_1d_tables() { + let n = 5; + let node = |i: usize| i as f32 / (n - 1) as f32; + let entries: Vec<[f32; 3]> = (0..n * n * n) + .map(|i| [i % n, (i / n) % n, i / (n * n)].map(|c| 0.5 * node(c) + 0.1)) + .collect(); + let forward = lut_3d(n as u32, [0.0; 3], [1.0; 3], &entries).unwrap(); + let inverse = invert_lut(&forward).unwrap(); + for x in [0.4_f32, 0.6] { + let back = sample_lut_3d(&inverse, sample_lut_3d(&forward, [x, x, x])); + assert!(back.iter().all(|b| (b - x).abs() < 0.01), "3D inverse of {x}: {back:?}"); + } + + let squares: Vec<[f32; 3]> = (0..n).map(|i| [node(i) * node(i); 3]).collect(); + let inverse_1d = invert_lut(&lut_1d([0.0; 3], [1.0; 3], &squares)).unwrap(); + assert!((inverse_1d.rgba_f32[4] - 0.5).abs() < 1e-6, "1D inverse of 0.25 is 0.5"); + } + + #[test] + fn clf_attrs_and_bit_depths() { + assert_eq!(xml_attr("", "outBitDepth"), Some("10i")); + assert_eq!(bit_depth_scale(Some("10i")), 1.0 / 1023.0); + assert_eq!(bit_depth_scale(Some("32f")), 1.0); + } +} diff --git a/crates/engine/src/eval/layer_ocio/layers.rs b/crates/engine/src/eval/layer_ocio/layers.rs new file mode 100644 index 0000000000000000000000000000000000000000..c6cf6d4d486ac76716759c79147a5ead467bd2c3 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/layers.rs @@ -0,0 +1,135 @@ +//! `LayerMuxer`, `LayerRegex`, `LayerRemover` and the lossless passthroughs `Dummy`, +//! `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC` (textures carry no metadata, so RGBA, DoD and aux pass through). + +use super::pattern::is_match; +use super::*; +use crate::cache::AuxChannels; +use std::sync::Arc; + +/// Aux channel names as matched by `LayerRegex` / `LayerRemover` patterns, with their `Kill*` input. +const AUX_LAYERS: [(&str, &str); 4] = [("Z", "KillZ"), ("Normal", "KillNormal"), ("Vector", "KillVector"), ("BackVector", "KillBackVector")]; + +fn aux_slots(aux: &mut AuxChannels) -> [&mut Option; 4] { + [&mut aux.z, &mut aux.normal, &mut aux.vector, &mut aux.back_vector] +} + +/// `tex` with `aux` swapped in under a content hash that reflects the change. +fn with_aux(tex: &CachedTexture, aux: AuxChannels, salt: &impl Hash) -> CachedTexture { + let mut out = tex.clone(); + out.set_aux(Some(Arc::new(aux))); + let mut h = DefaultHasher::new(); + tex.content_hash.hash(&mut h); + salt.hash(&mut h); + out.content_hash = h.finish(); + out +} + +fn mux_ports() -> impl Iterator { + ["Background", "Input"] + .into_iter() + .map(str::to_owned) + .chain((1..=16).flat_map(|n| [format!("Input{n}"), format!("Foreground{n}")])) + .chain(std::iter::once("Foreground".to_owned())) +} + +impl Engine { + /// `Dummy`, `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC`: the first connected input unchanged (a transparent + /// canvas when none is). `MetadataInput` and the timecode fields are not evaluated. + pub(in crate::eval) fn eval_passthrough( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + match conn_any(comp, node, &["Input", "Image", "Background", "Source"]) { + Some(id) => self.eval_node(comp, id, time, enc, visiting, stats), + None => self.dummy.clone(), + } + } + + /// `LayerMuxer` — RGBA from the first connected input (`Background`, `Input1..`, `Foreground1..`); + /// each aux channel the main input lacks comes from the first later input of identical DoD that has it. + pub(in crate::eval) fn eval_layer_muxer( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let mut inputs = mux_ports() + .filter_map(|p| node.connected_node(&p).and_then(|s| comp.find_node(s))) + .collect::>(); + inputs.dedup(); + let mut layers = inputs.into_iter().map(|id| self.eval_node(comp, id, time, enc, visiting, stats)); + let Some(main) = layers.next() else { + return self.dummy.clone(); + }; + let mut aux = main.aux_cloned(); + let mut donors = Vec::new(); + for layer in layers.filter(|l| l.size == main.size && l.origin == main.origin) { + let Some(other) = layer.aux.as_deref() else { continue }; + let mut other = other.clone(); + let mut taken = false; + for (slot, donor) in aux_slots(&mut aux).into_iter().zip(aux_slots(&mut other)) { + if slot.is_none() && donor.is_some() { + *slot = donor.take(); + taken = true; + } + } + if taken { + donors.push(layer.content_hash); + } + } + if donors.is_empty() { + return main; + } + with_aux(&main, aux, &("LayerMuxer", donors)) + } + + /// `LayerRegex` keeps the aux channels whose name matches `Pattern` (all when empty; `Invert` flips the + /// selection); `LayerRemover` drops those matching `Layers` plus any `Kill*` toggle. RGBA is never touched. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_layer_filter( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + remove: bool, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let Some(src_aux) = src.aux.as_deref() else { + return src; + }; + let pattern = if remove { + comp.eval_text(node, "Layers", time, "", &self.expr) + } else { + comp.eval_text(node, "Pattern", time, ".*", &self.expr) + }; + let invert = !remove && comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5; + let mut aux = src_aux.clone(); + let mut dropped = Vec::new(); + for ((name, kill), slot) in AUX_LAYERS.into_iter().zip(aux_slots(&mut aux)) { + let matched = !pattern.is_empty() && is_match(&pattern, name); + let killed = remove && (matched || comp.eval_number(node, kill, time, 0.0, &self.expr) > 0.5); + let keep = if remove { !killed } else { (pattern.is_empty() || matched) != invert }; + if !keep && slot.take().is_some() { + dropped.push(name); + } + } + if dropped.is_empty() { + return src; + } + with_aux(&src, aux, &(&node.kind, dropped)) + } +} diff --git a/crates/engine/src/eval/layer_ocio/ocio.rs b/crates/engine/src/eval/layer_ocio/ocio.rs new file mode 100644 index 0000000000000000000000000000000000000000..33d041fea9312ad8a6d0cf75a0a3e655ed530a74 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/ocio.rs @@ -0,0 +1,247 @@ +//! `OCIOColorSpace` and `OCIODisplay`, built on the `ColorSpaceTransform` colorimetry and transfer curves. + +use super::*; +use crate::eval::color_lut::ColorLutOp; +use crate::eval::color_lut::colorimetry::{ + CatMethod, P_AP0, P_AP1, P_AWG3, P_AWG4, P_DWG, P_P3_D60, P_P3_D65, P_P3_DCI, P_REC709, P_REC2020, P_RWG, + P_SGAMUT3, P_SGAMUT3_CINE, Primaries, parse_color_space, parse_gamma_id, rgb_to_rgb_matrix, +}; +use std::sync::Arc; + +/// An OCIO color space as `(gamut, transfer id)`; `gamut == None` is CIE XYZ. +type SpaceDef = (Option, i32); + +/// Resolves an OCIO space name onto the `ColorSpaceTransform` vocabulary; `None` for `Raw`/data spaces. +fn ocio_space(name: &str) -> Option { + let s = squash(name); + if s == "raw" || s.contains("data") || s.contains("passthrough") { + return None; + } + let gamut = if s.contains("acescc") || s.contains("acescg") || s.contains("ap1") { + Some(P_AP1) + } else if s.contains("aces") || s.contains("ap0") { + Some(P_AP0) + } else if s.contains("logc4") || s.contains("awg4") { + Some(P_AWG4) + } else if s.contains("logc") || s.contains("alexa") || s.contains("awg") { + Some(P_AWG3) + } else if s.contains("slog") || s.contains("sgamut") { + Some(if s.contains("cine") { P_SGAMUT3_CINE } else { P_SGAMUT3 }) + } else if s.contains("log3g10") || s.contains("rwg") || s.contains("redwidegamut") { + Some(P_RWG) + } else if s.contains("davinci") || s.contains("dwg") { + Some(P_DWG) + } else { + parse_color_space(Some(name)) + }; + let xfer = if s.starts_with("linear") || s == "lin" { + 0 + } else if s.contains("intermediate") { + 15 + } else if s.contains("displayp3") || s.contains("srgb") { + 1 + } else { + parse_gamma_id(Some(&s)) + }; + Some((gamut, xfer)) +} + +/// `ColorSpaceTransform` shader parameters taking `from`-encoded RGB to `to`-encoded RGB. +struct Cst { + m: [[f32; 3]; 3], + in_xfer: i32, + out_xfer: i32, +} + +impl Cst { + /// `None` when the conversion is an identity. + fn between(from: SpaceDef, to: SpaceDef) -> Option { + let m = rgb_to_rgb_matrix(from.0, to.0, true, CatMethod::Bradford); + let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + (m != identity || from.1 != to.1).then_some(Self { m, in_xfer: from.1, out_xfer: to.1 }) + } + + fn uniforms(&self, fx: Option<&Effect>) -> UniformParams { + let mut u = UniformParams::default(); + for (row, m) in u.p.iter_mut().zip(&self.m) { + *row = [m[0], m[1], m[2], 0.0]; + } + u.p[3] = [self.in_xfer as f32, self.out_xfer as f32, 0.0, 0.0]; + u.p[4] = [100.0, 100.0, 0.9, 1.0]; + u.p[5] = [1.0, 1.0, 0.0, 0.0]; + if let Some(fx) = fx { + u.p[5] = [1.0, fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv)]; + u.p[6] = [b2f(fx.mbm), 0.0, 0.0, 0.0]; + u.p[7] = fx.skip; + } + u + } +} + +/// Display gamut and curve id (see `ocio_display_op`) plus whether the device implies an ACES view. +fn parse_display_device(device: &str) -> (Primaries, i32, bool) { + let s = squash(device); + let aces = s.contains("aces"); + let (gamut, curve) = if s.contains("2100") && s.contains("hlg") { + (P_REC2020, 6) + } else if s.contains("2100") || s.contains("pq") { + (P_REC2020, 5) + } else if s.contains("displayp3") { + (P_P3_D65, 1) + } else if s.contains("p3") { + let gamut = if s.contains("dci") { + P_P3_DCI + } else if s.contains("d60") { + P_P3_D60 + } else { + P_P3_D65 + }; + (gamut, 4) + } else if s.contains("2020") { + (P_REC2020, 3) + } else if s.contains("709") || s.contains("1886") { + (P_REC709, 3) + } else { + (P_REC709, 1) + }; + (gamut, curve, aces) +} + +fn parse_view_transform(view: Option<&str>, aces_device: bool) -> i32 { + match view.map(squash).as_deref() { + Some(v) if v.contains("aces") || v.contains("filmic") => 1, + Some(v) if v.contains("reinhard") => 2, + Some(v) if !v.is_empty() => 0, + _ => i32::from(aces_device), + } +} + +impl Engine { + /// Dispatches one `color_lut` op over `src` with an optional packed LUT texture (binding 1), + /// caching the result under a key of its inputs; the result keeps `src`'s DoD and aux channels. + #[allow(clippy::too_many_arguments)] + pub(super) fn run_cl_filter( + &mut self, + node: &Node, + tag: &'static str, + op: ColorLutOp, + src: &CachedTexture, + lut: Option<(&Arc, u64)>, + mask: Option<&CachedTexture>, + u: &UniformParams, + depth: BitDepth, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let lut_hash = lut.map_or(0, |l| l.1); + let mask_hash = mask.map_or(0, |m| m.content_hash); + let key = self.make_key(node, tag, src.size, &[src.content_hash, mask_hash, lut_hash, depth as u64], bytemuck::cast_slice(&u.p)); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mut dst = self.alloc_tex_like(src, depth, key); + let views = [ + &*src.view, + lut.map_or(&*self.dummy.view, |l| &**l.0), + &*self.dummy.view, + mask.map_or(&*self.dummy.view, |m| &*m.view), + ]; + self.dispatch_cl(enc, op, views, &dst, u); + dst.set_aux(src.aux.clone()); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + /// `OCIOColorSpace` — converts between named OCIO color spaces (`SourceSpace` -> `OutputSpace`). + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_ocio_color_space( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let from = ocio_space(str_any(node, &["SourceSpace", "InputSpace"]).unwrap_or("scene_linear")); + let to = ocio_space(str_any(node, &["OutputSpace", "DestSpace"]).unwrap_or("scene_linear")); + let cst = from.zip(to).and_then(|(from, to)| Cst::between(from, to)); + let Some(cst) = cst else { + return if fx.mbm && fx.mask.is_some() { self.mask_only(node, &src, &fx, frame_i, enc, stats) } else { src }; + }; + let depth = self.node_depth(comp, node, time, Some(src.depth)); + let u = cst.uniforms(Some(&fx)); + self.run_cl_filter(node, "OCIOColorSpace", ColorLutOp::ColorSpaceTransform, &src, None, fx.mask.as_ref(), &u, depth, frame_i, enc, stats) + } + + /// `MultiplyByMask` on an identity transform: zeroes outside the EffectMask via the `FileLUT` identity path. + pub(super) fn mask_only( + &mut self, + node: &Node, + src: &CachedTexture, + fx: &Effect, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let mut u = UniformParams::default(); + u.p[2] = [1.0, 1.0, 1.0, 1.0]; + u.p[4] = [fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)]; + u.p[5] = fx.skip; + self.run_cl_filter(node, "OCIOIdentityMask", ColorLutOp::FileLut, src, None, fx.mask.as_ref(), &u, src.depth, frame_i, enc, stats) + } + + /// `OCIODisplay` — `InputSpace` -> display gamut, then exposure, view transform, display curve and post gamma. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_ocio_display( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let (gamut, curve, aces_device) = parse_display_device(str_any(node, &["DisplayDevice", "Display"]).unwrap_or("sRGB")); + let view = parse_view_transform(str_any(node, &["ViewTransform", "View"]), aces_device); + let exposure = comp.eval_number(node, "Exposure", time, 0.0, &self.expr); + let gamma = comp.eval_number(node, "Gamma", time, 1.0, &self.expr).max(1e-3); + let depth = self.node_depth(comp, node, time, Some(src.depth)); + + let from = ocio_space(str_any(node, &["InputSpace", "SourceSpace"]).unwrap_or("scene_linear")); + let linear_depth = if depth.is_float() { depth } else { BitDepth::Float16 }; + let lin = match from.and_then(|from| Cst::between(from, (Some(gamut), 0))) { + Some(cst) => { + self.run_cl_filter(node, "OCIODisplayInput", ColorLutOp::ColorSpaceTransform, &src, None, None, &cst.uniforms(None), linear_depth, frame_i, enc, stats) + } + None => src.clone(), + }; + + let mut u = UniformParams::default(); + u.p[0] = [2f64.powf(exposure) as f32, (1.0 / gamma) as f32, curve as f32, view as f32]; + let tex_b = &src; + self.run_lo_filter(node, "OCIODisplay", LayerOcioOp::OcioDisplay, &lin, Some(tex_b), None, &fx, depth, u, frame_i, enc, stats) + } +} diff --git a/crates/engine/src/eval/layer_ocio/pattern.rs b/crates/engine/src/eval/layer_ocio/pattern.rs new file mode 100644 index 0000000000000000000000000000000000000000..b33e61d2a94cb49d6ec0531397d62229e4a92de9 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/pattern.rs @@ -0,0 +1,139 @@ +//! Minimal case-insensitive regex subset for layer names: literals, `.`, `[...]` classes (ranges, `^` +//! negation), `\` escapes, `*` `+` `?` quantifiers, top-level `|`, and `^` / `$` anchors. +//! Unanchored patterns match anywhere in the name. + +enum Atom { + Any, + Lit(char), + Class { ranges: Vec<(char, char)>, negated: bool }, +} + +struct Token { + atom: Atom, + min: usize, + max: usize, +} + +struct Branch { + start_anchored: bool, + end_anchored: bool, + tokens: Vec, +} + +impl Atom { + fn matches(&self, c: char) -> bool { + match self { + Atom::Any => true, + Atom::Lit(l) => *l == c, + Atom::Class { ranges, negated } => ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&c)) != *negated, + } + } +} + +fn parse_branch(pattern: &str) -> Branch { + let chars: Vec = pattern.to_lowercase().chars().collect(); + let (mut i, mut tokens) = (0, Vec::new()); + let start_anchored = chars.first() == Some(&'^'); + i += usize::from(start_anchored); + let escaped_dollar = chars.len() >= 2 && chars[chars.len() - 2] == '\\'; + let end_anchored = chars.len() > i && chars.last() == Some(&'$') && !escaped_dollar; + let end = chars.len() - usize::from(end_anchored); + while i < end { + let atom = match chars[i] { + '.' => Atom::Any, + '\\' if i + 1 < end => { + i += 1; + Atom::Lit(chars[i]) + } + '[' => { + let mut j = i + 1; + let negated = chars.get(j) == Some(&'^'); + j += usize::from(negated); + let mut ranges = Vec::new(); + while j < end && chars[j] != ']' { + let lo = chars[j]; + if chars.get(j + 1) == Some(&'-') && j + 2 < end && chars[j + 2] != ']' { + ranges.push((lo, chars[j + 2])); + j += 3; + } else { + ranges.push((lo, lo)); + j += 1; + } + } + i = j; + Atom::Class { ranges, negated } + } + c => Atom::Lit(c), + }; + i += 1; + let (min, max) = match chars.get(i).filter(|_| i < end) { + Some('*') => (0, usize::MAX), + Some('+') => (1, usize::MAX), + Some('?') => (0, 1), + _ => (1, 1), + }; + if (min, max) != (1, 1) { + i += 1; + } + tokens.push(Token { atom, min, max }); + } + Branch { start_anchored, end_anchored, tokens } +} + +fn match_from(tokens: &[Token], text: &[char], end_anchored: bool) -> bool { + let Some((tok, rest)) = tokens.split_first() else { + return !end_anchored || text.is_empty(); + }; + let available = text.iter().take(tok.max).take_while(|&&c| tok.atom.matches(c)).count(); + (tok.min..=available).rev().any(|n| match_from(rest, &text[n..], end_anchored)) +} + +/// True when any `|` alternative of `pattern` matches `text`. +pub(super) fn is_match(pattern: &str, text: &str) -> bool { + let text: Vec = text.to_lowercase().chars().collect(); + split_alternatives(pattern).into_iter().any(|alt| { + let branch = parse_branch(alt); + let last_start = if branch.start_anchored { 0 } else { text.len() }; + (0..=last_start).any(|s| match_from(&branch.tokens, &text[s..], branch.end_anchored)) + }) +} + +fn split_alternatives(pattern: &str) -> Vec<&str> { + let (mut parts, mut start, mut escaped, mut in_class) = (Vec::new(), 0, false, false); + for (i, c) in pattern.char_indices() { + match c { + _ if escaped => escaped = false, + '\\' => escaped = true, + '[' => in_class = true, + ']' => in_class = false, + '|' if !in_class => { + parts.push(&pattern[start..i]); + start = i + 1; + } + _ => {} + } + } + parts.push(&pattern[start..]); + parts +} + +#[cfg(test)] +mod tests { + use super::is_match; + + #[test] + fn subset_semantics() { + assert!(is_match(".*", "Normal")); + assert!(is_match("^z$", "Z")); + assert!(!is_match("^z$", "BackZ")); + assert!(is_match("vec", "BackVector")); + assert!(!is_match("^vec", "BackVector")); + assert!(is_match("^vector$", "Vector")); + assert!(is_match("^z$|^normal$", "Normal")); + assert!(!is_match("^z$|^normal$", "Vector")); + assert!(is_match("^[a-c]+x$", "abcx")); + assert!(!is_match("^[^a-c]+x$", "abcx")); + assert!(is_match("^back?vector$", "BackVector")); + assert!(is_match("^ba?ck?vector$", "bcvector")); + } +} diff --git a/crates/engine/src/eval/layer_ocio/swizzle_fields.rs b/crates/engine/src/eval/layer_ocio/swizzle_fields.rs new file mode 100644 index 0000000000000000000000000000000000000000..924c56e8adc18831d2243137e890cbd31d8c02a4 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/swizzle_fields.rs @@ -0,0 +1,162 @@ +//! `Swizzler`, `Fields` and `ChromaticAberrationRemoval` — the `layer_ocio.wgsl` spatial/channel filters. + +use super::*; + +/// Swizzler channel selector id (see `swizzle_channel` in the shader): `Red`..`Alpha`, `Zero`, `One`, +/// `Luminance`, `Z`; a `Secondary` prefix reads the second input, `Inverted` flips the result (ids 12+). +fn swizzle_source(node: &Node, comp: &Comp, key: &str, default: f64, time: f64, expr: &ExprEngine) -> f32 { + let Some(name) = str_any(node, &[key]) else { + return comp.eval_number(node, key, time, default, expr).round().clamp(0.0, 23.0) as f32; + }; + let mut s = squash(name); + let mut offset = 0; + if let Some(rest) = ["inverted", "invert", "inv"].iter().find_map(|p| s.strip_prefix(p)) { + s = rest.to_owned(); + offset = 12; + } + let secondary = ["secondary", "background", "input2", "bg"].iter().find_map(|p| s.strip_prefix(p).map(str::to_owned)); + let channel = secondary.as_deref().unwrap_or(&s); + let id = match channel { + "red" | "r" => 0, + "green" | "g" => 1, + "blue" | "b" => 2, + "alpha" | "a" => 3, + "zero" | "0" | "black" => 4, + "one" | "1" | "white" => 5, + "luminance" | "luma" | "y" => 6, + "z" | "depth" => 7, + _ => default as i32, + }; + // Secondary-input channels only exist for R, G, B, A (ids 8..=11). + let id = if secondary.is_some() && id <= 3 { id + 8 } else { id }; + (id + offset) as f32 +} + +fn enum_id(comp: &Comp, node: &Node, key: &str, names: &[&str], default: f64, time: f64, expr: &ExprEngine) -> i32 { + match str_any(node, &[key]).map(squash) { + Some(s) => names.iter().position(|n| s.contains(n)).unwrap_or(0) as i32, + None => comp.eval_number(node, key, time, default, expr).round().clamp(0.0, (names.len() - 1) as f64) as i32, + } +} + +impl Engine { + /// `Swizzler` — each output channel picks a source channel (`Red`/`Green`/`Blue`/`Alpha` inputs). + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_swizzler( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let sources = [("Red", 0.0), ("Green", 1.0), ("Blue", 2.0), ("Alpha", 3.0)] + .map(|(key, default)| swizzle_source(node, comp, key, default, time, &self.expr)); + if sources == [0.0, 1.0, 2.0, 3.0] && !(fx.mbm && fx.mask.is_some()) { + return src; + } + let second = conn_any(comp, node, &["Input2", "Secondary", "Background", "Foreground"]) + .map(|id| self.eval_node(comp, id, time, enc, visiting, stats)); + let z = src.aux.as_ref().and_then(|a| a.z.as_ref()).map(|z| z.view.clone()); + let depth = self.node_depth(comp, node, time, Some(src.depth)); + let mut u = UniformParams::default(); + u.p[0] = sources; + u.p[1][0] = b2f(z.is_some()); + self.run_lo_filter(node, "Swizzler", LayerOcioOp::Swizzler, &src, second.as_ref(), z.as_deref(), &fx, depth, u, frame_i, enc, stats) + } + + /// `Fields` — `Operation` Deinterlace / Interlace / SwapFields / StripFields over `FieldOrder` line parity. + /// `Interlace` weaves in `Input2` (or `Input` at the next frame) as the second field. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_fields( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let e = &self.expr; + // `deint` precedes `interlace` so "Deinterlace" is not read as "Interlace". + let operation = match str_any(node, &["Operation"]).map(squash) { + Some(s) => ["deint", "interlace", "swap", "strip"].iter().position(|n| s.contains(n)).unwrap_or(0) as i32, + None => comp.eval_number(node, "Operation", time, 0.0, e).round().clamp(0.0, 3.0) as i32, + }; + let method = enum_id(comp, node, "Method", &["blend", "interp", "dup"], 0.0, time, e); + let parity = enum_id(comp, node, "FieldOrder", &["odd", "even"], 0.0, time, e); + let second = if operation == 1 { + Some(match conn_any(comp, node, &["Input2", "Foreground"]) { + Some(id) => self.eval_node(comp, id, time, enc, visiting, stats), + None => { + let next = (time + 1.0).min(comp.global_range[1].max(comp.global_range[0]) as f64).max(time); + self.eval_node(comp, src_id, next, enc, visiting, stats) + } + }) + } else { + None + }; + let second = second.map(|s| self.crop_to_canvas(enc, s)); + let depth = self.node_depth(comp, node, time, Some(src.depth)); + let mut u = UniformParams::default(); + u.p[0] = [operation as f32, method as f32, parity as f32, b2f(second.is_some())]; + self.run_lo_filter(node, "Fields", LayerOcioOp::Fields, &src, second.as_ref(), None, &fx, depth, u, frame_i, enc, stats) + } + + /// `ChromaticAberrationRemoval` — radially rescales R/G/B about `Center` (scale = `*Scale` + 0.01 * `RedCyan` + /// / `GreenMagenta` / `BlueYellow`) and desaturates colour fringes by `Defringe`. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_chromatic_aberration_removal( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let (src, fx) = match self.effect_prologue(comp, node, time, src, enc, visiting, stats) { + Ok(v) => v, + Err(src) => return src, + }; + let e = &self.expr; + let channel = |shift: &str, scale: &str| { + (num_any(comp, node, &[scale], time, 1.0, e) + 0.01 * num_any(comp, node, &[shift], time, 0.0, e)) as f32 + }; + let scales = [channel("RedCyan", "RedScale"), channel("GreenMagenta", "GreenScale"), channel("BlueYellow", "BlueScale")]; + let defringe = comp.eval_number(node, "Defringe", time, 0.0, e).max(0.0) as f32; + if scales.iter().all(|s| (s - 1.0).abs() < 1e-7) && defringe <= 1e-6 && !(fx.mbm && fx.mask.is_some()) { + return src; + } + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], e); + let depth = self.node_depth(comp, node, time, Some(src.depth)); + let mut u = UniformParams::default(); + u.p[0] = [scales[0], scales[1], scales[2], defringe]; + u.p[1] = [center[0] as f32, 1.0 - center[1] as f32, 0.0, 0.0]; + self.run_lo_filter(node, "ChromaticAberrationRemoval", LayerOcioOp::ChromaAberration, &src, None, None, &fx, depth, u, frame_i, enc, stats) + } +} diff --git a/crates/engine/src/eval/layer_ocio/tests.rs b/crates/engine/src/eval/layer_ocio/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..345c70627614dd42b806aa5111314b473fe59f4a --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/tests.rs @@ -0,0 +1,432 @@ +//! GPU unit tests for the 14 OCIO / Layer / Metadata / Generator / Utility built-ins. + +use super::*; + +fn comp(tools: &str) -> Comp { + let src = format!( + "Composition {{ CurrentTime = 0, RenderRange = {{ 0, 10 }}, GlobalRange = {{ 0, 10 }}, Tools = ordered() {{ {tools} }} }}" + ); + Comp::from_fusion_str(&src).expect("parse comp") +} + +/// Float32 solid-colour `Background` named `name`. +fn solid(name: &str, w: u32, h: u32, [r, g, b, a]: [f32; 4]) -> String { + format!( + "{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {h}, }}, Depth = Input {{ Value = 4, }}, \ + TopLeftRed = Input {{ Value = {r}, }}, TopLeftGreen = Input {{ Value = {g}, }}, TopLeftBlue = Input {{ Value = {b}, }}, TopLeftAlpha = Input {{ Value = {a}, }}, }}, }}," + ) +} + +/// `name = { Inputs = { Input = , } }`. +fn tool(name: &str, kind: &str, src: &str, extra: &str) -> String { + format!("{name} = {kind} {{ Inputs = {{ Input = Input {{ SourceOp = \"{src}\", Source = \"Output\", }}, {extra} }}, }},") +} + +fn with_z(name: &str, src: &str) -> String { + tool(name, "Dimension.CopyAux", src, "Channel = Input { Value = FuID { \"Z\" }, }, Mode = Input { Value = 1, },") +} + +fn render(c: &Comp, name: &str, time: f64) -> Option<(CachedTexture, Vec)> { + let mut eng = Engine::new_headless().ok()?; + let (tex, stats) = eng.evaluate(c, c.find_node(name).expect("find node"), time); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba_f32(&tex).unwrap(); + Some((tex, px)) +} + +fn px(buf: &[f32], w: u32, x: u32, y: u32) -> [f32; 4] { + let i = ((y * w + x) * 4) as usize; + buf[i..i + 4].try_into().unwrap() +} + +fn near(got: f32, want: f32, tol: f32, what: &str) { + assert!((got - want).abs() <= tol, "{what}: got {got}, want {want} (±{tol})"); +} + +fn srgb_oetf(x: f32) -> f32 { + if x <= 0.0031308 { x * 12.92 } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 } +} + +fn left_half_mask() -> &'static str { + "M = RectangleMask { Inputs = { MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 16, }, \ + Center = Input { Value = { 0.25, 0.5 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, }, }," +} + +#[test] +fn ocio_color_space_converts_transfer_gamut_and_preserves_hdr() { + let c = comp(&[ + solid("Mid", 16, 16, [0.5, 0.5, 0.5, 1.0]), + solid("Red", 16, 16, [1.0, 0.0, 0.0, 1.0]), + solid("Hdr", 16, 16, [2.5, 2.5, 2.5, 1.0]), + solid("Gray", 16, 16, [0.18, 0.18, 0.18, 1.0]), + tool("Lin", "OCIOColorSpace", "Mid", "SourceSpace = Input { Value = \"sRGB - Texture\", }, OutputSpace = Input { Value = \"Linear Rec.709 (sRGB)\", },"), + tool("Ap1", "OCIOColorSpace", "Red", "SourceSpace = Input { Value = \"Linear Rec.709 (sRGB)\", }, OutputSpace = Input { Value = \"ACEScg\", },"), + tool("Log", "OCIOColorSpace", "Gray", "SourceSpace = Input { Value = \"Linear\", }, OutputSpace = Input { Value = \"ARRI LogC3\", },"), + tool("Back", "OCIOColorSpace", "Log", "SourceSpace = Input { Value = \"ARRI LogC3\", }, OutputSpace = Input { Value = \"Linear\", },"), + tool("Id", "OCIOColorSpace", "Hdr", "SourceSpace = Input { Value = \"ACEScg\", }, OutputSpace = Input { Value = \"ACEScg\", },"), + tool("Hdr2", "OCIOColorSpace", "Hdr", "SourceSpace = Input { Value = \"Linear\", }, OutputSpace = Input { Value = \"ACEScct\", },"), + tool("Off", "OCIOColorSpace", "Mid", "SourceSpace = Input { Value = \"sRGB\", }, Blend = Input { Value = 0, },"), + solid("Lft", 32, 16, [0.5, 0.5, 0.5, 1.0]), + left_half_mask().to_owned(), + tool("Masked", "OCIOColorSpace", "Lft", "SourceSpace = Input { Value = \"sRGB\", }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"), + tool("MaskedInv", "OCIOColorSpace", "Lft", "SourceSpace = Input { Value = \"sRGB\", }, ApplyMaskInverted = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"), + ].concat()); + let Some((_, lin)) = render(&c, "Lin", 0.0) else { return }; + near(px(&lin, 16, 3, 3)[0], 0.21404, 2e-3, "sRGB 0.5 -> linear"); + let (_, ap1) = render(&c, "Ap1", 0.0).unwrap(); + let p = px(&ap1, 16, 3, 3); + near(p[0], 0.6131, 0.01, "Rec.709 red -> ACEScg R"); + near(p[1], 0.0702, 0.01, "Rec.709 red -> ACEScg G"); + near(p[2], 0.0206, 0.01, "Rec.709 red -> ACEScg B"); + let (_, log) = render(&c, "Log", 0.0).unwrap(); + near(px(&log, 16, 3, 3)[0], 0.391, 0.01, "LogC3 of 18% gray"); + let (_, back) = render(&c, "Back", 0.0).unwrap(); + near(px(&back, 16, 3, 3)[0], 0.18, 2e-3, "LogC3 round trip"); + let (_, id) = render(&c, "Id", 0.0).unwrap(); + assert_eq!(px(&id, 16, 3, 3), [2.5, 2.5, 2.5, 1.0], "identity keeps HDR exactly"); + let (_, cct) = render(&c, "Hdr2", 0.0).unwrap(); + assert!(px(&cct, 16, 3, 3)[0] > 0.5, "ACEScct encodes HDR without clamping"); + let (_, off) = render(&c, "Off", 0.0).unwrap(); + assert_eq!(px(&off, 16, 3, 3), [0.5, 0.5, 0.5, 1.0], "Blend=0 passes through"); + let (_, masked) = render(&c, "Masked", 0.0).unwrap(); + near(px(&masked, 32, 4, 8)[0], 0.21404, 2e-3, "inside mask converted"); + near(px(&masked, 32, 28, 8)[0], 0.5, 1e-4, "outside mask untouched"); + let (_, inv) = render(&c, "MaskedInv", 0.0).unwrap(); + near(px(&inv, 32, 4, 8)[0], 0.5, 1e-4, "ApplyMaskInverted keeps inside"); + near(px(&inv, 32, 28, 8)[0], 0.21404, 2e-3, "ApplyMaskInverted converts outside"); +} + +#[test] +fn ocio_display_applies_exposure_curve_gamma_and_view() { + let c = comp(&[ + solid("Gray", 16, 16, [0.18, 0.18, 0.18, 1.0]), + solid("Hdr", 16, 16, [4.0, 4.0, 4.0, 1.0]), + tool("Def", "OCIODisplay", "Gray", ""), + tool("Ev1", "OCIODisplay", "Gray", "Exposure = Input { Value = 1, },"), + tool("G2", "OCIODisplay", "Gray", "Gamma = Input { Value = 2, },"), + tool("P2", "OCIODisplay", "Gray", "DisplayDevice = Input { Value = \"Rec.709\", },"), + tool("Raw", "OCIODisplay", "Hdr", ""), + tool("Aces", "OCIODisplay", "Hdr", "ViewTransform = Input { Value = \"ACES\", },"), + tool("Srgb", "OCIODisplay", "Gray", "InputSpace = Input { Value = \"sRGB\", },"), + tool("Off", "OCIODisplay", "Gray", "Blend = Input { Value = 0, },"), + ].concat()); + let Some((_, def)) = render(&c, "Def", 0.0) else { return }; + near(px(&def, 16, 4, 4)[0], srgb_oetf(0.18), 2e-3, "sRGB display of 18% gray"); + let (_, ev) = render(&c, "Ev1", 0.0).unwrap(); + near(px(&ev, 16, 4, 4)[0], srgb_oetf(0.36), 2e-3, "+1 stop doubles linear before the curve"); + let (_, g2) = render(&c, "G2", 0.0).unwrap(); + near(px(&g2, 16, 4, 4)[0], srgb_oetf(0.18).sqrt(), 2e-3, "post gamma"); + let (_, p2) = render(&c, "P2", 0.0).unwrap(); + near(px(&p2, 16, 4, 4)[0], 0.18_f32.powf(1.0 / 2.4), 2e-3, "Rec.709 display uses gamma 2.4"); + let (_, raw) = render(&c, "Raw", 0.0).unwrap(); + assert!(px(&raw, 16, 4, 4)[0] > 1.0, "no view transform keeps HDR above 1"); + let (_, aces) = render(&c, "Aces", 0.0).unwrap(); + let a = px(&aces, 16, 4, 4)[0]; + assert!(a > 0.5 && a < 1.0, "ACES view rolls HDR into range: {a}"); + let (_, srgb_in) = render(&c, "Srgb", 0.0).unwrap(); + assert!(px(&srgb_in, 16, 4, 4)[0] < px(&def, 16, 4, 4)[0], "sRGB-encoded input decodes before the display curve"); + let (_, off) = render(&c, "Off", 0.0).unwrap(); + assert_eq!(px(&off, 16, 4, 4)[0], 0.18); +} + +const POW2_LUT: &str = "LUT_1D_SIZE 5\\n0 0 0\\n0.0625 0.0625 0.0625\\n0.25 0.25 0.25\\n0.5625 0.5625 0.5625\\n1 1 1\\n"; +const SWAP_RB_CLF: &str = "\ + 0 0 0 1 0 0 0 1 0 1 1 0 0 0 1 1 0 1 0 1 1 1 1 1"; +const DOUBLE_CDL: &str = "2 2 20 0 01 1 1\ + 1"; + +#[test] +fn ocio_file_transform_luts_cdl_clf_direction_and_interpolation() { + let file = |spec: &str, extra: &str| format!("File = Input {{ Value = \"{spec}\", }}, {extra}"); + let c = comp(&[ + solid("Src", 16, 16, [0.5, 0.5, 0.5, 1.0]), + solid("Low", 16, 16, [0.3, 0.3, 0.3, 1.0]), + solid("Rgb", 16, 16, [0.2, 0.4, 0.6, 1.0]), + tool("Fwd", "OCIOFileTransform", "Src", &file(POW2_LUT, "")), + tool("Inv", "OCIOFileTransform", "Fwd", &file(POW2_LUT, "Direction = Input { Value = \"Inverse\", },")), + tool("Lin", "OCIOFileTransform", "Low", &file(POW2_LUT, "Interpolation = Input { Value = \"Linear\", },")), + tool("Near", "OCIOFileTransform", "Low", &file(POW2_LUT, "Interpolation = Input { Value = \"Nearest\", },")), + tool("Clf", "OCIOFileTransform", "Rgb", &file(SWAP_RB_CLF, "")), + tool("Cdl", "OCIOFileTransform", "Low", &file(DOUBLE_CDL, "")), + tool("CdlInv", "OCIOFileTransform", "Low", &file(DOUBLE_CDL, "Direction = Input { Value = \"Inverse\", },")), + tool("Empty", "OCIOFileTransform", "Rgb", &file("", "")), + tool("Missing", "OCIOFileTransform", "Rgb", &file("/nonexistent/grade.cube", "")), + tool("Off", "OCIOFileTransform", "Src", &file(POW2_LUT, "Blend = Input { Value = 0, },")), + ].concat()); + let Some((_, fwd)) = render(&c, "Fwd", 0.0) else { return }; + near(px(&fwd, 16, 3, 3)[0], 0.25, 2e-3, "1D .cube forward"); + let (_, inv) = render(&c, "Inv", 0.0).unwrap(); + near(px(&inv, 16, 3, 3)[0], 0.5, 5e-3, "Inverse undoes the forward LUT"); + let (_, lin) = render(&c, "Lin", 0.0).unwrap(); + near(px(&lin, 16, 3, 3)[0], 0.1, 2e-3, "Linear interpolation between nodes"); + let (_, near_px) = render(&c, "Near", 0.0).unwrap(); + near(px(&near_px, 16, 3, 3)[0], 0.0625, 2e-3, "Nearest snaps to the closest node"); + let (_, clf) = render(&c, "Clf", 0.0).unwrap(); + let p = px(&clf, 16, 3, 3); + near(p[0], 0.6, 2e-3, "CLF LUT3D B-fastest order: R<-B"); + near(p[1], 0.4, 2e-3, "CLF LUT3D G"); + near(p[2], 0.2, 2e-3, "CLF LUT3D B<-R"); + let (_, cdl) = render(&c, "Cdl", 0.0).unwrap(); + near(px(&cdl, 16, 3, 3)[0], 0.6, 2e-3, "CDL slope 2"); + let (_, cdl_inv) = render(&c, "CdlInv", 0.0).unwrap(); + near(px(&cdl_inv, 16, 3, 3)[0], 0.15, 2e-3, "CDL inverse"); + for name in ["Empty", "Missing"] { + let (_, same) = render(&c, name, 0.0).unwrap(); + assert_eq!(px(&same, 16, 3, 3), [0.2, 0.4, 0.6, 1.0], "{name} passes through"); + } + let (_, off) = render(&c, "Off", 0.0).unwrap(); + assert_eq!(px(&off, 16, 3, 3)[0], 0.5); +} + +#[test] +fn layer_muxer_regex_and_remover_route_aux_without_touching_rgba() { + let c = comp(&[ + solid("Plain", 16, 16, [0.2, 0.4, 0.6, 1.0]), + solid("Other", 16, 16, [0.9, 0.1, 0.1, 1.0]), + with_z("Deep", "Other"), + "Mux = LayerMuxer { Inputs = { Background = Input { SourceOp = \"Plain\", Source = \"Output\", }, Foreground1 = Input { SourceOp = \"Deep\", Source = \"Output\", }, }, },".to_owned(), + "MuxMain = LayerMuxer { Inputs = { Background = Input { SourceOp = \"Deep\", Source = \"Output\", }, Input1 = Input { SourceOp = \"Plain\", Source = \"Output\", }, }, },".to_owned(), + "MuxEmpty = LayerMuxer { },".to_owned(), + tool("KeepAll", "LayerRegex", "Deep", ""), + tool("KeepZ", "LayerRegex", "Deep", "Pattern = Input { Value = \"^z$\", },"), + tool("KeepNormal", "LayerRegex", "Deep", "Pattern = Input { Value = \"^normal$\", },"), + tool("InvZ", "LayerRegex", "Deep", "Pattern = Input { Value = \"^z$\", }, Invert = Input { Value = 1, },"), + tool("KillZ", "LayerRemover", "Deep", "KillZ = Input { Value = 1, },"), + tool("KillByName", "LayerRemover", "Deep", "Layers = Input { Value = \"^z$|^normal$\", },"), + tool("KillNormal", "LayerRemover", "Deep", "KillNormal = Input { Value = 1, },"), + ].concat()); + let has_z = |t: &CachedTexture| t.aux.as_ref().is_some_and(|a| a.z.is_some()); + let Some((plain, plain_px)) = render(&c, "Plain", 0.0) else { return }; + assert!(!has_z(&plain)); + + let (mux, mux_px) = render(&c, "Mux", 0.0).unwrap(); + assert!(has_z(&mux), "Background lacks Z so the foreground's Z is routed in"); + assert_eq!(mux_px, plain_px, "main RGBA comes from the Background"); + let (mux_main, mux_main_px) = render(&c, "MuxMain", 0.0).unwrap(); + let (deep, deep_px) = render(&c, "Deep", 0.0).unwrap(); + assert!(has_z(&mux_main) && mux_main.content_hash == deep.content_hash, "nothing to route: input returned untouched"); + assert_eq!(mux_main_px, deep_px); + assert_eq!(render(&c, "MuxEmpty", 0.0).unwrap().0.size, [1, 1]); + + for (name, expect_z) in [("KeepAll", true), ("KeepZ", true), ("KeepNormal", false), ("InvZ", false), ("KillZ", false), ("KillByName", false), ("KillNormal", true)] { + let (t, p) = render(&c, name, 0.0).unwrap(); + assert_eq!(has_z(&t), expect_z, "{name} Z presence"); + assert_eq!(p, deep_px, "{name} leaves RGBA lossless"); + } +} + +#[test] +fn swizzler_remaps_channels_secondary_luminance_z_and_mask() { + let c = comp(&[ + solid("Src", 32, 16, [0.2, 0.4, 0.6, 0.5]), + solid("Sec", 32, 16, [0.9, 0.8, 0.7, 0.1]), + solid("Hdr", 32, 16, [2.5, 2.5, 2.5, 1.0]), + with_z("Deep", "Src"), + left_half_mask().to_owned(), + tool("Swap", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, Green = Input { Value = \"Zero\", }, Alpha = Input { Value = \"One\", },"), + tool("Id", "Swizzler", "Src", ""), + tool("Inv", "Swizzler", "Src", "Red = Input { Value = \"InvertedRed\", },"), + tool("Luma", "Swizzler", "Hdr", "Red = Input { Value = \"Luminance\", },"), + tool("Z", "Swizzler", "Deep", "Green = Input { Value = \"Z\", },"), + "Sw2 = Swizzler { Inputs = { Input = Input { SourceOp = \"Src\", Source = \"Output\", }, Input2 = Input { SourceOp = \"Sec\", Source = \"Output\", }, \ + Red = Input { Value = \"SecondaryRed\", }, Alpha = Input { Value = \"SecondaryAlpha\", }, }, },".to_owned(), + tool("Masked", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"), + tool("MaskedInv", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, Blue = Input { Value = \"Red\", }, ApplyMaskInverted = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"), + tool("Mult", "Swizzler", "Src", "Red = Input { Value = \"Blue\", }, MultiplyByMask = Input { Value = 1, }, EffectMask = Input { SourceOp = \"M\", Source = \"Mask\", },"), + ].concat()); + let Some((_, swap)) = render(&c, "Swap", 0.0) else { return }; + assert_eq!(px(&swap, 32, 5, 5), [0.6, 0.0, 0.2, 1.0]); + let (_, id) = render(&c, "Id", 0.0).unwrap(); + assert_eq!(px(&id, 32, 5, 5), [0.2, 0.4, 0.6, 0.5], "default selectors are identity"); + let (_, inv) = render(&c, "Inv", 0.0).unwrap(); + near(px(&inv, 32, 5, 5)[0], 0.8, 1e-6, "inverted red"); + let (_, luma) = render(&c, "Luma", 0.0).unwrap(); + near(px(&luma, 32, 5, 5)[0], 2.5, 1e-3, "luminance of HDR gray stays above 1"); + let (_, z) = render(&c, "Z", 0.0).unwrap(); + assert!(px(&z, 32, 5, 5)[1] != 0.4, "Z aux replaces green"); + let (_, sw2) = render(&c, "Sw2", 0.0).unwrap(); + let p = px(&sw2, 32, 5, 5); + near(p[0], 0.9, 1e-5, "secondary red"); + near(p[3], 0.1, 1e-5, "secondary alpha"); + near(p[1], 0.4, 1e-6, "untouched green"); + let (_, masked) = render(&c, "Masked", 0.0).unwrap(); + assert_eq!(px(&masked, 32, 4, 8)[0], 0.6, "inside mask swapped"); + assert_eq!(px(&masked, 32, 28, 8)[0], 0.2, "outside mask untouched"); + let (_, inverted) = render(&c, "MaskedInv", 0.0).unwrap(); + assert_eq!(px(&inverted, 32, 4, 8)[0], 0.2); + assert_eq!(px(&inverted, 32, 28, 8)[0], 0.6); + let (_, mult) = render(&c, "Mult", 0.0).unwrap(); + assert_eq!(px(&mult, 32, 28, 8), [0.0; 4], "MultiplyByMask zeroes outside the mask"); +} + +#[test] +fn metadata_tools_and_dummy_are_lossless_passthroughs() { + let c = comp(&[ + solid("Src", 16, 16, [0.2, 0.4, 0.6, 1.0]), + with_z("Deep", "Src"), + tool("Copy", "Fuse.FLS_CopyMetadata", "Deep", ""), + tool("Tc", "Fuse.SetMetaDataTC", "Deep", "TimeCode = Input { Value = \"01:00:00:00\", }, FPS = Input { Value = 24, }, DropFrame = Input { Value = 0, },"), + tool("Dum", "Dummy", "Deep", ""), + "Free = Dummy { }, FreeCopy = Fuse.FLS_CopyMetadata { }, FreeTc = Fuse.SetMetaDataTC { },".to_owned(), + ].concat()); + let Some((deep, deep_px)) = render(&c, "Deep", 0.0) else { return }; + for name in ["Copy", "Tc", "Dum"] { + let (t, p) = render(&c, name, 0.0).unwrap(); + assert_eq!(p, deep_px, "{name} pixels"); + assert_eq!((t.origin, t.canvas_size, t.depth), (deep.origin, deep.canvas_size, deep.depth), "{name} DoD/depth"); + assert!(t.aux.as_ref().is_some_and(|a| a.z.is_some()), "{name} keeps aux.z"); + } + for name in ["Free", "FreeCopy", "FreeTc"] { + assert_eq!(render(&c, name, 0.0).unwrap().0.size, [1, 1], "{name} disconnected"); + } +} + +#[test] +fn multi_text_renders_each_layer_and_matches_text_plus_for_one() { + let c = comp(r#" + Mt = MultiText { Inputs = { + Width = Input { Value = 128, }, Height = Input { Value = 64, }, + StyledText1 = Input { Value = "II", }, Center1 = Input { Value = { 0.25, 0.5 }, }, Size1 = Input { Value = 0.4, }, + Red1 = Input { Value = 1, }, Green1 = Input { Value = 0, }, Blue1 = Input { Value = 0, }, + Text2 = Input { Value = "II", }, Center2 = Input { Value = { 0.75, 0.5 }, }, Size2 = Input { Value = 0.4, }, + Red2 = Input { Value = 0, }, Green2 = Input { Value = 1, }, Blue2 = Input { Value = 0, }, + }, }, + One = MultiText { Inputs = { + Width = Input { Value = 128, }, Height = Input { Value = 64, }, + StyledText = Input { Value = "HI", }, Size = Input { Value = 0.25, }, + }, }, + Tp = TextPlus { Inputs = { + Width = Input { Value = 128, }, Height = Input { Value = 64, }, + StyledText = Input { Value = "HI", }, Size = Input { Value = 0.25, }, + }, }, + Empty = MultiText { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 64, }, }, }, + "#); + let Some((mt, mt_px)) = render(&c, "Mt", 0.0) else { return }; + assert_eq!(mt.canvas_size, [128, 64]); + let count = |range: std::ops::Range, pred: &dyn Fn([f32; 4]) -> bool| { + range.flat_map(|x| (0..64).map(move |y| (x, y))).filter(|&(x, y)| pred(px(&mt_px, mt.size[0], x, y))).count() + }; + assert!(count(0..64, &|p| p[0] > 0.8 && p[1] < 0.2 && p[3] > 0.8) > 10, "layer 1 renders red text on the left"); + assert!(count(64..128, &|p| p[1] > 0.8 && p[0] < 0.2 && p[3] > 0.8) > 10, "layer 2 renders green text on the right"); + assert_eq!(count(0..64, &|p| p[1] > 0.5 && p[3] > 0.5), 0, "layers stay on their own side"); + let (one, one_px) = render(&c, "One", 0.0).unwrap(); + let (tp, tp_px) = render(&c, "Tp", 0.0).unwrap(); + assert_eq!((one.size, one.origin), (tp.size, tp.origin)); + assert_eq!(one_px, tp_px, "a single layer is exactly TextPlus"); + let (_, empty_px) = render(&c, "Empty", 0.0).unwrap(); + assert!(empty_px.iter().all(|&v| v == 0.0), "no text renders transparent"); +} + +fn row_ramp() -> String { + "Ramp = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \ + Type = Input { Value = FuID { \"Vertical\" }, }, TopLeftRed = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, \ + BottomLeftRed = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, }, }, }," + .to_owned() +} + +#[test] +fn fields_deinterlace_interlace_swap_and_strip() { + let fields = |name: &str, extra: &str| tool(name, "Fields", "Ramp", extra); + let c = comp(&[ + row_ramp(), + solid("Second", 16, 16, [0.0, 1.0, 0.0, 1.0]), + fields("Dup", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Duplicate\", },"), + fields("Interp", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Interpolate\", },"), + fields("Blend", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Blend\", },"), + fields("Even", "Operation = Input { Value = \"Deinterlace\", }, Method = Input { Value = \"Duplicate\", }, FieldOrder = Input { Value = \"Even\", },"), + fields("Swap", "Operation = Input { Value = \"SwapFields\", },"), + fields("Strip", "Operation = Input { Value = \"StripFields\", }, Method = Input { Value = \"Blend\", },"), + "Weave = Fields { Inputs = { Input = Input { SourceOp = \"Ramp\", Source = \"Output\", }, Input2 = Input { SourceOp = \"Second\", Source = \"Output\", }, \ + Operation = Input { Value = \"Interlace\", }, }, },".to_owned(), + fields("Off", "Operation = Input { Value = \"SwapFields\", }, Blend = Input { Value = 0, },"), + ].concat()); + let Some((_, ramp)) = render(&c, "Ramp", 0.0) else { return }; + let r = |buf: &[f32], y: u32| px(buf, 16, 2, y)[0]; + assert!(r(&ramp, 3) > r(&ramp, 2) + 0.01, "the ramp must vary per row for the parity checks to mean anything"); + let (_, dup) = render(&c, "Dup", 0.0).unwrap(); + near(r(&dup, 2), r(&ramp, 2), 1e-6, "dominant (odd) lines kept"); + near(r(&dup, 3), r(&ramp, 2), 1e-6, "Duplicate copies the dominant line above"); + let (_, interp) = render(&c, "Interp", 0.0).unwrap(); + near(r(&interp, 3), (r(&ramp, 2) + r(&ramp, 4)) / 2.0, 1e-6, "Interpolate averages neighbours"); + let (_, blend) = render(&c, "Blend", 0.0).unwrap(); + near(r(&blend, 3), (r(&ramp, 3) + (r(&ramp, 2) + r(&ramp, 4)) / 2.0) / 2.0, 1e-6, "Blend mixes with the interpolation"); + let (_, even) = render(&c, "Even", 0.0).unwrap(); + near(r(&even, 2), r(&ramp, 1), 1e-6, "Even field order keeps odd rows and rebuilds even ones"); + let (_, swap) = render(&c, "Swap", 0.0).unwrap(); + near(r(&swap, 2), r(&ramp, 3), 1e-6, "SwapFields exchanges line pairs"); + near(r(&swap, 3), r(&ramp, 2), 1e-6, "SwapFields exchanges line pairs"); + let (_, strip) = render(&c, "Strip", 0.0).unwrap(); + near(r(&strip, 3), r(&ramp, 2), 1e-6, "StripFields drops the second field"); + let (_, weave) = render(&c, "Weave", 0.0).unwrap(); + near(r(&weave, 2), r(&ramp, 2), 1e-6, "Interlace keeps the dominant line from Input"); + assert_eq!(px(&weave, 16, 2, 3), [0.0, 1.0, 0.0, 1.0], "Interlace takes the other lines from Input2"); + let (_, off) = render(&c, "Off", 0.0).unwrap(); + assert_eq!(off, ramp); +} + +#[test] +fn chromatic_aberration_removal_rescales_channels_radially() { + let c = comp(&[ + "Ramp = Background { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \ + Type = Input { Value = FuID { \"Horizontal\" }, }, TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, \ + TopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, }, },".to_owned(), + "Edge = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, Depth = Input { Value = 4, }, \ + TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, }, },".to_owned(), + tool("Def", "ChromaticAberrationRemoval", "Ramp", ""), + tool("Red", "ChromaticAberrationRemoval", "Ramp", "RedScale = Input { Value = 1.1, },"), + tool("Blue", "ChromaticAberrationRemoval", "Ramp", "BlueYellow = Input { Value = 10, },"), + tool("Off", "ChromaticAberrationRemoval", "Ramp", "RedScale = Input { Value = 1.1, }, Blend = Input { Value = 0, },"), + tool("Defr", "ChromaticAberrationRemoval", "Edge", "Defringe = Input { Value = 1, },"), + ].concat()); + let Some((_, ramp)) = render(&c, "Ramp", 0.0) else { return }; + let (_, def) = render(&c, "Def", 0.0).unwrap(); + assert_eq!(def, ramp, "default is identity"); + let (_, red) = render(&c, "Red", 0.0).unwrap(); + let (a, b) = (px(&ramp, 64, 48, 8), px(&red, 64, 48, 8)); + assert!(b[0] > a[0] + 0.01, "red sampled farther from the centre: {} vs {}", b[0], a[0]); + near(b[1], a[1], 1e-5, "green untouched"); + near(px(&red, 64, 32, 8)[0], px(&ramp, 64, 32, 8)[0], 0.02, "centre pixel stays put"); + let (_, blue) = render(&c, "Blue", 0.0).unwrap(); + assert!(px(&blue, 64, 48, 8)[2] > a[2] + 0.01, "BlueYellow shifts blue"); + let (_, off) = render(&c, "Off", 0.0).unwrap(); + assert_eq!(off, ramp); + let (_, defr) = render(&c, "Defr", 0.0).unwrap(); + assert_eq!(px(&defr, 16, 8, 8), [1.0, 0.0, 0.0, 1.0], "defringe leaves flat colour alone"); +} + +#[test] +fn key_stretcher_keeps_intro_and_outro_and_stretches_the_middle() { + let keys = (0..=10).map(|f| format!("[{f}] = {{ {}, Flags = {{ StepIn = true }} }},", f as f32 / 10.0)).collect::(); + let stretch = |name: &str, mode: &str| { + format!( + "{name} = KeyStretcher {{ Inputs = {{ Input = Input {{ SourceOp = \"Clip\", Source = \"Output\", }}, \ + SourceStart = Input {{ Value = 2, }}, SourceEnd = Input {{ Value = 4, }}, StretchStart = Input {{ Value = 2, }}, \ + StretchEnd = Input {{ Value = 6, }}, StretchMode = Input {{ Value = \"{mode}\", }}, }}, }}," + ) + }; + let c = comp(&[ + "Clip = Background { Inputs = { Width = Input { Value = 4, }, Height = Input { Value = 4, }, Depth = Input { Value = 4, }, \ + TopLeftRed = Input { SourceOp = \"Ramp\", Source = \"Value\", }, TopLeftAlpha = Input { Value = 1, }, }, },".to_owned(), + format!("Ramp = BezierSpline {{ KeyFrames = {{ {keys} }} }},"), + stretch("Loop", "Loop"), + stretch("Hold", "Hold"), + stretch("Ping", "PingPong"), + stretch("Scale", "Scale"), + "Ident = KeyStretcher { Inputs = { Input = Input { SourceOp = \"Clip\", Source = \"Output\", }, }, },".to_owned(), + "Cycle = KeyStretcher { Inputs = { Input = Input { SourceOp = \"Cycle\", Source = \"Output\", }, }, },".to_owned(), + "Free = KeyStretcher { },".to_owned(), + ].concat()); + let value = |name: &str, t: f64| render(&c, name, t).map(|(_, p)| px(&p, 4, 1, 1)[0]); + let Some(intro) = value("Loop", 1.0) else { return }; + near(intro, 0.1, 1e-3, "intro plays unstretched"); + near(value("Loop", 5.0).unwrap(), 0.3, 1e-3, "Loop wraps the middle over the source range"); + near(value("Loop", 8.0).unwrap(), 0.6, 1e-3, "outro continues from SourceEnd"); + near(value("Hold", 5.0).unwrap(), 0.4, 1e-3, "Hold clamps at SourceEnd"); + near(value("Ping", 5.0).unwrap(), 0.3, 1e-3, "PingPong folds back"); + near(value("Scale", 4.0).unwrap(), 0.3, 1e-3, "Scale maps linearly"); + for t in [0.0, 3.0, 10.0] { + near(value("Ident", t).unwrap(), t as f32 / 10.0, 1e-3, "defaults are the identity"); + } + assert_eq!(render(&c, "Cycle", 3.0).unwrap().0.size, [1, 1], "self-referencing input terminates"); + assert_eq!(render(&c, "Free", 0.0).unwrap().0.size, [1, 1]); +} diff --git a/crates/engine/src/eval/layer_ocio/utility.rs b/crates/engine/src/eval/layer_ocio/utility.rs new file mode 100644 index 0000000000000000000000000000000000000000..a6402d46c5bc7a41395c562fbf25d1f606582072 --- /dev/null +++ b/crates/engine/src/eval/layer_ocio/utility.rs @@ -0,0 +1,215 @@ +//! `KeyStretcher` and `MultiText`. + +use super::*; +use model::InputBinding; + +const MAX_TEXT_LAYERS: usize = 16; + +/// How the middle segment maps onto `[SourceStart, SourceEnd]`. +#[derive(Clone, Copy, PartialEq, Debug)] +enum StretchMode { + Hold, + Loop, + PingPong, + Scale, +} + +struct Stretch { + source: [f64; 2], + stretch: [f64; 2], + mode: StretchMode, +} + +impl Stretch { + /// Source time for output time `t`: the intro before `stretch[0]` and outro after `stretch[1]` play + /// unstretched, continuous with the middle segment's ends. + fn source_time(&self, t: f64) -> f64 { + let [src_start, src_end] = self.source; + let [st_start, st_end] = self.stretch; + if t < st_start { + return t + (src_start - st_start); + } + if t > st_end { + return src_end + (t - st_end); + } + let dt = t - st_start; + let src_span = src_end - src_start; + let out_span = st_end - st_start; + if src_span <= 0.0 { + return src_start; + } + src_start + + match self.mode { + StretchMode::Scale if out_span > 0.0 => dt / out_span * src_span, + StretchMode::Scale => 0.0, + StretchMode::Hold => dt.min(src_span), + StretchMode::Loop => dt.rem_euclid(src_span), + StretchMode::PingPong => { + let p = dt.rem_euclid(2.0 * src_span); + if p <= src_span { p } else { 2.0 * src_span - p } + } + } + } +} + +/// Re-keys `node`'s inputs for text layer `layer` (`0` = the shared inputs only): `Layer{n}Foo`, `Layer{n}.Foo` +/// and `Foo{n}` override `Foo`, then MultiText names map onto `TextPlus` inputs. +fn text_layer_inputs(node: &Node, layer: usize) -> HashMap { + const ALIASES: [(&str, &str); 5] = + [("Text", "StyledText"), ("Red", "Red1"), ("Green", "Green1"), ("Blue", "Blue1"), ("Alpha", "Alpha1")]; + let alias = |name: &str| ALIASES.iter().find(|(from, _)| *from == name).map_or(name, |(_, to)| *to).to_owned(); + let layer_name = |key: &str| -> Option { + let n = layer.to_string(); + let rest = key + .strip_prefix(&format!("Layer{n}")) + .filter(|r| !r.starts_with(|c: char| c.is_ascii_digit())) + .map(|r| r.trim_start_matches('.')); + let rest = rest.or_else(|| key.strip_suffix(&n).filter(|r| !r.is_empty() && !r.ends_with(|c: char| c.is_ascii_digit()))); + rest.map(|r| if r.is_empty() { "StyledText".to_owned() } else { alias(r) }) + }; + let shared = node + .inputs + .iter() + .filter(|(k, _)| !k.starts_with("Layer") && !k.ends_with(|c: char| c.is_ascii_digit())) + .map(|(k, b)| (alias(k), b.clone())); + let own = node.inputs.iter().filter_map(|(k, b)| Some((layer_name(k).filter(|_| layer > 0)?, b.clone()))); + shared.chain(own).collect() +} + +fn text_layers(node: &Node) -> Vec { + (1..=MAX_TEXT_LAYERS) + .filter(|&n| { + ["Layer{}", "Layer{}StyledText", "Layer{}.StyledText", "Layer{}Text", "Layer{}.Text", "StyledText{}", "Text{}"] + .iter() + .any(|pat| node.inputs.contains_key(&pat.replace("{}", &n.to_string()))) + }) + .collect() +} + +impl Engine { + /// `KeyStretcher` — retimes `Input` so the intro and outro play unstretched around a stretched middle segment. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_key_stretcher( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = conn_any(comp, node, &["Input", "Image", "Background"]) else { + return self.dummy.clone(); + }; + let [g_start, g_end] = comp.global_range.map(|f| f as f64); + let read = |keys: &[&str], default: f64| num_any(comp, node, keys, time, default, &self.expr); + let mode = match str_any(node, &["StretchMode", "Mode"]).map(squash).as_deref() { + Some("hold") => StretchMode::Hold, + Some("loop") => StretchMode::Loop, + Some("pingpong") => StretchMode::PingPong, + Some(_) => StretchMode::Scale, + None => match read(&["StretchMode", "Mode"], 3.0).round() as i32 { + 0 => StretchMode::Hold, + 1 => StretchMode::Loop, + 2 => StretchMode::PingPong, + _ => StretchMode::Scale, + }, + }; + let stretch = Stretch { + source: [read(&["SourceStart"], g_start), read(&["SourceEnd"], g_end)], + stretch: [read(&["StretchStart", "KeyFrames"], g_start), read(&["StretchEnd"], g_end)], + mode, + }; + let remapped = stretch.source_time(time).clamp(g_start, g_end.max(g_start)); + if (remapped - time).abs() < 1e-9 { + return self.eval_node(comp, src_id, time, enc, visiting, stats); + } + self.eval_time_remapped(comp, node, time, frame_i, remapped, enc, visiting, stats) + } + + /// `MultiText` — one `TextPlus` render per layer (`Layer{n}` / `Text{n}` / `StyledText{n}` with per-layer + /// overrides of the shared inputs), composited over each other in layer order on the shared canvas. + #[allow(clippy::too_many_arguments)] + pub(in crate::eval) fn eval_multi_text( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let layers = text_layers(node); + let mut acc: Option = None; + for layer in if layers.is_empty() { vec![0] } else { layers } { + let mut text_node = node.clone(); + text_node.kind = "TextPlus".to_owned(); + text_node.inputs = text_layer_inputs(node, layer); + let rendered = self.eval_text_plus(comp, &text_node, time, frame_i, comp_dims, enc, stats); + acc = Some(match acc { + None => rendered, + Some(bg) => { + let bg = self.crop_to_canvas(enc, bg); + let fg = self.crop_to_canvas(enc, rendered); + self.merge_text_layer(node, bg, fg, frame_i, enc, stats) + } + }); + } + acc.unwrap_or_else(|| self.dummy.clone()) + } + + /// Straight `Merge` of canvas-sized `fg` over `bg`. + fn merge_text_layer( + &mut self, + node: &Node, + bg: CachedTexture, + fg: CachedTexture, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let key = self.make_key(node, "MultiTextMerge", bg.size, &[bg.content_hash, fg.content_hash], &[]); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let mut u = UniformParams::default(); + u.p[0] = [0.5, 0.5, 1.0, 0.0]; + u.p[1] = [1.0, 1.0, 0.0, 0.0]; + u.p[2] = [0.0, 0.0, 1.0, 0.0]; + u.p[3] = [0.0, 0.0, fg.size[0] as f32, fg.size[1] as f32]; + u.p[6] = [0.0, 1.0, 0.0, 0.0]; + let dst = self.alloc_tex_like(&bg, bg.depth.max(fg.depth), key); + self.dispatch_op(enc, ShaderOp::Merge, &bg.view, &fg.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stretch(mode: StretchMode) -> Stretch { + Stretch { source: [10.0, 14.0], stretch: [10.0, 18.0], mode } + } + + #[test] + fn middle_modes_map_into_source_range() { + assert_eq!(stretch(StretchMode::Scale).source_time(14.0), 12.0); + assert_eq!(stretch(StretchMode::Hold).source_time(17.0), 14.0); + assert_eq!(stretch(StretchMode::Loop).source_time(15.0), 11.0); + assert_eq!(stretch(StretchMode::PingPong).source_time(15.0), 13.0); + } + + #[test] + fn intro_and_outro_stay_unstretched() { + let s = stretch(StretchMode::Loop); + assert_eq!(s.source_time(4.0), 4.0); + assert_eq!(s.source_time(20.0), 16.0); + } +} diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index f028d6fb7302fb286a1b0bbc752031e8ef3223a5..9b77e85c2aeae174d88a401406f5eeb0472c3a63 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -33,6 +33,7 @@ mod warps_masks; mod fx_fuses; mod archive_fx2; mod surface_fx; +mod layer_ocio; mod text_3d; mod registry; mod dispatch; @@ -87,6 +88,7 @@ pub struct Engine { fx_fuses_pipelines: OnceCell>, archive_fx2_pipelines: OnceCell>, pub(crate) surface_fx: OnceCell>, + pub(crate) layer_ocio: OnceCell>, auto_matte_pipelines: OnceCell>, pub auto_matte_cache: crate::auto_matte::AutoMatteCache, motion_blur: crate::motion_blur::MotionBlurPipelines, @@ -204,6 +206,7 @@ impl Engine { fx_fuses_pipelines: OnceCell::new(), archive_fx2_pipelines: OnceCell::new(), surface_fx: OnceCell::new(), + layer_ocio: OnceCell::new(), auto_matte_pipelines: OnceCell::new(), auto_matte_cache: crate::auto_matte::AutoMatteCache::new(), motion_blur: crate::motion_blur::MotionBlurPipelines::default(), @@ -373,6 +376,9 @@ impl Engine { if let Some(sfx) = self.surface_fx.get() { sfx.borrow_mut().reset_uniform_cursor(); } + if let Some(lo) = self.layer_ocio.get() { + lo.borrow_mut().reset_uniform_cursor(); + } if let Some(am) = self.auto_matte_pipelines.get() { am.borrow_mut().reset_uniform_cursor(); } @@ -411,6 +417,9 @@ impl Engine { if let Some(sfx) = self.surface_fx.get() { sfx.borrow_mut().trim_uniform_chunks(2); } + if let Some(lo) = self.layer_ocio.get() { + lo.borrow_mut().trim_uniform_chunks(2); + } if let Some(am) = self.auto_matte_pipelines.get() { am.borrow_mut().trim_uniform_chunks(2); } @@ -1063,6 +1072,18 @@ impl Engine { "TV" => self.eval_tv(comp, node, time, frame_i, enc, visiting, stats), "AutoDomain" => self.eval_auto_domain(comp, node, time, frame_i, enc, visiting, stats), "Fuse.FrameAverage" => self.eval_fuse_frame_average(comp, node, time, frame_i, enc, visiting, stats), + "OCIOColorSpace" => self.eval_ocio_color_space(comp, node, time, frame_i, enc, visiting, stats), + "OCIODisplay" => self.eval_ocio_display(comp, node, time, frame_i, enc, visiting, stats), + "OCIOFileTransform" => self.eval_ocio_file_transform(comp, node, time, frame_i, enc, visiting, stats), + "LayerMuxer" => self.eval_layer_muxer(comp, node, time, enc, visiting, stats), + "LayerRegex" => self.eval_layer_filter(comp, node, time, false, enc, visiting, stats), + "LayerRemover" => self.eval_layer_filter(comp, node, time, true, enc, visiting, stats), + "Swizzler" => self.eval_swizzler(comp, node, time, frame_i, enc, visiting, stats), + "Dummy" | "Fuse.FLS_CopyMetadata" | "Fuse.SetMetaDataTC" => self.eval_passthrough(comp, node, time, enc, visiting, stats), + "MultiText" => self.eval_multi_text(comp, node, time, frame_i, comp_dims, enc, stats), + "Fields" => self.eval_fields(comp, node, time, frame_i, enc, visiting, stats), + "KeyStretcher" => self.eval_key_stretcher(comp, node, time, frame_i, enc, visiting, stats), + "ChromaticAberrationRemoval" => self.eval_chromatic_aberration_removal(comp, node, time, frame_i, enc, visiting, stats), "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "sNGon" | "sRectangle" diff --git a/crates/engine/src/shaders/color_lut.wgsl b/crates/engine/src/shaders/color_lut.wgsl index 3ecf64dfe97626afadffc403bf17b59348f3eace..382696d9c5e2c2bc48a5621b4a48ac9ca60aacf0 100644 --- a/crates/engine/src/shaders/color_lut.wgsl +++ b/crates/engine/src/shaders/color_lut.wgsl @@ -905,6 +905,18 @@ fn sample_lut3d_tetrahedral(lut: texture_2d, rgb_norm: vec3, n: i32, t } } +fn sample_lut3d_trilinear(lut: texture_2d, rgb_norm: vec3, n: i32, tiles_x: i32) -> vec3 { + let pos = clamp(rgb_norm, vec3(0.0), vec3(1.0)) * f32(n - 1); + let i0 = min(vec3(floor(pos)), vec3(max(n - 2, 0))); + let i1 = min(i0 + vec3(1), vec3(n - 1)); + let f = pos - vec3(i0); + let c00 = mix(fetch_lut3d_texel(lut, i0.r, i0.g, i0.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i0.g, i0.b, n, tiles_x, false), f.r); + let c10 = mix(fetch_lut3d_texel(lut, i0.r, i1.g, i0.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i1.g, i0.b, n, tiles_x, false), f.r); + let c01 = mix(fetch_lut3d_texel(lut, i0.r, i0.g, i1.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i0.g, i1.b, n, tiles_x, false), f.r); + let c11 = mix(fetch_lut3d_texel(lut, i0.r, i1.g, i1.b, n, tiles_x, false), fetch_lut3d_texel(lut, i1.r, i1.g, i1.b, n, tiles_x, false), f.r); + return mix(mix(c00, c10, f.g), mix(c01, c11, f.g), f.b); +} + fn sample_lut1d(lut: texture_2d, rgb_norm: vec3, n: i32) -> vec3 { let max_i = f32(n - 1); let pr = clamp(rgb_norm.r, 0.0, 1.0) * max_i; @@ -930,7 +942,7 @@ fn sample_lut1d(lut: texture_2d, rgb_norm: vec3, n: i32) -> vec3 // p[3] = (offset, clip_black, clip_white, prediv) // p[4] = (blend, has_mask, mask_inv, mbm) // p[5] = skip -// p[6] = (color_space: 0=RGB, 1=YUV, 2=HLS, 3=YIQ, 4=CMY, 0, 0, 0) +// p[6] = (color_space: 0=RGB, 1=YUV, 2=HLS, 3=YIQ, 4=CMY, interp: 0=tetrahedral 1=trilinear 2=nearest, 0, 0) // ============================================================================ fn lut_rgb_to_cs(rgb: vec3, cs: i32) -> vec3 { if (cs == 1) { @@ -993,10 +1005,19 @@ fn file_lut_op(@builtin(global_invocation_id) gid: vec3) { let dmin = u.p[0].xyz; let dmax = u.p[1].xyz; - let norm_rgb = (rgb - dmin) / max(dmax - dmin, vec3(1e-6)); + var norm_rgb = (rgb - dmin) / max(dmax - dmin, vec3(1e-6)); + let interp = i32(round(u.p[6].y)); + if (interp == 2 && lut_size >= 2) { + let last = f32(lut_size - 1); + norm_rgb = round(clamp(norm_rgb, vec3(0.0), vec3(1.0)) * last) / last; + } if (lut_kind == 3 && lut_size >= 2) { - rgb = sample_lut3d_tetrahedral(tex_b, norm_rgb, lut_size, tiles_x, false); + if (interp == 1) { + rgb = sample_lut3d_trilinear(tex_b, norm_rgb, lut_size, tiles_x); + } else { + rgb = sample_lut3d_tetrahedral(tex_b, norm_rgb, lut_size, tiles_x, false); + } } else if (lut_kind == 1 && lut_size >= 2) { rgb = sample_lut1d(tex_b, norm_rgb, lut_size); } diff --git a/crates/engine/src/shaders/layer_ocio.wgsl b/crates/engine/src/shaders/layer_ocio.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..2a1a257cfdaa19ae3556c3241dad52940457cc6f --- /dev/null +++ b/crates/engine/src/shaders/layer_ocio.wgsl @@ -0,0 +1,269 @@ +// OCIODisplay, Swizzler, Fields & ChromaticAberrationRemoval compute shaders. +// +// WebGPU-safe (`wasm32` compatible): every texture input is `filterable: false` and read via +// `textureLoad`; the output is a WriteOnly storage texture (format patched at pipeline build); +// no `read_write` storage textures. +// +// Shared tail params for every op: p[14] = (blend, has_mask, mask_inv, mbm), p[15] = skip (1 = keep source). +// Bindings: tex_a = main source, tex_b = secondary, tex_c = Z aux (Swizzler) / unused, mask_tex = EffectMask. + +@group(0) @binding(0) var tex_a: texture_2d; +@group(0) @binding(1) var tex_b: texture_2d; +@group(0) @binding(2) var tex_c: texture_2d; +@group(0) @binding(3) var mask_tex: texture_2d; +@group(0) @binding(4) var dst_tex: texture_storage_2d; + +struct Params { + p: array, 16>, +}; +@group(0) @binding(5) var u: Params; + +const HDR_FLOAT: bool = false; +const LUMA_709: vec3 = vec3(0.2126, 0.7152, 0.0722); + +fn store_dst(p: vec2, col: vec4) { + if (HDR_FLOAT) { + textureStore(dst_tex, p, col); + } else { + textureStore(dst_tex, p, clamp(col, vec4(0.0), vec4(1.0))); + } +} + +fn load_clamped(tex: texture_2d, p: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + return textureLoad(tex, clamp(p, vec2(0), max(dims - vec2(1), vec2(0))), 0); +} + +fn sample_bilinear(tex: texture_2d, uv: vec2) -> vec4 { + let dims = vec2(textureDimensions(tex)); + let max_c = max(dims - vec2(1), vec2(0)); + let f = clamp(uv, vec2(0.0), vec2(1.0)) * vec2(dims) - vec2(0.5); + let i0 = clamp(vec2(floor(f)), vec2(0), max_c); + let i1 = clamp(i0 + vec2(1), vec2(0), max_c); + let t = clamp(f - floor(f), vec2(0.0), vec2(1.0)); + let c00 = textureLoad(tex, i0, 0); + let c10 = textureLoad(tex, vec2(i1.x, i0.y), 0); + let c01 = textureLoad(tex, vec2(i0.x, i1.y), 0); + let c11 = textureLoad(tex, i1, 0); + return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); +} + +fn read_mask(gid: vec2, dims: vec2) -> f32 { + if (u.p[14].y < 0.5) { + return 1.0; + } + let uv = (vec2(gid) + vec2(0.5)) / vec2(dims); + let m = sample_bilinear(mask_tex, uv).a; + return select(m, 1.0 - m, u.p[14].z > 0.5); +} + +/// Blend `res` over `src` by `Blend * EffectMask`; `MultiplyByMask` zeroes outside the mask. +fn finish(src: vec4, res: vec4, gid: vec2, dims: vec2) -> vec4 { + let m = clamp(read_mask(gid, dims) * u.p[14].x, 0.0, 1.0); + let use_mbm = u.p[14].y > 0.5 && u.p[14].w > 0.5; + var out_col = select(mix(src, res, m), res * m, use_mbm); + let unproc = select(src, vec4(0.0), use_mbm); + return select(out_col, unproc, u.p[15] > vec4(0.5)); +} + +// ============================================================================ +// OCIODisplay — exposure -> view transform -> display curve -> post gamma +// tex_a = premultiplied linear image in display primaries, tex_b = original source (blend base) +// p[0] = (exposure_gain, inv_post_gamma, display_curve, view_transform) +// display_curve: 0=linear 1=sRGB 2=g2.2 3=g2.4 4=g2.6 5=PQ 6=HLG +// view_transform: 0=none 1=ACES filmic fit 2=Reinhard +// ============================================================================ +fn pow_signed(c: f32, e: f32) -> f32 { + return sign(c) * pow(abs(c), e); +} + +fn encode_display(c: f32, curve: i32) -> f32 { + switch curve { + case 1: { + let a = abs(c); + let v = select(1.055 * pow(a, 1.0 / 2.4) - 0.055, a * 12.92, a <= 0.0031308); + return sign(c) * v; + } + case 2: { return pow_signed(c, 1.0 / 2.2); } + case 3: { return pow_signed(c, 1.0 / 2.4); } + case 4: { return pow_signed(c, 1.0 / 2.6); } + case 5: { + let y = pow(clamp(c, 0.0, 1.0e4) * 100.0 / 10000.0, 0.1593017578125); + return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), 78.84375); + } + case 6: { + let e = max(c, 0.0); + return select(0.17883277 * log(12.0 * e - 0.28466892) + 0.55991073, sqrt(3.0 * e), e <= 1.0 / 12.0); + } + default: { return c; } + } +} + +fn view_tonemap(x: vec3, mode: i32) -> vec3 { + if (mode == 1) { + let v = max(x, vec3(0.0)); + return clamp((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14), vec3(0.0), vec3(1.0)); + } + if (mode == 2) { + let v = max(x, vec3(0.0)); + return v / (vec3(1.0) + v); + } + return x; +} + +@compute @workgroup_size(8, 8) +fn ocio_display_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let lin = textureLoad(tex_a, p, 0); + let orig = textureLoad(tex_b, p, 0); + let curve = i32(round(u.p[0].z)); + let straight = select(lin.rgb, lin.rgb / lin.a, lin.a > 1e-6); + var rgb = view_tonemap(straight * u.p[0].x, i32(round(u.p[0].w))); + rgb = vec3(encode_display(rgb.r, curve), encode_display(rgb.g, curve), encode_display(rgb.b, curve)); + if (abs(u.p[0].y - 1.0) > 1e-6) { + rgb = vec3(pow_signed(rgb.r, u.p[0].y), pow_signed(rgb.g, u.p[0].y), pow_signed(rgb.b, u.p[0].y)); + } + store_dst(p, finish(orig, vec4(rgb * lin.a, lin.a), gid.xy, dims)); +} + +// ============================================================================ +// Swizzler — per-channel source selection +// p[0] = (src_r, src_g, src_b, src_a), p[1] = (has_z, 0, 0, 0) +// selector: 0..3 = R,G,B,A of Input, 4 = 0, 5 = 1, 6 = luminance, 7 = Z aux, +// 8..11 = R,G,B,A of the secondary input (tex_b, UV-mapped), 12..15 = inverted 0..3 +// ============================================================================ +fn pick_channel(sel: i32, a: vec4, b: vec4, z: f32) -> f32 { + switch sel { + case 0: { return a.r; } + case 1: { return a.g; } + case 2: { return a.b; } + case 3: { return a.a; } + case 4: { return 0.0; } + case 5: { return 1.0; } + case 6: { return dot(a.rgb, LUMA_709); } + case 7: { return z; } + case 8: { return b.r; } + case 9: { return b.g; } + case 10: { return b.b; } + default: { return b.a; } + } +} + +fn swizzle_channel(sel: i32, a: vec4, b: vec4, z: f32) -> f32 { + let inverted = sel >= 12; + let v = pick_channel(select(sel, sel - 12, inverted), a, b, z); + return select(v, 1.0 - v, inverted); +} + +@compute @workgroup_size(8, 8) +fn swizzler_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let a = textureLoad(tex_a, p, 0); + let uv = (vec2(gid.xy) + vec2(0.5)) / vec2(dims); + let b = sample_bilinear(tex_b, uv); + var z = 0.0; + if (u.p[1].x > 0.5) { + z = sample_bilinear(tex_c, uv).r; + } + let res = vec4( + swizzle_channel(i32(round(u.p[0].x)), a, b, z), + swizzle_channel(i32(round(u.p[0].y)), a, b, z), + swizzle_channel(i32(round(u.p[0].z)), a, b, z), + swizzle_channel(i32(round(u.p[0].w)), a, b, z), + ); + store_dst(p, finish(a, res, gid.xy, dims)); +} + +// ============================================================================ +// Fields — line-parity processing. tex_a = Input, tex_b = second field source (Interlace) +// p[0] = (operation, method, dominant_parity, has_b) +// operation: 0=Deinterlace 1=Interlace 2=SwapFields 3=StripFields +// method: 0=Blend 1=Interpolate 2=Duplicate +// dominant_parity: row % 2 == parity rows belong to the dominant (first) field +// ============================================================================ +@compute @workgroup_size(8, 8) +fn fields_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let a = textureLoad(tex_a, p, 0); + let op = i32(round(u.p[0].x)); + let method = i32(round(u.p[0].y)); + let parity = i32(round(u.p[0].z)); + let h = i32(dims.y); + let dominant = (p.y % 2) == parity; + let up = load_clamped(tex_a, p + vec2(0, -1)); + let down = load_clamped(tex_a, p + vec2(0, 1)); + var res = a; + if (op == 1) { + if (!dominant && u.p[0].w > 0.5) { + res = load_clamped(tex_b, p); + } + } else if (op == 2) { + // Swap each (2k, 2k+1) line pair; an unpaired last line passes through. + let partner = select(p.y + 1, p.y - 1, (p.y % 2) == 1); + if (partner < h) { + res = textureLoad(tex_a, vec2(p.x, partner), 0); + } + } else if (!dominant) { + // Deinterlace / StripFields: rebuild the non-dominant field from the dominant one. + let has_up = p.y > 0; + let has_down = p.y + 1 < h; + let dup = select(down, up, has_up); + let interp = select(select(select(a, down, has_down), up, has_up), (up + down) * 0.5, has_up && has_down); + if (op == 3 || method == 2) { + res = dup; + } else if (method == 1) { + res = interp; + } else { + res = (a + interp) * 0.5; + } + } + store_dst(p, finish(a, res, gid.xy, dims)); +} + +// ============================================================================ +// ChromaticAberrationRemoval — per-channel radial rescale about Center + defringe +// p[0] = (scale_r, scale_g, scale_b, defringe), p[1] = (center_u, center_v (top-down), 0, 0) +// ============================================================================ +fn sample_channel_scaled(uv: vec2, center: vec2, scale: f32) -> vec4 { + return sample_bilinear(tex_a, center + (uv - center) * scale); +} + +@compute @workgroup_size(8, 8) +fn chroma_aberration_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let p = vec2(gid.xy); + let a = textureLoad(tex_a, p, 0); + let uv = (vec2(gid.xy) + vec2(0.5)) / vec2(dims); + let center = u.p[1].xy; + var rgb = vec3( + sample_channel_scaled(uv, center, u.p[0].x).r, + sample_channel_scaled(uv, center, u.p[0].y).g, + sample_channel_scaled(uv, center, u.p[0].z).b, + ); + let defringe = u.p[0].w; + if (defringe > 1e-6) { + // Desaturate where the 3x3 neighbourhood's colour-difference signal swings hard (colour fringes). + var lo = vec3(1.0e9); + var hi = vec3(-1.0e9); + for (var dy = -1; dy <= 1; dy++) { + for (var dx = -1; dx <= 1; dx++) { + let n = load_clamped(tex_a, p + vec2(dx, dy)).rgb; + let l = dot(n, LUMA_709); + let d = vec3(n.r - l, n.g - l, n.b - l); + lo = min(lo, d); + hi = max(hi, d); + } + } + let swing = max(hi.r - lo.r, max(hi.b - lo.b, hi.g - lo.g)); + let amount = clamp(swing * defringe * 2.0, 0.0, 1.0); + rgb = mix(rgb, vec3(dot(rgb, LUMA_709)), amount); + } + store_dst(p, finish(a, vec4(rgb, a.a), gid.xy, dims)); +} -- 2.54.1