1use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use wgpu::util::DeviceExt;
6
7use super::gpu_image::create_texture;
8use super::{
9 histogram_cdf_gpu, histogram_cdf_gpu_profiled, histogram_u8_gpu, histogram_u8_gpu_profiled,
10};
11use super::{GpuImage, GpuImageCdf};
12use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
13
14const LOOKUP_BYTES: u64 = 1024;
15
16#[repr(C)]
17#[derive(Clone, Copy, Pod, Zeroable)]
18struct Params {
19 width: u32,
20 height: u32,
21 groups_x: u32,
22 groups_y: u32,
23}
24
25pub(crate) struct EqualizePipelines {
26 lookup_layout: wgpu::BindGroupLayout,
27 lookup: wgpu::ComputePipeline,
28 apply_layout: wgpu::BindGroupLayout,
29 apply: wgpu::ComputePipeline,
30}
31
32impl EqualizePipelines {
33 fn new(device: &wgpu::Device) -> Self {
34 let buffer = |binding, ty| wgpu::BindGroupLayoutEntry {
35 binding,
36 visibility: wgpu::ShaderStages::COMPUTE,
37 ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None },
38 count: None,
39 };
40 let lookup_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
41 label: Some("gpu-equalize-lookup-layout"),
42 entries: &[
43 buffer(0, wgpu::BufferBindingType::Storage { read_only: true }),
44 buffer(1, wgpu::BufferBindingType::Storage { read_only: false }),
45 ],
46 });
47 let apply_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
48 label: Some("gpu-equalize-apply-layout"),
49 entries: &[
50 buffer(0, wgpu::BufferBindingType::Uniform),
51 wgpu::BindGroupLayoutEntry {
52 binding: 1,
53 visibility: wgpu::ShaderStages::COMPUTE,
54 ty: wgpu::BindingType::Texture {
55 sample_type: wgpu::TextureSampleType::Uint,
56 view_dimension: wgpu::TextureViewDimension::D2,
57 multisampled: false,
58 },
59 count: None,
60 },
61 buffer(2, wgpu::BufferBindingType::Storage { read_only: true }),
62 wgpu::BindGroupLayoutEntry {
63 binding: 3,
64 visibility: wgpu::ShaderStages::COMPUTE,
65 ty: wgpu::BindingType::StorageTexture {
66 access: wgpu::StorageTextureAccess::WriteOnly,
67 format: wgpu::TextureFormat::Rgba8Uint,
68 view_dimension: wgpu::TextureViewDimension::D2,
69 },
70 count: None,
71 },
72 ],
73 });
74 let pipeline = |layout: &wgpu::BindGroupLayout, text: &'static str, entry: &'static str| {
75 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
76 label: Some(entry),
77 source: wgpu::ShaderSource::Wgsl(text.into()),
78 });
79 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
80 label: Some(entry),
81 bind_group_layouts: &[layout],
82 push_constant_ranges: &[],
83 });
84 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
85 label: Some(entry),
86 layout: Some(&layout),
87 module: &shader,
88 entry_point: Some(entry),
89 compilation_options: wgpu::PipelineCompilationOptions::default(),
90 cache: None,
91 })
92 };
93 Self {
94 lookup: pipeline(
95 &lookup_layout,
96 concat!(include_str!("rounding_u32.wgsl"), include_str!("equalize_lookup.wgsl")),
97 "equalize_lookup",
98 ),
99 apply: pipeline(&apply_layout, include_str!("equalize_apply.wgsl"), "equalize_apply"),
100 lookup_layout,
101 apply_layout,
102 }
103 }
104}
105
106fn plan(width: u32, height: u32, limits: &wgpu::Limits) -> SpatialResult<(u32, u32)> {
107 super::histogram::dispatch_plan(width, height, limits)?;
108 if width > limits.max_texture_dimension_2d
109 || height > limits.max_texture_dimension_2d
110 || width > i32::MAX as u32
111 || height > i32::MAX as u32
112 || limits.max_storage_textures_per_shader_stage == 0
113 || limits.max_sampled_textures_per_shader_stage == 0
114 || limits.max_uniform_buffers_per_shader_stage == 0
115 || limits.max_compute_workgroup_size_y < 16
116 {
117 return Err(invalid("GPU equalization requires supported texture dimensions, sampled/storage textures and uniforms"));
118 }
119 let axis =
120 |size: u32| size.div_ceil(16).min(64).min(limits.max_compute_workgroups_per_dimension);
121 Ok((axis(width), axis(height)))
122}
123
124pub fn equalize_histogram_gpu(runtime: &WgpuRuntime, source: &GpuImage) -> SpatialResult<GpuImage> {
132 equalize_with_profiler(runtime, source, None)
133}
134
135pub fn equalize_histogram_gpu_profiled(
138 runtime: &WgpuRuntime,
139 source: &GpuImage,
140 profiler: &mut GpuStageProfiler,
141) -> SpatialResult<GpuImage> {
142 profiler.validate(runtime, 5)?;
143 let result = equalize_with_profiler(runtime, source, Some(profiler));
144 profiler.finish_recording(&result);
145 result
146}
147
148fn equalize_with_profiler(
149 runtime: &WgpuRuntime,
150 source: &GpuImage,
151 mut profiler: Option<&mut GpuStageProfiler>,
152) -> SpatialResult<GpuImage> {
153 source.validate_runtime(runtime)?;
154 if source.channels() != 1 {
155 return Err(invalid("GPU histogram equalization requires one logical channel"));
156 }
157 let groups = plan(source.width(), source.height(), &runtime.device().limits())?;
158 let histogram = match profiler.as_deref_mut() {
159 Some(p) => histogram_u8_gpu_profiled(runtime, source, 0, p)?,
160 None => histogram_u8_gpu(runtime, source, 0)?,
161 };
162 let cdf = match profiler.as_deref_mut() {
163 Some(p) => histogram_cdf_gpu_profiled(runtime, &histogram, p)?,
164 None => histogram_cdf_gpu(runtime, &histogram)?,
165 };
166 let result = apply_equalization(runtime, source, &cdf, groups, profiler);
167 cdf.recycle(runtime);
168 histogram.recycle(runtime);
169 result
170}
171
172fn apply_equalization(
173 runtime: &WgpuRuntime,
174 source: &GpuImage,
175 cdf: &GpuImageCdf,
176 groups: (u32, u32),
177 mut profiler: Option<&mut GpuStageProfiler>,
178) -> SpatialResult<GpuImage> {
179 let pipelines =
180 runtime.image_equalize_pipelines.get_or_init(|| EqualizePipelines::new(runtime.device()));
181 let mut scratch = ScratchBuffers::new(runtime);
182 let lookup = scratch.acquire("gpu-equalize-lookup", LOOKUP_BYTES);
183 let output = create_texture(runtime, source.width(), source.height(), "gpu-equalize-output");
184 let params = Params {
185 width: source.width(),
186 height: source.height(),
187 groups_x: groups.0,
188 groups_y: groups.1,
189 };
190 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
191 label: Some("gpu-equalize-params"),
192 contents: bytemuck::bytes_of(¶ms),
193 usage: wgpu::BufferUsages::UNIFORM,
194 });
195 let lookup_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
196 label: Some("gpu-equalize-lookup-group"),
197 layout: &pipelines.lookup_layout,
198 entries: &[
199 wgpu::BindGroupEntry { binding: 0, resource: cdf.buffer().as_entire_binding() },
200 wgpu::BindGroupEntry { binding: 1, resource: lookup.as_entire_binding() },
201 ],
202 });
203 let source_view = source.view();
204 let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
205 let apply_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
206 label: Some("gpu-equalize-apply-group"),
207 layout: &pipelines.apply_layout,
208 entries: &[
209 wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
210 wgpu::BindGroupEntry {
211 binding: 1,
212 resource: wgpu::BindingResource::TextureView(&source_view),
213 },
214 wgpu::BindGroupEntry { binding: 2, resource: lookup.as_entire_binding() },
215 wgpu::BindGroupEntry {
216 binding: 3,
217 resource: wgpu::BindingResource::TextureView(&output_view),
218 },
219 ],
220 });
221 let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
222 label: Some("gpu-equalize-encoder"),
223 });
224 for (pipeline, bind_group, stage, groups) in [
225 (&pipelines.lookup, &lookup_group, "equalize_histogram_lookup_gpu", (1, 1)),
226 (&pipelines.apply, &apply_group, "equalize_histogram_apply_gpu", groups),
227 ] {
228 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
229 label: Some(stage),
230 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
231 });
232 pass.set_pipeline(pipeline);
233 pass.set_bind_group(0, bind_group, &[]);
234 pass.dispatch_workgroups(groups.0, groups.1, 1);
235 }
236 scratch.submit_and_recycle(encoder);
237 let mut receipt = cdf.receipt().clone();
238 receipt.record_gpu_to_gpu(LOOKUP_BYTES, "equalize_histogram_lookup_gpu");
239 receipt.record_gpu_to_gpu(source.storage_bytes(), "equalize_histogram_apply_gpu");
240 GpuImage::from_parts(
241 runtime,
242 source.width(),
243 source.height(),
244 1,
245 output,
246 source.metadata(),
247 receipt,
248 )
249}
250
251fn invalid(message: &str) -> SpatialError {
252 SpatialError::InvalidArgument(message.to_owned())
253}
254
255#[cfg(all(test, not(target_arch = "wasm32")))]
256mod tests {
257 use super::super::gpu_image::read_staging_bytes;
258 use super::*;
259
260 #[test]
261 fn equalization_plan_bounds_counters_textures_and_dispatch_before_allocation() {
262 let limits = wgpu::Limits::default();
263 assert_eq!(plan(1, 1, &limits).unwrap(), (1, 1));
264 assert_eq!(plan(3840, 2160, &limits).unwrap(), (64, 64));
265 let mut reduced = limits.clone();
266 reduced.max_compute_workgroups_per_dimension = 3;
267 assert_eq!(plan(3840, 2160, &reduced).unwrap(), (3, 3));
268 for (width, height) in
269 [(0, 1), (1, 0), (65_536, 65_536), (limits.max_texture_dimension_2d + 1, 1)]
270 {
271 assert!(plan(width, height, &limits).is_err());
272 }
273 for field in 0..5 {
274 let mut invalid = limits.clone();
275 match field {
276 0 => invalid.max_storage_textures_per_shader_stage = 0,
277 1 => invalid.max_sampled_textures_per_shader_stage = 0,
278 2 => invalid.max_uniform_buffers_per_shader_stage = 0,
279 3 => invalid.max_compute_invocations_per_workgroup = 255,
280 _ => invalid.max_compute_workgroup_size_y = 15,
281 }
282 assert!(plan(17, 19, &invalid).is_err());
283 }
284 }
285
286 fn rounded(value: f64) -> u32 {
287 let floor = value.floor();
288 let fraction = value - floor;
289 (floor as u32) + u32::from(fraction > 0.5 || (fraction == 0.5 && floor as u32 % 2 != 0))
290 }
291
292 fn gcd(mut a: u32, mut b: u32) -> u32 {
293 while b != 0 {
294 (a, b) = (b, a % b);
295 }
296 a
297 }
298
299 #[test]
300 fn gpu_lookup_matches_cpu_binary64_at_half_boundaries_and_maximum_counts() {
301 let runtime = WgpuRuntime::new_headless().unwrap();
302 let pipelines = EqualizePipelines::new(runtime.device());
303 let mut denominators: Vec<_> = (1..=4096).collect();
304 denominators.extend([
305 50,
306 58,
307 162,
308 210,
309 1_000_000,
310 8_294_399,
311 16_777_214,
312 16_777_216,
313 2_147_483_646,
314 u32::MAX - 1,
315 ]);
316 let mut seed = 19u32;
317 for _ in 0..512 {
318 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
319 denominators.push(seed.clamp(1, u32::MAX - 1));
320 }
321 let mut inputs = Vec::new();
322 let mut expected = Vec::new();
323 for d in denominators {
324 let mut numerators: Vec<_> =
325 (0..=255).map(|i| (u64::from(d) * i / 255) as u32).collect();
326 let step = 510 / gcd(d, 510);
327 if step % 2 == 1 {
328 for odd in (step..510).step_by((2 * step) as usize) {
329 let n = (u64::from(odd) * u64::from(d) / 510) as u32;
330 numerators.extend([n.saturating_sub(1), n, (n + 1).min(d)]);
331 }
332 }
333 numerators.sort_unstable();
334 numerators.dedup();
335 for chunk in numerators.chunks(254) {
338 let mut cdf = [1u32; 256];
339 let mut lookup = [0u32; 256];
340 for (i, &n) in chunk.iter().enumerate() {
341 cdf[i + 1] = n + 1;
342 lookup[i + 1] = rounded(f64::from(n) * (255.0 / f64::from(d)));
343 }
344 for i in chunk.len() + 1..256 {
345 cdf[i] = d + 1;
346 lookup[i] = 255;
347 }
348 inputs.extend(cdf);
349 expected.extend(lookup);
350 }
351 }
352 inputs.extend([17u32; 256]);
354 expected.extend(0..256u32);
355 let input = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
356 label: Some("equalize-test-cdfs"),
357 contents: bytemuck::cast_slice(&inputs),
358 usage: wgpu::BufferUsages::STORAGE,
359 });
360 let output = runtime.device().create_buffer(&wgpu::BufferDescriptor {
361 label: Some("equalize-test-lookups"),
362 size: (inputs.len() * 4) as u64,
363 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
364 mapped_at_creation: false,
365 });
366 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
367 label: Some("equalize-test-readback"),
368 size: output.size(),
369 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
370 mapped_at_creation: false,
371 });
372 let mut encoder = runtime.device().create_command_encoder(&Default::default());
373 for row in 0..inputs.len() / 256 {
374 fn binding(buffer: &wgpu::Buffer, row: usize) -> wgpu::BufferBinding<'_> {
375 wgpu::BufferBinding {
376 buffer,
377 offset: row as u64 * LOOKUP_BYTES,
378 size: std::num::NonZeroU64::new(LOOKUP_BYTES),
379 }
380 }
381 let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
382 label: Some("equalize-test-group"),
383 layout: &pipelines.lookup_layout,
384 entries: &[
385 wgpu::BindGroupEntry {
386 binding: 0,
387 resource: wgpu::BindingResource::Buffer(binding(&input, row)),
388 },
389 wgpu::BindGroupEntry {
390 binding: 1,
391 resource: wgpu::BindingResource::Buffer(binding(&output, row)),
392 },
393 ],
394 });
395 let mut pass = encoder.begin_compute_pass(&Default::default());
396 pass.set_pipeline(&pipelines.lookup);
397 pass.set_bind_group(0, &bind_group, &[]);
398 pass.dispatch_workgroups(1, 1, 1);
399 }
400 encoder.copy_buffer_to_buffer(&output, 0, &staging, 0, output.size());
401 runtime.queue().submit(Some(encoder.finish()));
402 let bytes = read_staging_bytes(runtime.device(), &staging, output.size() as usize).unwrap();
403 for (i, (word, expected)) in bytes.chunks_exact(4).zip(expected).enumerate() {
404 let actual = u32::from_le_bytes(word.try_into().unwrap());
405 assert_eq!(
406 actual,
407 expected,
408 "CDF row {}, bin {}, count {}",
409 i / 256,
410 i % 256,
411 inputs[i]
412 );
413 }
414 eprintln!(
415 "Verified {} GPU lookup entries against independent CPU binary64 rounding",
416 inputs.len()
417 );
418 }
419}