| 1 | //! ColorFX, ColorSpaceTransform, Gamut, FilmLookCreator, OCIOCDLTransform, |
| 2 | //! Complete LUT category (`FileLUT`, `Fuse.LUTCubeCreator`, `Fuse.LUTCubeApply`, |
| 3 | //! `Fuse.LUTCubeAnalyzer`), and DaVinci Resolve I/O (`MediaIn`, `MediaOut`). |
| 4 | //! |
| 5 | //! All texture inputs use `TextureSampleType::Float { filterable: false }` with |
| 6 | //! `textureLoad`, outputs are `WriteOnly` storage textures, and 3D LUTs are packed |
| 7 | //! into 2D `Rgba32Float` textures for 100% WebGPU / `wasm32` parity. |
| 8 | |
| 9 | pub(in crate::eval) mod color_fx; |
| 10 | pub(in crate::eval) mod colorimetry; |
| 11 | mod cst_gamut; |
| 12 | mod film_look; |
| 13 | pub mod lut_io; |
| 14 | mod resolve_io; |
| 15 | #[cfg(test)] |
| 16 | mod tests; |
| 17 | |
| 18 | use super::*; |
| 19 | use std::num::NonZeroU64; |
| 20 | use std::sync::Arc; |
| 21 | |
| 22 | const COLOR_LUT_WGSL: &str = include_str!("../shaders/color_lut.wgsl"); |
| 23 | const CL_UNIFORM_SLOTS_PER_CHUNK: u32 = 512; |
| 24 | |
| 25 | #[derive(Clone, Copy)] |
| 26 | pub(in crate::eval) enum ColorLutOp { |
| 27 | ColorMatrix, |
| 28 | SetCanvasColor, |
| 29 | ChromaticAdaptation, |
| 30 | ColorSpaceTransform, |
| 31 | GamutLimiter, |
| 32 | GamutMapping, |
| 33 | FilmLookGrade, |
| 34 | FilmLookExtract, |
| 35 | FilmLookFinish, |
| 36 | OcioCdl, |
| 37 | FileLut, |
| 38 | LutCubeCreator, |
| 39 | LutCubeApply, |
| 40 | LutCubeAnalyzer, |
| 41 | } |
| 42 | |
| 43 | struct ColorLutFormatPipelines { |
| 44 | bgl: wgpu::BindGroupLayout, |
| 45 | color_matrix: wgpu::ComputePipeline, |
| 46 | set_canvas_color: wgpu::ComputePipeline, |
| 47 | chromatic_adaptation: wgpu::ComputePipeline, |
| 48 | color_space_transform: wgpu::ComputePipeline, |
| 49 | gamut_limiter: wgpu::ComputePipeline, |
| 50 | gamut_mapping: wgpu::ComputePipeline, |
| 51 | film_look_grade: wgpu::ComputePipeline, |
| 52 | film_look_extract: wgpu::ComputePipeline, |
| 53 | film_look_finish: wgpu::ComputePipeline, |
| 54 | ocio_cdl: wgpu::ComputePipeline, |
| 55 | file_lut: wgpu::ComputePipeline, |
| 56 | lut_cube_creator: wgpu::ComputePipeline, |
| 57 | lut_cube_apply: wgpu::ComputePipeline, |
| 58 | lut_cube_analyzer: wgpu::ComputePipeline, |
| 59 | } |
| 60 | |
| 61 | impl ColorLutFormatPipelines { |
| 62 | fn pipeline(&self, op: ColorLutOp) -> &wgpu::ComputePipeline { |
| 63 | match op { |
| 64 | ColorLutOp::ColorMatrix => &self.color_matrix, |
| 65 | ColorLutOp::SetCanvasColor => &self.set_canvas_color, |
| 66 | ColorLutOp::ChromaticAdaptation => &self.chromatic_adaptation, |
| 67 | ColorLutOp::ColorSpaceTransform => &self.color_space_transform, |
| 68 | ColorLutOp::GamutLimiter => &self.gamut_limiter, |
| 69 | ColorLutOp::GamutMapping => &self.gamut_mapping, |
| 70 | ColorLutOp::FilmLookGrade => &self.film_look_grade, |
| 71 | ColorLutOp::FilmLookExtract => &self.film_look_extract, |
| 72 | ColorLutOp::FilmLookFinish => &self.film_look_finish, |
| 73 | ColorLutOp::OcioCdl => &self.ocio_cdl, |
| 74 | ColorLutOp::FileLut => &self.file_lut, |
| 75 | ColorLutOp::LutCubeCreator => &self.lut_cube_creator, |
| 76 | ColorLutOp::LutCubeApply => &self.lut_cube_apply, |
| 77 | ColorLutOp::LutCubeAnalyzer => &self.lut_cube_analyzer, |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | pub(crate) struct CachedLutGpu { |
| 83 | pub(self) _texture: Arc<wgpu::Texture>, |
| 84 | pub(self) view: Arc<wgpu::TextureView>, |
| 85 | } |
| 86 | |
| 87 | pub(crate) struct ColorLutPipelines { |
| 88 | uniform_stride: u32, |
| 89 | uniform_chunks: Vec<wgpu::Buffer>, |
| 90 | uniform_cursor: u32, |
| 91 | formats: HashMap<(wgpu::TextureFormat, bool), ColorLutFormatPipelines>, |
| 92 | lut_gpu_cache: HashMap<u64, CachedLutGpu>, |
| 93 | } |
| 94 | |
| 95 | fn build_cl_wgsl(format: wgpu::TextureFormat, hdr_float: bool) -> String { |
| 96 | let mut src = COLOR_LUT_WGSL.to_owned(); |
| 97 | let storage_fmt = match format { |
| 98 | wgpu::TextureFormat::Rgba16Float => "rgba16float", |
| 99 | wgpu::TextureFormat::Rgba32Float => "rgba32float", |
| 100 | _ => "rgba8unorm", |
| 101 | }; |
| 102 | if storage_fmt != "rgba8unorm" { |
| 103 | src = src.replace( |
| 104 | "texture_storage_2d<rgba8unorm, write>", |
| 105 | &format!("texture_storage_2d<{storage_fmt}, write>"), |
| 106 | ); |
| 107 | } |
| 108 | if hdr_float { |
| 109 | src = src.replace("const HDR_FLOAT: bool = false;", "const HDR_FLOAT: bool = true;"); |
| 110 | } |
| 111 | src |
| 112 | } |
| 113 | |
| 114 | fn unfilterable_tex_entry(binding: u32) -> wgpu::BindGroupLayoutEntry { |
| 115 | wgpu::BindGroupLayoutEntry { |
| 116 | binding, |
| 117 | visibility: wgpu::ShaderStages::COMPUTE, |
| 118 | ty: wgpu::BindingType::Texture { |
| 119 | sample_type: wgpu::TextureSampleType::Float { filterable: false }, |
| 120 | view_dimension: wgpu::TextureViewDimension::D2, |
| 121 | multisampled: false, |
| 122 | }, |
| 123 | count: None, |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl ColorLutPipelines { |
| 128 | pub(crate) fn new(device: &wgpu::Device) -> Self { |
| 129 | let uniform_size = std::mem::size_of::<UniformParams>() as u32; |
| 130 | let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1); |
| 131 | let uniform_stride = uniform_size.div_ceil(min_align) * min_align; |
| 132 | Self { |
| 133 | uniform_stride, |
| 134 | uniform_chunks: Vec::new(), |
| 135 | uniform_cursor: 0, |
| 136 | formats: HashMap::new(), |
| 137 | lut_gpu_cache: HashMap::new(), |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | pub(crate) fn reset_uniform_cursor(&mut self) { |
| 142 | self.uniform_cursor = 0; |
| 143 | } |
| 144 | |
| 145 | pub(crate) fn trim_uniform_chunks(&mut self, max_chunks: usize) { |
| 146 | self.uniform_cursor = 0; |
| 147 | if self.uniform_chunks.len() > max_chunks { |
| 148 | self.uniform_chunks.truncate(max_chunks); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub(crate) fn clear_lut_cache(&mut self) { |
| 153 | self.lut_gpu_cache.clear(); |
| 154 | } |
| 155 | |
| 156 | fn alloc_uniform_slot( |
| 157 | &mut self, |
| 158 | device: &wgpu::Device, |
| 159 | queue: &wgpu::Queue, |
| 160 | params: &UniformParams, |
| 161 | ) -> (usize, u32) { |
| 162 | let slot_global = self.uniform_cursor; |
| 163 | let chunk_idx = (slot_global / CL_UNIFORM_SLOTS_PER_CHUNK) as usize; |
| 164 | let slot_in_chunk = slot_global % CL_UNIFORM_SLOTS_PER_CHUNK; |
| 165 | while chunk_idx >= self.uniform_chunks.len() { |
| 166 | let size = u64::from(CL_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride); |
| 167 | let buf = device.create_buffer(&wgpu::BufferDescriptor { |
| 168 | label: Some("color-lut-params-ring"), |
| 169 | size, |
| 170 | usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, |
| 171 | mapped_at_creation: false, |
| 172 | }); |
| 173 | self.uniform_chunks.push(buf); |
| 174 | } |
| 175 | let offset = slot_in_chunk * self.uniform_stride; |
| 176 | queue.write_buffer( |
| 177 | &self.uniform_chunks[chunk_idx], |
| 178 | u64::from(offset), |
| 179 | bytemuck::bytes_of(params), |
| 180 | ); |
| 181 | self.uniform_cursor = slot_global + 1; |
| 182 | (chunk_idx, offset) |
| 183 | } |
| 184 | |
| 185 | pub(in crate::eval) fn get_or_upload_lut_rgba32f( |
| 186 | &mut self, |
| 187 | device: &wgpu::Device, |
| 188 | queue: &wgpu::Queue, |
| 189 | hash: u64, |
| 190 | size: [u32; 2], |
| 191 | rgba_f32: &[f32], |
| 192 | ) -> Arc<wgpu::TextureView> { |
| 193 | if let Some(hit) = self.lut_gpu_cache.get(&hash) { |
| 194 | return hit.view.clone(); |
| 195 | } |
| 196 | if self.lut_gpu_cache.len() >= 64 { |
| 197 | self.lut_gpu_cache.clear(); |
| 198 | } |
| 199 | let tex = Arc::new(device.create_texture(&wgpu::TextureDescriptor { |
| 200 | label: Some("file-lut-2d-packed"), |
| 201 | size: wgpu::Extent3d { |
| 202 | width: size[0].max(1), |
| 203 | height: size[1].max(1), |
| 204 | depth_or_array_layers: 1, |
| 205 | }, |
| 206 | mip_level_count: 1, |
| 207 | sample_count: 1, |
| 208 | dimension: wgpu::TextureDimension::D2, |
| 209 | format: wgpu::TextureFormat::Rgba32Float, |
| 210 | usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, |
| 211 | view_formats: &[], |
| 212 | })); |
| 213 | queue.write_texture( |
| 214 | tex.as_image_copy(), |
| 215 | bytemuck::cast_slice(rgba_f32), |
| 216 | wgpu::TexelCopyBufferLayout { |
| 217 | offset: 0, |
| 218 | bytes_per_row: Some(size[0].max(1) * 16), |
| 219 | rows_per_image: Some(size[1].max(1)), |
| 220 | }, |
| 221 | wgpu::Extent3d { |
| 222 | width: size[0].max(1), |
| 223 | height: size[1].max(1), |
| 224 | depth_or_array_layers: 1, |
| 225 | }, |
| 226 | ); |
| 227 | let view = Arc::new(tex.create_view(&wgpu::TextureViewDescriptor::default())); |
| 228 | self.lut_gpu_cache.insert(hash, CachedLutGpu { _texture: tex, view: view.clone() }); |
| 229 | view |
| 230 | } |
| 231 | |
| 232 | fn ensure_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, hdr_float: bool) { |
| 233 | if self.formats.contains_key(&(format, hdr_float)) { |
| 234 | return; |
| 235 | } |
| 236 | let u_size = std::mem::size_of::<UniformParams>() as u64; |
| 237 | let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { |
| 238 | label: Some("color-lut-bgl"), |
| 239 | entries: &[ |
| 240 | unfilterable_tex_entry(0), |
| 241 | unfilterable_tex_entry(1), |
| 242 | unfilterable_tex_entry(2), |
| 243 | unfilterable_tex_entry(3), |
| 244 | wgpu::BindGroupLayoutEntry { |
| 245 | binding: 4, |
| 246 | visibility: wgpu::ShaderStages::COMPUTE, |
| 247 | ty: wgpu::BindingType::StorageTexture { |
| 248 | access: wgpu::StorageTextureAccess::WriteOnly, |
| 249 | format, |
| 250 | view_dimension: wgpu::TextureViewDimension::D2, |
| 251 | }, |
| 252 | count: None, |
| 253 | }, |
| 254 | wgpu::BindGroupLayoutEntry { |
| 255 | binding: 5, |
| 256 | visibility: wgpu::ShaderStages::COMPUTE, |
| 257 | ty: wgpu::BindingType::Buffer { |
| 258 | ty: wgpu::BufferBindingType::Uniform, |
| 259 | has_dynamic_offset: true, |
| 260 | min_binding_size: NonZeroU64::new(u_size), |
| 261 | }, |
| 262 | count: None, |
| 263 | }, |
| 264 | ], |
| 265 | }); |
| 266 | let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { |
| 267 | label: Some("color-lut-pl"), |
| 268 | bind_group_layouts: &[Some(&bgl)], |
| 269 | immediate_size: 0, |
| 270 | }); |
| 271 | let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 272 | label: Some("color-lut-wgsl"), |
| 273 | source: wgpu::ShaderSource::Wgsl(build_cl_wgsl(format, hdr_float).into()), |
| 274 | }); |
| 275 | let mk = |entry: &str| { |
| 276 | device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { |
| 277 | label: Some(entry), |
| 278 | layout: Some(&pl), |
| 279 | module: &module, |
| 280 | entry_point: Some(entry), |
| 281 | compilation_options: Default::default(), |
| 282 | cache: None, |
| 283 | }) |
| 284 | }; |
| 285 | self.formats.insert( |
| 286 | (format, hdr_float), |
| 287 | ColorLutFormatPipelines { |
| 288 | bgl, |
| 289 | color_matrix: mk("color_matrix_op"), |
| 290 | set_canvas_color: mk("set_canvas_color_op"), |
| 291 | chromatic_adaptation: mk("chromatic_adaptation_op"), |
| 292 | color_space_transform: mk("color_space_transform_op"), |
| 293 | gamut_limiter: mk("gamut_limiter_op"), |
| 294 | gamut_mapping: mk("gamut_mapping_op"), |
| 295 | film_look_grade: mk("film_look_grade_op"), |
| 296 | film_look_extract: mk("film_look_extract_op"), |
| 297 | film_look_finish: mk("film_look_finish_op"), |
| 298 | ocio_cdl: mk("ocio_cdl_op"), |
| 299 | file_lut: mk("file_lut_op"), |
| 300 | lut_cube_creator: mk("lut_cube_creator_op"), |
| 301 | lut_cube_apply: mk("lut_cube_apply_op"), |
| 302 | lut_cube_analyzer: mk("lut_cube_analyzer_op"), |
| 303 | }, |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | #[allow(clippy::too_many_arguments)] |
| 308 | fn dispatch( |
| 309 | &mut self, |
| 310 | device: &wgpu::Device, |
| 311 | queue: &wgpu::Queue, |
| 312 | enc: &mut wgpu::CommandEncoder, |
| 313 | op: ColorLutOp, |
| 314 | views: [&wgpu::TextureView; 4], |
| 315 | dst: &CachedTexture, |
| 316 | params: &UniformParams, |
| 317 | ) { |
| 318 | let hdr_float = dst.depth.is_float(); |
| 319 | self.ensure_format(device, dst.format, hdr_float); |
| 320 | let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params); |
| 321 | let entry = &self.formats[&(dst.format, hdr_float)]; |
| 322 | let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { |
| 323 | label: Some("color-lut-bg"), |
| 324 | layout: &entry.bgl, |
| 325 | entries: &[ |
| 326 | wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(views[0]) }, |
| 327 | wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(views[1]) }, |
| 328 | wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(views[2]) }, |
| 329 | wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(views[3]) }, |
| 330 | wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(&dst.view) }, |
| 331 | wgpu::BindGroupEntry { |
| 332 | binding: 5, |
| 333 | resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { |
| 334 | buffer: &self.uniform_chunks[chunk_idx], |
| 335 | offset: 0, |
| 336 | size: NonZeroU64::new(std::mem::size_of::<UniformParams>() as u64), |
| 337 | }), |
| 338 | }, |
| 339 | ], |
| 340 | }); |
| 341 | let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { |
| 342 | label: Some("color-lut-pass"), |
| 343 | timestamp_writes: None, |
| 344 | }); |
| 345 | pass.set_pipeline(entry.pipeline(op)); |
| 346 | pass.set_bind_group(0, &bg, &[offset]); |
| 347 | pass.dispatch_workgroups(dst.size[0].div_ceil(8), dst.size[1].div_ceil(8), 1); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | impl Engine { |
| 352 | pub(super) fn color_lut_pipelines(&self) -> &RefCell<ColorLutPipelines> { |
| 353 | self.color_lut_pipelines |
| 354 | .get_or_init(|| RefCell::new(ColorLutPipelines::new(&self.device))) |
| 355 | } |
| 356 | |
| 357 | #[allow(clippy::too_many_arguments)] |
| 358 | pub(in crate::eval) fn dispatch_cl( |
| 359 | &self, |
| 360 | enc: &mut wgpu::CommandEncoder, |
| 361 | op: ColorLutOp, |
| 362 | views: [&wgpu::TextureView; 4], |
| 363 | dst: &CachedTexture, |
| 364 | params: &UniformParams, |
| 365 | ) { |
| 366 | self.color_lut_pipelines() |
| 367 | .borrow_mut() |
| 368 | .dispatch(&self.device, &self.queue, enc, op, views, dst, params); |
| 369 | } |
| 370 | } |