oximedia-gpu 0.1.0

GPU compute pipeline using WGPU for OxiMedia - cross-platform acceleration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! GPU compute pipeline using WGPU for `OxiMedia`
//!
//! This crate provides a cross-platform GPU acceleration layer using WGPU,
//! supporting Vulkan, Metal, DirectX 12, and WebGPU backends.
//!
//! # Features
//!
//! - Color space conversions (RGB ↔ YUV with BT.601, BT.709, BT.2020)
//! - Image scaling (nearest, bilinear, bicubic)
//! - Convolution filters (blur, sharpen, edge detection)
//! - Transform operations (DCT, FFT)
//! - Automatic CPU fallback
//! - Multi-GPU support
//!
//! # Example
//!
//! ```no_run
//! use oximedia_gpu::GpuContext;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let ctx = GpuContext::new()?;
//!
//! let input = vec![0u8; 1920 * 1080 * 4];
//! let mut output = vec![0u8; 1920 * 1080 * 4];
//!
//! ctx.rgb_to_yuv(&input, &mut output)?;
//! # Ok(())
//! # }
//! ```

#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_wrap)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]

// Core modules
pub mod buffer;
pub mod device;
pub mod ops;
pub mod shader;

// New comprehensive modules
pub mod accelerator;
pub mod backend;
pub mod cache;
pub mod compiler;
pub mod compute;
pub mod kernels;
pub mod memory;
pub mod queue;
pub mod sync;

// GPU compute operation modules
pub mod histogram;
pub mod motion_detect;
pub mod pipeline;
pub mod texture;
pub mod video_process;

// New kernel / pass / shader-param modules
pub mod compute_pass;
pub mod kernel;
pub mod shader_params;

// Wave-8 new modules
pub mod compute_dispatch;
pub mod memory_pool;
pub mod shader_cache;

// Wave-9 new modules
pub mod gpu_buffer;
pub mod gpu_fence;
pub mod render_pass;

// Wave-10 new modules
pub mod command_buffer;
pub mod resource_manager;
pub mod sync_primitive;

// Wave-11 new modules
pub mod descriptor_set;
pub mod gpu_stats;
pub mod viewport;

// Wave-12 new modules
pub mod gpu_profiler;
pub mod sampler;
pub mod vertex_buffer;

// Wave-13 new modules
pub mod fence_pool;
pub mod gpu_timer;
pub mod upload_queue;

// Wave-14 new modules
pub mod buffer_copy;
pub mod occupancy;
pub mod workgroup;

use std::sync::Arc;
use thiserror::Error;

// Accelerator exports
pub use accelerator::{AcceleratorBuilder, CpuAccelerator, GpuAccelerator, WgpuAccelerator};

// Core exports
pub use buffer::{BufferType, GpuBuffer};
pub use device::{GpuDevice, GpuDeviceInfo};
pub use ops::{ColorSpaceConversion, FilterOperation, ScaleOperation, TransformOperation};

// Backend exports
pub use backend::{Backend, BackendCapabilities, BackendType, CpuBackend, VulkanBackend};

// Cache exports
pub use cache::{CacheStats, PipelineCache, ShaderCache};

// Compiler exports
pub use compiler::{
    CompilationError, CompilationOptions, OptimizationLevel, ShaderCompiler, ShaderPreprocessor,
};

// Compute exports
pub use compute::{
    ComputeExecutor, ComputePassBuilder, ComputePipelineHandle, ComputePipelineManager,
    DispatchHelper,
};

// Kernels exports
pub use kernels::{
    ColorConversionKernel, ConvolutionKernel, FilterKernel, ReduceKernel, ReduceOp, ResizeFilter,
    ResizeKernel, TransformKernel, TransformType,
};

// Memory exports
pub use memory::{ManagedBuffer, MemoryAllocator, MemoryPool, MemoryStats};

// Queue exports
pub use queue::{
    AsyncSubmission, BatchSubmitter, CommandBufferBuilder, CommandQueue, QueueManager, QueueType,
};

// Sync exports
pub use sync::{Barrier, Event, Fence, Semaphore};

// Video processing exports
pub use histogram::{ChannelHistogram, ImageHistogram};
pub use motion_detect::{MotionAnalysis, MotionDetector, MotionRegion, Sensitivity};
pub use pipeline::{GpuPipeline, PipelineMetrics, PipelineNode, PipelineStage};
pub use texture::{TextureDescriptor, TextureFormat, TexturePool};
pub use video_process::{FrameProcessConfig, FrameProcessResult, VideoFrameProcessor};

/// Error types for GPU operations
#[derive(Debug, Error)]
pub enum GpuError {
    /// Device initialization failed
    #[error("Failed to initialize GPU device: {0}")]
    DeviceInit(String),

    /// Adapter selection failed
    #[error("No suitable GPU adapter found")]
    NoAdapter,

    /// Device request failed
    #[error("Failed to request GPU device: {0}")]
    DeviceRequest(String),

    /// Buffer creation failed
    #[error("Failed to create GPU buffer: {0}")]
    BufferCreation(String),

    /// Shader compilation failed
    #[error("Failed to compile shader: {0}")]
    ShaderCompilation(String),

    /// Pipeline creation failed
    #[error("Failed to create compute pipeline: {0}")]
    PipelineCreation(String),

    /// Command submission failed
    #[error("Failed to submit GPU commands: {0}")]
    CommandSubmission(String),

    /// Buffer mapping failed
    #[error("Failed to map GPU buffer: {0}")]
    BufferMapping(String),

    /// Invalid dimensions
    #[error("Invalid image dimensions: {width}x{height}")]
    InvalidDimensions { width: u32, height: u32 },

    /// Invalid buffer size
    #[error("Invalid buffer size: expected {expected}, got {actual}")]
    InvalidBufferSize { expected: usize, actual: usize },

    /// Operation not supported
    #[error("Operation not supported: {0}")]
    NotSupported(String),

    /// Internal error
    #[error("Internal GPU error: {0}")]
    Internal(String),
}

pub type Result<T> = std::result::Result<T, GpuError>;

/// GPU context for compute operations
///
/// This is the main entry point for GPU-accelerated operations.
/// It manages device selection, resource allocation, and command submission.
pub struct GpuContext {
    device: Arc<GpuDevice>,
}

impl GpuContext {
    /// Create a new GPU context with automatic device selection
    ///
    /// This will select the most suitable GPU device available on the system.
    /// If no GPU is available, an error is returned.
    ///
    /// # Errors
    ///
    /// Returns an error if no suitable GPU device is found or if device
    /// initialization fails.
    pub fn new() -> Result<Self> {
        let device = GpuDevice::new(None)?;
        Ok(Self {
            device: Arc::new(device),
        })
    }

    /// Create a new GPU context with a specific device
    ///
    /// # Arguments
    ///
    /// * `device_index` - Index of the device to use (from `list_devices`)
    ///
    /// # Errors
    ///
    /// Returns an error if the device index is invalid or if device
    /// initialization fails.
    pub fn with_device(device_index: usize) -> Result<Self> {
        let device = GpuDevice::new(Some(device_index))?;
        Ok(Self {
            device: Arc::new(device),
        })
    }

    /// List available GPU devices
    ///
    /// Returns information about all GPU devices available on the system.
    pub fn list_devices() -> Result<Vec<GpuDeviceInfo>> {
        GpuDevice::list_devices()
    }

    /// Get information about the current device
    #[must_use]
    pub fn device_info(&self) -> &GpuDeviceInfo {
        self.device.info()
    }

    /// Convert RGB to YUV (BT.601)
    ///
    /// # Arguments
    ///
    /// * `input` - Input RGB buffer (packed RGBA format)
    /// * `output` - Output YUV buffer (packed YUVA format)
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    pub fn rgb_to_yuv(&self, input: &[u8], output: &mut [u8]) -> Result<()> {
        if input.len() != output.len() {
            return Err(GpuError::InvalidBufferSize {
                expected: input.len(),
                actual: output.len(),
            });
        }

        if input.len() % 4 != 0 {
            return Err(GpuError::InvalidBufferSize {
                expected: (input.len() / 4) * 4,
                actual: input.len(),
            });
        }

        let width = ((input.len() / 4) as f32).sqrt() as u32;
        let height = width;

        ops::ColorSpaceConversion::rgb_to_yuv(
            &self.device,
            input,
            output,
            width,
            height,
            ops::ColorSpace::BT601,
        )
    }

    /// Convert YUV to RGB (BT.601)
    ///
    /// # Arguments
    ///
    /// * `input` - Input YUV buffer (packed YUVA format)
    /// * `output` - Output RGB buffer (packed RGBA format)
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    pub fn yuv_to_rgb(&self, input: &[u8], output: &mut [u8]) -> Result<()> {
        if input.len() != output.len() {
            return Err(GpuError::InvalidBufferSize {
                expected: input.len(),
                actual: output.len(),
            });
        }

        if input.len() % 4 != 0 {
            return Err(GpuError::InvalidBufferSize {
                expected: (input.len() / 4) * 4,
                actual: input.len(),
            });
        }

        let width = ((input.len() / 4) as f32).sqrt() as u32;
        let height = width;

        ops::ColorSpaceConversion::yuv_to_rgb(
            &self.device,
            input,
            output,
            width,
            height,
            ops::ColorSpace::BT601,
        )
    }

    /// Scale an image using bilinear interpolation
    ///
    /// # Arguments
    ///
    /// * `input` - Input image buffer (packed RGBA format)
    /// * `src_width` - Source image width
    /// * `src_height` - Source image height
    /// * `output` - Output image buffer (packed RGBA format)
    /// * `dst_width` - Destination image width
    /// * `dst_height` - Destination image height
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    pub fn scale_bilinear(
        &self,
        input: &[u8],
        src_width: u32,
        src_height: u32,
        output: &mut [u8],
        dst_width: u32,
        dst_height: u32,
    ) -> Result<()> {
        ops::ScaleOperation::scale(
            &self.device,
            input,
            src_width,
            src_height,
            output,
            dst_width,
            dst_height,
            ops::ScaleFilter::Bilinear,
        )
    }

    /// Scale an image using bicubic interpolation
    ///
    /// # Arguments
    ///
    /// * `input` - Input image buffer (packed RGBA format)
    /// * `src_width` - Source image width
    /// * `src_height` - Source image height
    /// * `output` - Output image buffer (packed RGBA format)
    /// * `dst_width` - Destination image width
    /// * `dst_height` - Destination image height
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    pub fn scale_bicubic(
        &self,
        input: &[u8],
        src_width: u32,
        src_height: u32,
        output: &mut [u8],
        dst_width: u32,
        dst_height: u32,
    ) -> Result<()> {
        ops::ScaleOperation::scale(
            &self.device,
            input,
            src_width,
            src_height,
            output,
            dst_width,
            dst_height,
            ops::ScaleFilter::Bicubic,
        )
    }

    /// Apply Gaussian blur
    ///
    /// # Arguments
    ///
    /// * `input` - Input image buffer (packed RGBA format)
    /// * `output` - Output image buffer (packed RGBA format)
    /// * `width` - Image width
    /// * `height` - Image height
    /// * `sigma` - Blur radius (standard deviation)
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    #[allow(clippy::too_many_arguments)]
    pub fn gaussian_blur(
        &self,
        input: &[u8],
        output: &mut [u8],
        width: u32,
        height: u32,
        sigma: f32,
    ) -> Result<()> {
        ops::FilterOperation::gaussian_blur(&self.device, input, output, width, height, sigma)
    }

    /// Apply sharpening filter
    ///
    /// # Arguments
    ///
    /// * `input` - Input image buffer (packed RGBA format)
    /// * `output` - Output image buffer (packed RGBA format)
    /// * `width` - Image width
    /// * `height` - Image height
    /// * `amount` - Sharpening strength
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    #[allow(clippy::too_many_arguments)]
    pub fn sharpen(
        &self,
        input: &[u8],
        output: &mut [u8],
        width: u32,
        height: u32,
        amount: f32,
    ) -> Result<()> {
        ops::FilterOperation::sharpen(&self.device, input, output, width, height, amount)
    }

    /// Detect edges using Sobel operator
    ///
    /// # Arguments
    ///
    /// * `input` - Input image buffer (packed RGBA format)
    /// * `output` - Output image buffer (packed RGBA format)
    /// * `width` - Image width
    /// * `height` - Image height
    ///
    /// # Errors
    ///
    /// Returns an error if buffer sizes are invalid or if the GPU operation fails.
    pub fn edge_detect(
        &self,
        input: &[u8],
        output: &mut [u8],
        width: u32,
        height: u32,
    ) -> Result<()> {
        ops::FilterOperation::edge_detect(&self.device, input, output, width, height)
    }

    /// Compute 2D DCT (Discrete Cosine Transform)
    ///
    /// # Arguments
    ///
    /// * `input` - Input data (f32 values)
    /// * `output` - Output DCT coefficients
    /// * `width` - Data width (must be multiple of 8)
    /// * `height` - Data height (must be multiple of 8)
    ///
    /// # Errors
    ///
    /// Returns an error if dimensions are invalid or if the GPU operation fails.
    pub fn dct_2d(&self, input: &[f32], output: &mut [f32], width: u32, height: u32) -> Result<()> {
        ops::TransformOperation::dct_2d(&self.device, input, output, width, height)
    }

    /// Compute 2D IDCT (Inverse Discrete Cosine Transform)
    ///
    /// # Arguments
    ///
    /// * `input` - Input DCT coefficients
    /// * `output` - Output reconstructed data
    /// * `width` - Data width (must be multiple of 8)
    /// * `height` - Data height (must be multiple of 8)
    ///
    /// # Errors
    ///
    /// Returns an error if dimensions are invalid or if the GPU operation fails.
    pub fn idct_2d(
        &self,
        input: &[f32],
        output: &mut [f32],
        width: u32,
        height: u32,
    ) -> Result<()> {
        ops::TransformOperation::idct_2d(&self.device, input, output, width, height)
    }

    /// Wait for all GPU operations to complete
    ///
    /// This is useful for synchronization and benchmarking.
    pub fn wait(&self) {
        self.device.wait();
    }
}

impl Default for GpuContext {
    fn default() -> Self {
        Self::new().expect("Failed to create GPU context")
    }
}