| 1 | //! OCIO, Layer, Metadata, Generator & Utility built-ins: |
| 2 | //! - `OCIOColorSpace`, `OCIODisplay`, `OCIOFileTransform` |
| 3 | //! - `LayerMuxer`, `LayerRegex`, `LayerRemover`, `Swizzler` |
| 4 | //! - `Fuse.FLS_CopyMetadata`, `Fuse.SetMetaDataTC`, `Dummy` |
| 5 | //! - `MultiText`, `Fields`, `KeyStretcher`, `ChromaticAberrationRemoval` |
| 6 | //! |
| 7 | //! Colour tools reuse the `color_lut` colorimetry, transfer-curve and LUT/CDL pipelines; the ops |
| 8 | //! with no existing equivalent live in `layer_ocio.wgsl` (`filterable: false` + `textureLoad`, |
| 9 | //! WriteOnly storage output patched per format, no `read_write` storage textures). |
| 10 | |
| 11 | mod file_transform; |
| 12 | mod layers; |
| 13 | mod ocio; |
| 14 | mod pattern; |
| 15 | mod swizzle_fields; |
| 16 | #[cfg(test)] |
| 17 | mod tests; |
| 18 | mod utility; |
| 19 | |
| 20 | use super::*; |
| 21 | use std::num::NonZeroU64; |
| 22 | |
| 23 | const LAYER_OCIO_WGSL: &str = include_str!("../shaders/layer_ocio.wgsl"); |
| 24 | const LO_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 25 | const ENTRY_POINTS: [&str; 4] = ["ocio_display_op", "swizzler_op", "fields_op", "chroma_aberration_op"]; |
| 26 | |
| 27 | #[derive(Clone, Copy)] |
| 28 | enum LayerOcioOp { |
| 29 | OcioDisplay, |
| 30 | Swizzler, |
| 31 | Fields, |
| 32 | ChromaAberration, |
| 33 | } |
| 34 | |
| 35 | struct LayerOcioFormatPipelines { |
| 36 | bgl: wgpu::BindGroupLayout, |
| 37 | ops: [wgpu::ComputePipeline; ENTRY_POINTS.len()], |
| 38 | } |
| 39 | |
| 40 | pub(crate) struct LayerOcioPipelines { |
| 41 | uniform_stride: u32, |
| 42 | uniform_chunks: Vec<wgpu::Buffer>, |
| 43 | uniform_cursor: u32, |
| 44 | by_format: HashMap<(wgpu::TextureFormat, bool), LayerOcioFormatPipelines>, |
| 45 | } |
| 46 | |
| 47 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { |
| 48 | wgpu::BindGroupLayoutEntry { |
| 49 | binding, |
| 50 | visibility: wgpu::ShaderStages::COMPUTE, |
| 51 | ty: wgpu::BindingType::Texture { |
| 52 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 53 | view_dimension: wgpu::TextureViewDimension::D2, |
| 54 | multisampled: false, |
| 55 | }, |
| 56 | count: None, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | fn patch_storage_format(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 61 | let storage_fmt = match format { |
| 62 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 63 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 64 | _ => "rgba8unorm", |
| 65 | }; |
| 66 | let mut src = LAYER_OCIO_WGSL.replace( |
| 67 | "texture_storage_2d<rgba8unorm, write>", |
| 68 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 69 | ); |
| 70 | if hdr_float { |
| 71 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 72 | } |
| 73 | src |
| 74 | } |
| 75 | |
| 76 | impl LayerOcioPipelines { |
| 77 | pub(super) fn new(device: &wgpu::Device) -> Self { |
| 78 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 79 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 80 | Self { |
| 81 | uniform_stride: uniform_size.div_ceil(min_align) * min_align, |
| 82 | uniform_chunks: Vec::new(), |
| 83 | uniform_cursor: 0, |
| 84 | by_format: HashMap::new(), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub(super) fn reset_uniform_cursor(&mut self) { |
| 89 | self.uniform_cursor = 0; |
| 90 | } |
| 91 | |
| 92 | pub(super) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 93 | self.uniform_cursor = 0; |
| 94 | self.uniform_chunks.truncate(max_chunks); |
| 95 | } |
| 96 | |
| 97 | fn alloc_uniform_slot(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, params: &UniformParams) -> (usize, u32) { |
| 98 | let slot = self.uniform_cursor; |
| 99 | let chunk_idx = (slot / LO_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 100 | while chunk_idx >= self.uniform_chunks.len() { |
| 101 | self.uniform_chunks.push(device.create_buffer(&wgpu::BufferDescriptor { |
| 102 | label: Some("layer-ocio-params-ring"), |
| 103 | size: u64::from(LO_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride), |
| 104 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 105 | mapped_at_creation: false, |
| 106 | })); |
| 107 | } |
| 108 | let offset = (slot % LO_UNIFORM_SLOTS_PER_CHUNK) * self.uniform_stride; |
| 109 | queue.write_buffer(&self.uniform_chunks[chunk_idx], u64::from(offset), bytemuck::bytes_of(params)); |
| 110 | self.uniform_cursor = slot + 1; |
| 111 | (chunk_idx, offset) |
| 112 | } |
| 113 | |
| 114 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 115 | if self.by_format.contains_key(&(format, hdr_float)) { |
| 116 | return; |
| 117 | } |
| 118 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 119 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 120 | label: Some("layer-ocio-bgl"), |
| 121 | entries: &[ |
| 122 | unfilterable_tex_entry(0), |
| 123 | unfilterable_tex_entry(1), |
| 124 | unfilterable_tex_entry(2), |
| 125 | unfilterable_tex_entry(3), |
| 126 | wgpu::BindGroupLayoutEntry { |
| 127 | binding: 4, |
| 128 | visibility: wgpu::ShaderStages::COMPUTE, |
| 129 | ty: wgpu::BindingType::StorageTexture { |
| 130 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 131 | format, |
| 132 | view_dimension: wgpu::TextureViewDimension::D2, |
| 133 | }, |
| 134 | count: None, |
| 135 | }, |
| 136 | wgpu::BindGroupLayoutEntry { |
| 137 | binding: 5, |
| 138 | visibility: wgpu::ShaderStages::COMPUTE, |
| 139 | ty: wgpu::BindingType::Buffer { |
| 140 | ty: wgpu::BufferBindingType::Uniform, |
| 141 | has_dynamic_offset: true, |
| 142 | min_binding_size: NonZeroU64::new(u_size), |
| 143 | }, |
| 144 | count: None, |
| 145 | }, |
| 146 | ], |
| 147 | }); |
| 148 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 149 | label: Some("layer-ocio-pl"), |
| 150 | bind_group_layouts: &[Some(&bgl)], |
| 151 | immediate_size: 0, |
| 152 | }); |
| 153 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 154 | label: Some("layer-ocio-wgsl"), |
| 155 | source: wgpu::ShaderSource::Wgsl(patch_storage_format(format, hdr_float).into()), |
| 156 | }); |
| 157 | let ops = ENTRY_POINTS.map(|entry| { |
| 158 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 159 | label: Some(entry), |
| 160 | layout: Some(&pl), |
| 161 | module: &module, |
| 162 | entry_point: Some(entry), |
| 163 | compilation_options: Default::default(), |
| 164 | cache: None, |
| 165 | }) |
| 166 | }); |
| 167 | self.by_format.insert((format, hdr_float), LayerOcioFormatPipelines { bgl, ops }); |
| 168 | } |
| 169 | |
| 170 | #[allow(clippy::too_many_arguments)] |
| 171 | fn dispatch( |
| 172 | &mut self, |
| 173 | device: &wgpu::Device, |
| 174 | queue: &wgpu::Queue, |
| 175 | enc: &mut wgpu::CommandEncoder, |
| 176 | op: LayerOcioOp, |
| 177 | views: [&wgpu::TextureView; 4], |
| 178 | dst: &CachedTexture, |
| 179 | params: &UniformParams, |
| 180 | ) { |
| 181 | let hdr_float = dst.depth.is_float(); |
| 182 | self.ensure_format(device, dst.format, hdr_float); |
| 183 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 184 | let fp = &self.by_format[&(dst.format, hdr_float)]; |
| 185 | let mut entries: Vec<wgpu::BindGroupEntry> = views |
| 186 | .iter() |
| 187 | .enumerate() |
| 188 | .map(|(i, v)| wgpu::BindGroupEntry { binding: i as u32, resource: wgpu::BindingResource::TextureView(v) }) |
| 189 | .collect(); |
| 190 | entries.push(wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }); |
| 191 | entries.push(wgpu::BindGroupEntry { |
| 192 | binding: 5, |
| 193 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 194 | buffer: &self.uniform_chunks[chunk_idx], |
| 195 | offset: 0, |
| 196 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 197 | }), |
| 198 | }); |
| 199 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 200 | label: Some("layer-ocio-bg"), |
| 201 | layout: &fp.bgl, |
| 202 | entries: &entries, |
| 203 | }); |
| 204 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 205 | label: Some("layer-ocio-pass"), |
| 206 | timestamp_writes: None, |
| 207 | }); |
| 208 | pass.set_pipeline(&fp.ops[op as usize]); |
| 209 | pass.set_bind_group(0, &bg, &[offset]); |
| 210 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /// Blend / EffectMask / Process* state shared by every colour or spatial filter. |
| 215 | struct Effect { |
| 216 | blend: f32, |
| 217 | mbm: bool, |
| 218 | mask: Option<CachedTexture>, |
| 219 | mask_inv: bool, |
| 220 | skip: [f32; 4], |
| 221 | } |
| 222 | |
| 223 | fn num_any(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f64 { |
| 224 | keys.iter() |
| 225 | .find(|&&k| node.inputs.contains_key(k)) |
| 226 | .map_or(default, |&k| comp.eval_number(node, k, time, default, expr)) |
| 227 | } |
| 228 | |
| 229 | fn str_any<'a>(node: &'a Node, keys: &[&str]) -> Option<&'a str> { |
| 230 | keys.iter().find_map(|k| node.static_str(k)) |
| 231 | } |
| 232 | |
| 233 | fn conn_any(comp: &Comp, node: &Node, ports: &[&str]) -> Option<NodeId> { |
| 234 | ports.iter().find_map(|p| node.connected_node(p).and_then(|s| comp.find_node(s))) |
| 235 | } |
| 236 | |
| 237 | /// Lowercased alphanumerics only, so `"Rec.709 (sRGB)"` matches `"rec709srgb"`. |
| 238 | fn squash(s: &str) -> String { |
| 239 | s.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect() |
| 240 | } |
| 241 | |
| 242 | impl Engine { |
| 243 | fn layer_ocio_pipelines(&self) -> &RefCell<LayerOcioPipelines> { |
| 244 | self.layer_ocio.get_or_init(|| RefCell::new(LayerOcioPipelines::new(&self.device))) |
| 245 | } |
| 246 | |
| 247 | /// Resolves `Blend` and the EffectMask for `src`; `Err(src)` when the effect is an identity |
| 248 | /// (`Blend == 0` without `MultiplyByMask`). A masked source is cropped to the canvas so mask UVs line up. |
| 249 | #[allow(clippy::too_many_arguments)] |
| 250 | fn effect_prologue( |
| 251 | &mut self, |
| 252 | comp: &Comp, |
| 253 | node: &Node, |
| 254 | time: f64, |
| 255 | src: CachedTexture, |
| 256 | enc: &mut wgpu::CommandEncoder, |
| 257 | visiting: &mut HashSet<(NodeId, i64)>, |
| 258 | stats: &mut EvalStats, |
| 259 | ) -> Result<(CachedTexture, Effect), CachedTexture> { |
| 260 | let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; |
| 261 | let mbm = self.multiplies_by_mask(comp, node, time); |
| 262 | if blend <= 1e-6 && !mbm { |
| 263 | return Err(src); |
| 264 | } |
| 265 | let src = if Self::resolve_effect_mask_id(comp, node).is_some() { self.crop_to_canvas(enc, src) } else { src }; |
| 266 | let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); |
| 267 | let skip = self.process_skip(comp, node, time); |
| 268 | Ok((src, Effect { blend, mbm, mask, mask_inv, skip })) |
| 269 | } |
| 270 | |
| 271 | /// Dispatches one `layer_ocio.wgsl` op over `src` (binding 0) with `b` (binding 1, `src` when `None`) |
| 272 | /// and `z` (binding 2, a dummy when `None`); the result keeps `src`'s DoD and aux channels. |
| 273 | #[allow(clippy::too_many_arguments)] |
| 274 | fn run_lo_filter( |
| 275 | &mut self, |
| 276 | node: &Node, |
| 277 | tag: &'static str, |
| 278 | op: LayerOcioOp, |
| 279 | src: &CachedTexture, |
| 280 | b: Option<&CachedTexture>, |
| 281 | z: Option<&wgpu::TextureView>, |
| 282 | fx: &Effect, |
| 283 | depth: BitDepth, |
| 284 | mut u: UniformParams, |
| 285 | frame_i: i64, |
| 286 | enc: &mut wgpu::CommandEncoder, |
| 287 | stats: &mut EvalStats, |
| 288 | ) -> CachedTexture { |
| 289 | u.p[14] = [fx.blend, b2f(fx.mask.is_some()), b2f(fx.mask_inv), b2f(fx.mbm)]; |
| 290 | u.p[15] = fx.skip; |
| 291 | let b_hash = b.map_or(0, |t| t.content_hash); |
| 292 | let mask_hash = fx.mask.as_ref().map_or(0, |m| m.content_hash); |
| 293 | let key = self.make_key(node, tag, src.size, &[src.content_hash, b_hash, mask_hash, depth as u64], bytemuck::cast_slice(&u.p)); |
| 294 | if let Some(hit) = self.cache.get(key, node.id, frame_i) { |
| 295 | stats.cache_hits += 1; |
| 296 | return hit; |
| 297 | } |
| 298 | stats.cache_misses += 1; |
| 299 | stats.nodes_evaluated += 1; |
| 300 | let mut dst = self.alloc_tex_like(src, depth, key); |
| 301 | let views = [ |
| 302 | &src.view, |
| 303 | b.map_or(&src.view, |t| &t.view), |
| 304 | z.unwrap_or(&self.dummy.view), |
| 305 | fx.mask.as_ref().map_or(&self.dummy.view, |m| &m.view), |
| 306 | ]; |
| 307 | self.layer_ocio_pipelines() |
| 308 | .borrow_mut() |
| 309 | .dispatch(&self.device, &self.queue, enc, op, views, &dst, &u); |
| 310 | dst.set_aux(src.aux.clone()); |
| 311 | self.cache.insert(key, dst.clone(), node.id, frame_i); |
| 312 | dst |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn b2f(v: bool) -> f32 { |
| 317 | if v { 1.0 } else { 0.0 } |
| 318 | } |