oximedia-gpu 0.1.8

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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! GPU blend kernels (CPU simulation via Rayon).
//!
//! Provides parallel image compositing and blending operations that simulate
//! GPU compute-shader dispatch semantics.
//!
//! # Supported blend modes
//!
//! | Mode | Description |
//! |------|-------------|
//! | [`BlendMode::AlphaComposite`] | Porter-Duff "over" compositing |
//! | [`BlendMode::Additive`] | src + dst, clamped to 255 |
//! | [`BlendMode::Multiply`] | src * dst / 255 |
//! | [`BlendMode::Screen`] | 1 - (1-src)*(1-dst) |
//! | [`BlendMode::Overlay`] | Photoshop-style overlay |
//! | [`BlendMode::SoftLight`] | Pegtop soft light formula |
//! | [`BlendMode::Difference`] | abs(src - dst) |
//! | [`BlendMode::Dissolve`] | Random per-pixel src/dst selection by opacity |
//!
//! # Example
//!
//! ```rust
//! use oximedia_gpu::blend_kernel::{BlendKernel, BlendMode};
//!
//! let src = vec![200u8, 100, 50, 255];   // opaque orange
//! let mut dst = vec![0u8, 128, 255, 255]; // opaque blue
//! BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::AlphaComposite, 255)?;
//! # Ok::<(), oximedia_gpu::blend_kernel::BlendError>(())
//! ```

use rayon::prelude::*;
use thiserror::Error;

// ─── Error ────────────────────────────────────────────────────────────────────

/// Errors returned by blend kernel operations.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum BlendError {
    /// Source or destination buffer has incorrect length.
    #[error("Buffer size mismatch: expected {expected}, got {actual}")]
    BufferSizeMismatch { expected: usize, actual: usize },
    /// Image dimensions are zero or invalid.
    #[error("Invalid dimensions: {width}x{height}")]
    InvalidDimensions { width: u32, height: u32 },
    /// Pixel count overflow.
    #[error("Pixel count overflow for {width}x{height}")]
    PixelCountOverflow { width: u32, height: u32 },
    /// Mask length doesn't match pixel count.
    #[error("Mask length mismatch: expected {expected}, got {actual}")]
    MaskLengthMismatch { expected: usize, actual: usize },
}

// ─── BlendMode ───────────────────────────────────────────────────────────────

/// Compositing / blend mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BlendMode {
    /// Porter-Duff "over" — alpha-premultiplied compositing.
    AlphaComposite,
    /// Linear additive blend, clamped to 255.
    Additive,
    /// Photographic multiply (darkens).
    Multiply,
    /// Screen blend (lightens).
    Screen,
    /// Overlay (contrast boost).
    Overlay,
    /// Pegtop soft-light formula.
    SoftLight,
    /// Absolute difference (subtract with abs).
    Difference,
    /// Stochastic dissolve controlled by global opacity.
    Dissolve,
}

impl BlendMode {
    /// Human-readable label.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::AlphaComposite => "alpha_composite",
            Self::Additive => "additive",
            Self::Multiply => "multiply",
            Self::Screen => "screen",
            Self::Overlay => "overlay",
            Self::SoftLight => "soft_light",
            Self::Difference => "difference",
            Self::Dissolve => "dissolve",
        }
    }
}

// ─── BlendStats ──────────────────────────────────────────────────────────────

/// Statistics from a blend operation.
#[derive(Debug, Clone, Default)]
pub struct BlendStats {
    /// Total destination pixels modified.
    pub pixels_blended: u64,
    /// Blend mode used.
    pub mode: Option<BlendMode>,
    /// Global opacity applied (0–255).
    pub opacity: u8,
}

// ─── BlendKernel ─────────────────────────────────────────────────────────────

/// GPU-style image blending kernel (CPU simulation via Rayon).
///
/// Operates on packed RGBA (4 bytes / pixel) buffers.
/// `dst` is modified in place (it acts as both the base and the output).
#[derive(Debug, Clone, Default)]
pub struct BlendKernel;

impl BlendKernel {
    // ── Validation helpers ────────────────────────────────────────────────────

    fn validate_rgba(buf: &[u8], width: u32, height: u32) -> Result<usize, BlendError> {
        if width == 0 || height == 0 {
            return Err(BlendError::InvalidDimensions { width, height });
        }
        let pixels = (width as usize)
            .checked_mul(height as usize)
            .ok_or(BlendError::PixelCountOverflow { width, height })?;
        let expected = pixels * 4;
        if buf.len() != expected {
            return Err(BlendError::BufferSizeMismatch {
                expected,
                actual: buf.len(),
            });
        }
        Ok(pixels)
    }

    // ── Public API ────────────────────────────────────────────────────────────

    /// Blend `src` over `dst` using the specified blend mode and global opacity.
    ///
    /// `opacity` controls how much of `src` is mixed in (0 = invisible, 255 = fully opaque).
    /// The per-pixel alpha in `src` is also respected by all modes.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] if buffers or dimensions are invalid.
    pub fn blend(
        src: &[u8],
        dst: &mut [u8],
        width: u32,
        height: u32,
        mode: BlendMode,
        opacity: u8,
    ) -> Result<BlendStats, BlendError> {
        Self::validate_rgba(src, width, height)?;
        let pixels = Self::validate_rgba(dst, width, height)?;
        let op = opacity as f32 / 255.0;

        src.par_chunks(4)
            .zip(dst.par_chunks_mut(4))
            .for_each(|(s, d)| {
                blend_pixel(s, d, mode, op);
            });

        Ok(BlendStats {
            pixels_blended: pixels as u64,
            mode: Some(mode),
            opacity,
        })
    }

    /// Blend with a per-pixel opacity mask (single channel, one byte per pixel).
    ///
    /// Each pixel's effective opacity is `global_opacity * mask[i] / 255`.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] if any buffer or mask length is invalid.
    pub fn blend_masked(
        src: &[u8],
        dst: &mut [u8],
        mask: &[u8],
        width: u32,
        height: u32,
        mode: BlendMode,
        global_opacity: u8,
    ) -> Result<BlendStats, BlendError> {
        Self::validate_rgba(src, width, height)?;
        let pixels = Self::validate_rgba(dst, width, height)?;
        if mask.len() != pixels {
            return Err(BlendError::MaskLengthMismatch {
                expected: pixels,
                actual: mask.len(),
            });
        }

        let go = global_opacity as f32 / 255.0;

        src.par_chunks(4)
            .zip(dst.par_chunks_mut(4))
            .zip(mask.par_iter())
            .for_each(|((s, d), &m)| {
                let op = go * (m as f32 / 255.0);
                blend_pixel(s, d, mode, op);
            });

        Ok(BlendStats {
            pixels_blended: pixels as u64,
            mode: Some(mode),
            opacity: global_opacity,
        })
    }

    /// Composite multiple layers using Porter-Duff "over" operator.
    ///
    /// Layers are composited from bottom to top (index 0 is the base).
    /// Each `(buffer, opacity)` entry is blended onto the accumulator.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] if any layer has incorrect dimensions.
    pub fn composite_layers(
        layers: &[(&[u8], u8)],
        width: u32,
        height: u32,
    ) -> Result<Vec<u8>, BlendError> {
        if width == 0 || height == 0 {
            return Err(BlendError::InvalidDimensions { width, height });
        }
        let pixels = (width as usize)
            .checked_mul(height as usize)
            .ok_or(BlendError::PixelCountOverflow { width, height })?;
        let buf_size = pixels * 4;

        for (i, (layer, _)) in layers.iter().enumerate() {
            if layer.len() != buf_size {
                return Err(BlendError::BufferSizeMismatch {
                    expected: buf_size,
                    actual: layer.len(),
                });
            }
            let _ = i;
        }

        if layers.is_empty() {
            return Ok(vec![0u8; buf_size]);
        }

        // Start with a transparent black canvas.
        let mut acc = vec![0u8; buf_size];
        for (layer, opacity) in layers {
            let op = *opacity as f32 / 255.0;
            layer
                .par_chunks(4)
                .zip(acc.par_chunks_mut(4))
                .for_each(|(s, d)| {
                    blend_pixel(s, d, BlendMode::AlphaComposite, op);
                });
        }
        Ok(acc)
    }

    /// Apply a constant color tint (multiply by a solid RGBA color).
    ///
    /// Each pixel is multiplied component-wise by `tint / 255`.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] if buffer or dimensions are invalid.
    pub fn apply_tint(
        src: &[u8],
        dst: &mut [u8],
        width: u32,
        height: u32,
        tint: [u8; 4],
    ) -> Result<(), BlendError> {
        Self::validate_rgba(src, width, height)?;
        Self::validate_rgba(dst, width, height)?;

        src.par_chunks(4)
            .zip(dst.par_chunks_mut(4))
            .for_each(|(s, d)| {
                for c in 0..4 {
                    let v = (s[c] as u32 * tint[c] as u32 + 127) / 255;
                    d[c] = v.min(255) as u8;
                }
            });
        Ok(())
    }

    /// Premultiply RGB channels by the alpha channel in place.
    ///
    /// Input: `[R, G, B, A]` straight alpha.
    /// Output: `[R*A/255, G*A/255, B*A/255, A]` premultiplied.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] on dimension or buffer mismatch.
    pub fn premultiply_alpha(buf: &mut [u8], width: u32, height: u32) -> Result<(), BlendError> {
        Self::validate_rgba(buf, width, height)?;
        buf.par_chunks_mut(4).for_each(|px| {
            let a = px[3] as u32;
            for c in 0..3 {
                px[c] = ((px[c] as u32 * a + 127) / 255) as u8;
            }
        });
        Ok(())
    }

    /// Un-premultiply alpha (divide RGB by alpha).
    ///
    /// Pixels with `A = 0` are left as `[0, 0, 0, 0]`.
    ///
    /// # Errors
    ///
    /// Returns [`BlendError`] on dimension or buffer mismatch.
    pub fn unpremultiply_alpha(buf: &mut [u8], width: u32, height: u32) -> Result<(), BlendError> {
        Self::validate_rgba(buf, width, height)?;
        buf.par_chunks_mut(4).for_each(|px| {
            let a = px[3] as f32;
            if a > 0.0 {
                for c in 0..3 {
                    px[c] = (px[c] as f32 / a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
            }
        });
        Ok(())
    }
}

// ─── Pixel-level blend functions ──────────────────────────────────────────────

/// Apply one blend operation to a single `[R,G,B,A]` pixel pair.
///
/// `s` is the source pixel, `d` is the destination (modified in place).
/// `opacity` is the global layer opacity in `[0.0, 1.0]`.
fn blend_pixel(s: &[u8], d: &mut [u8], mode: BlendMode, opacity: f32) {
    let sa = (s[3] as f32 / 255.0) * opacity;
    match mode {
        BlendMode::AlphaComposite => alpha_composite(s, d, sa),
        BlendMode::Additive => additive(s, d, sa),
        BlendMode::Multiply => multiply(s, d, sa),
        BlendMode::Screen => screen(s, d, sa),
        BlendMode::Overlay => overlay(s, d, sa),
        BlendMode::SoftLight => soft_light(s, d, sa),
        BlendMode::Difference => difference(s, d, sa),
        BlendMode::Dissolve => dissolve(s, d, sa),
    }
}

/// Porter-Duff "over": `Cout = Cs * As + Cd * Ad * (1 - As)`.
fn alpha_composite(s: &[u8], d: &mut [u8], sa: f32) {
    let da = d[3] as f32 / 255.0;
    let out_a = sa + da * (1.0 - sa);
    if out_a < 1e-9 {
        d[0] = 0;
        d[1] = 0;
        d[2] = 0;
        d[3] = 0;
        return;
    }
    for c in 0..3 {
        let sc = s[c] as f32 / 255.0;
        let dc = d[c] as f32 / 255.0;
        let out_c = (sc * sa + dc * da * (1.0 - sa)) / out_a;
        d[c] = (out_c * 255.0).round().clamp(0.0, 255.0) as u8;
    }
    d[3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
}

/// Additive blend: `Cout = clamp(Cd + Cs * Sa, 0, 255)`.
fn additive(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let v = d[c] as f32 + s[c] as f32 * sa;
        d[c] = v.round().clamp(0.0, 255.0) as u8;
    }
    // Alpha: additive does not change destination alpha.
}

/// Multiply blend: `Cout = lerp(Cd, Cd * Cs / 255, Sa)`.
fn multiply(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let dc = d[c] as f32;
        let sc = s[c] as f32;
        let blended = dc * sc / 255.0;
        d[c] = lerp_channel(dc, blended, sa);
    }
}

/// Screen blend: `Cout = lerp(Cd, 255 - (255-Cd)*(255-Cs)/255, Sa)`.
fn screen(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let dc = d[c] as f32;
        let sc = s[c] as f32;
        let blended = 255.0 - (255.0 - dc) * (255.0 - sc) / 255.0;
        d[c] = lerp_channel(dc, blended, sa);
    }
}

/// Overlay blend: multiply if dst < 0.5, screen otherwise.
fn overlay(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let dc = d[c] as f32 / 255.0;
        let sc = s[c] as f32 / 255.0;
        let blended = if dc < 0.5 {
            2.0 * dc * sc
        } else {
            1.0 - 2.0 * (1.0 - dc) * (1.0 - sc)
        };
        d[c] = lerp_channel(d[c] as f32, blended * 255.0, sa);
    }
}

/// Pegtop soft-light: `2*Cd*Cs + Cd²*(1-2*Cs)` (all in [0,1]).
fn soft_light(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let dc = d[c] as f32 / 255.0;
        let sc = s[c] as f32 / 255.0;
        let blended = 2.0 * dc * sc + dc * dc * (1.0 - 2.0 * sc);
        d[c] = lerp_channel(d[c] as f32, blended * 255.0, sa);
    }
}

/// Difference blend: `Cout = lerp(Cd, abs(Cd - Cs), Sa)`.
fn difference(s: &[u8], d: &mut [u8], sa: f32) {
    for c in 0..3 {
        let dc = d[c] as f32;
        let sc = s[c] as f32;
        let blended = (dc - sc).abs();
        d[c] = lerp_channel(dc, blended, sa);
    }
}

/// Dissolve: use source pixel when opacity threshold is met.
///
/// Deterministic per-pixel: uses a hash of the channel index to simulate
/// stochastic per-pixel selection without an RNG.
fn dissolve(s: &[u8], d: &mut [u8], sa: f32) {
    // Deterministic "random" threshold using a simple fixed pattern.
    // In real GPU shaders this uses a noise texture; here we use a xor-shift
    // of the combined src/dst byte values to avoid needing a true RNG.
    let hash =
        xorshift32(s[0] as u32 ^ (s[1] as u32 * 17) ^ (d[0] as u32 * 31) ^ (d[1] as u32 * 7));
    let threshold = (hash & 0xFF) as f32 / 255.0;
    if sa > threshold {
        // Use source pixel
        for c in 0..3 {
            d[c] = s[c];
        }
        d[3] = s[3];
    }
    // else keep destination unchanged
}

// ─── Private helpers ──────────────────────────────────────────────────────────

/// Linear interpolation: `a + (b - a) * t`, returns u8.
#[inline]
fn lerp_channel(a: f32, b: f32, t: f32) -> u8 {
    (a + (b - a) * t).round().clamp(0.0, 255.0) as u8
}

/// Simple xorshift32 for deterministic dissolve without RNG.
#[inline]
fn xorshift32(mut x: u32) -> u32 {
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    x
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── BlendMode ─────────────────────────────────────────────────────────────

    #[test]
    fn test_blend_mode_labels() {
        assert_eq!(BlendMode::AlphaComposite.label(), "alpha_composite");
        assert_eq!(BlendMode::Additive.label(), "additive");
        assert_eq!(BlendMode::Multiply.label(), "multiply");
        assert_eq!(BlendMode::Screen.label(), "screen");
        assert_eq!(BlendMode::Overlay.label(), "overlay");
        assert_eq!(BlendMode::SoftLight.label(), "soft_light");
        assert_eq!(BlendMode::Difference.label(), "difference");
        assert_eq!(BlendMode::Dissolve.label(), "dissolve");
    }

    // ── Error handling ────────────────────────────────────────────────────────

    #[test]
    fn test_blend_invalid_dims() {
        let src = vec![0u8; 4];
        let mut dst = vec![0u8; 4];
        let err = BlendKernel::blend(&src, &mut dst, 0, 1, BlendMode::Additive, 255);
        assert!(matches!(err, Err(BlendError::InvalidDimensions { .. })));
    }

    #[test]
    fn test_blend_buffer_mismatch() {
        let src = vec![0u8; 8]; // wrong: 1×1 = 4
        let mut dst = vec![0u8; 4];
        let err = BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Additive, 255);
        assert!(matches!(err, Err(BlendError::BufferSizeMismatch { .. })));
    }

    #[test]
    fn test_blend_masked_mask_mismatch() {
        let src = vec![255u8; 4 * 4 * 4];
        let mut dst = vec![0u8; 4 * 4 * 4];
        let mask = vec![255u8; 10]; // wrong size
        let err = BlendKernel::blend_masked(&src, &mut dst, &mask, 4, 4, BlendMode::Multiply, 255);
        assert!(matches!(err, Err(BlendError::MaskLengthMismatch { .. })));
    }

    // ── Opacity=0 preserves destination ──────────────────────────────────────

    #[test]
    fn test_opacity_zero_preserves_dst() -> Result<(), BlendError> {
        let src: Vec<u8> = vec![255, 0, 0, 255]; // opaque red
        let original_dst = vec![0u8, 128, 255, 255]; // opaque blue
        let mut dst = original_dst.clone();
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::AlphaComposite, 0)?;
        // With opacity=0 the src contributes nothing; dst should be almost unchanged.
        for (orig, &out) in original_dst.iter().zip(dst.iter()) {
            let diff = (*orig as i16 - out as i16).abs();
            assert!(diff <= 1, "channel diff={diff}");
        }
        Ok(())
    }

    // ── Opacity=255 opaque source covers destination (AlphaComposite) ─────────

    #[test]
    fn test_alpha_composite_fully_opaque_src() -> Result<(), BlendError> {
        let src = vec![200u8, 100, 50, 255]; // fully opaque
        let mut dst = vec![0u8, 0, 0, 255];
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::AlphaComposite, 255)?;
        assert_eq!(dst[0], 200);
        assert_eq!(dst[1], 100);
        assert_eq!(dst[2], 50);
        assert_eq!(dst[3], 255);
        Ok(())
    }

    // ── Additive ──────────────────────────────────────────────────────────────

    #[test]
    fn test_additive_blend_clamps_to_255() -> Result<(), BlendError> {
        let src = vec![200u8, 200, 200, 255];
        let mut dst = vec![100u8, 100, 100, 255];
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Additive, 255)?;
        assert_eq!(dst[0], 255, "200+100=300 → clamp to 255");
        Ok(())
    }

    #[test]
    fn test_additive_blend_zero_src() -> Result<(), BlendError> {
        let src = vec![0u8, 0, 0, 255];
        let original = vec![100u8, 150, 200, 255];
        let mut dst = original.clone();
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Additive, 255)?;
        assert_eq!(dst[..3], original[..3]);
        Ok(())
    }

    // ── Multiply ──────────────────────────────────────────────────────────────

    #[test]
    fn test_multiply_with_white_src_unchanged() -> Result<(), BlendError> {
        let src = vec![255u8, 255, 255, 255]; // white multiplier
        let original = vec![100u8, 150, 200, 255];
        let mut dst = original.clone();
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Multiply, 255)?;
        // Multiply with white → dst * 255/255 = dst
        for c in 0..3 {
            let diff = (original[c] as i16 - dst[c] as i16).abs();
            assert!(diff <= 1, "channel {c}: diff={diff}");
        }
        Ok(())
    }

    #[test]
    fn test_multiply_with_black_src_yields_zero() -> Result<(), BlendError> {
        let src = vec![0u8, 0, 0, 255]; // black multiplier
        let mut dst = vec![200u8, 150, 100, 255];
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Multiply, 255)?;
        // Multiply with black → 0
        for c in 0..3 {
            assert_eq!(dst[c], 0, "channel {c} should be 0");
        }
        Ok(())
    }

    // ── Screen ────────────────────────────────────────────────────────────────

    #[test]
    fn test_screen_with_black_src_unchanged() -> Result<(), BlendError> {
        let src = vec![0u8, 0, 0, 255]; // black screen → no change
        let original = vec![100u8, 150, 200, 255];
        let mut dst = original.clone();
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Screen, 255)?;
        for c in 0..3 {
            let diff = (original[c] as i16 - dst[c] as i16).abs();
            assert!(diff <= 1, "channel {c}: diff={diff}");
        }
        Ok(())
    }

    #[test]
    fn test_screen_with_white_src_yields_white() -> Result<(), BlendError> {
        let src = vec![255u8, 255, 255, 255]; // white screen → white
        let mut dst = vec![100u8, 150, 200, 255];
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Screen, 255)?;
        for c in 0..3 {
            assert_eq!(
                dst[c], 255,
                "channel {c} should be 255 after screen with white"
            );
        }
        Ok(())
    }

    // ── Difference ────────────────────────────────────────────────────────────

    #[test]
    fn test_difference_with_same_src_dst_yields_black() -> Result<(), BlendError> {
        let src = vec![100u8, 150, 200, 255];
        let mut dst = vec![100u8, 150, 200, 255];
        BlendKernel::blend(&src, &mut dst, 1, 1, BlendMode::Difference, 255)?;
        for c in 0..3 {
            assert_eq!(dst[c], 0, "difference of equal values should be 0");
        }
        Ok(())
    }

    // ── Masked blend ──────────────────────────────────────────────────────────

    #[test]
    fn test_masked_blend_all_opaque() -> Result<(), BlendError> {
        let w = 2u32;
        let h = 2u32;
        let src = vec![255u8; (w * h * 4) as usize];
        let mut dst = vec![0u8; (w * h * 4) as usize];
        let mask = vec![255u8; (w * h) as usize]; // fully opaque mask
        BlendKernel::blend_masked(&src, &mut dst, &mask, w, h, BlendMode::AlphaComposite, 255)?;
        // All dst pixels should become white (src is all 255 opaque)
        for &v in &dst {
            assert_eq!(v, 255);
        }
        Ok(())
    }

    #[test]
    fn test_masked_blend_all_transparent_preserves_dst() -> Result<(), BlendError> {
        let w = 2u32;
        let h = 2u32;
        let src = vec![255u8; (w * h * 4) as usize];
        let original_dst = vec![100u8; (w * h * 4) as usize];
        let mut dst = original_dst.clone();
        let mask = vec![0u8; (w * h) as usize]; // fully transparent mask
        BlendKernel::blend_masked(&src, &mut dst, &mask, w, h, BlendMode::AlphaComposite, 255)?;
        // With mask=0, alpha=0, dst should be unchanged
        assert_eq!(dst, original_dst);
        Ok(())
    }

    // ── Layer compositing ─────────────────────────────────────────────────────

    #[test]
    fn test_composite_layers_empty_returns_transparent() -> Result<(), BlendError> {
        let result = BlendKernel::composite_layers(&[], 4, 4)?;
        assert_eq!(result.len(), 4 * 4 * 4);
        assert!(result.iter().all(|&v| v == 0));
        Ok(())
    }

    #[test]
    fn test_composite_layers_single_opaque() -> Result<(), BlendError> {
        let layer = vec![200u8, 100, 50, 255]; // 1×1 opaque orange
        let result = BlendKernel::composite_layers(&[(&layer, 255)], 1, 1)?;
        assert_eq!(result.len(), 4);
        // Should match the layer
        assert_eq!(result[0], 200);
        assert_eq!(result[1], 100);
        assert_eq!(result[2], 50);
        Ok(())
    }

    // ── Tint ──────────────────────────────────────────────────────────────────

    #[test]
    fn test_apply_tint_white_tint_unchanged() -> Result<(), BlendError> {
        let src = vec![100u8, 150, 200, 255];
        let mut dst = vec![0u8; 4];
        BlendKernel::apply_tint(&src, &mut dst, 1, 1, [255, 255, 255, 255])?;
        for c in 0..3 {
            let diff = (src[c] as i16 - dst[c] as i16).abs();
            assert!(diff <= 1, "channel {c}: diff={diff}");
        }
        Ok(())
    }

    #[test]
    fn test_apply_tint_black_tint_yields_black() -> Result<(), BlendError> {
        let src = vec![200u8, 150, 100, 255];
        let mut dst = vec![0u8; 4];
        BlendKernel::apply_tint(&src, &mut dst, 1, 1, [0, 0, 0, 0])?;
        assert_eq!(dst[0], 0);
        assert_eq!(dst[1], 0);
        assert_eq!(dst[2], 0);
        Ok(())
    }

    // ── Premultiply / unpremultiply ───────────────────────────────────────────

    #[test]
    fn test_premultiply_alpha_full_opaque() -> Result<(), BlendError> {
        let mut buf = vec![200u8, 100, 50, 255];
        BlendKernel::premultiply_alpha(&mut buf, 1, 1)?;
        // With alpha=255, channels stay the same
        assert_eq!(buf[0], 200);
        assert_eq!(buf[1], 100);
        assert_eq!(buf[2], 50);
        Ok(())
    }

    #[test]
    fn test_premultiply_alpha_half_opacity() -> Result<(), BlendError> {
        let mut buf = vec![200u8, 200, 200, 128];
        BlendKernel::premultiply_alpha(&mut buf, 1, 1)?;
        // ~200 * 128 / 255 ≈ 100
        let expected = (200u32 * 128 + 127) / 255;
        let diff = (buf[0] as i32 - expected as i32).abs();
        assert!(
            diff <= 1,
            "premultiplied R: got {}, expected ~{}",
            buf[0],
            expected
        );
        Ok(())
    }

    #[test]
    fn test_unpremultiply_alpha_zero_alpha() -> Result<(), BlendError> {
        let mut buf = vec![100u8, 100, 100, 0]; // fully transparent
        BlendKernel::unpremultiply_alpha(&mut buf, 1, 1)?;
        // alpha=0 → no change (stays 0)
        assert_eq!(buf[0], 100); // left unchanged when alpha=0
        Ok(())
    }

    #[test]
    fn test_premultiply_unpremultiply_roundtrip() -> Result<(), BlendError> {
        let original = vec![200u8, 150, 100, 200];
        let mut buf = original.clone();
        BlendKernel::premultiply_alpha(&mut buf, 1, 1)?;
        BlendKernel::unpremultiply_alpha(&mut buf, 1, 1)?;
        for c in 0..3 {
            let diff = (original[c] as i16 - buf[c] as i16).abs();
            assert!(
                diff <= 2,
                "channel {c}: orig={} back={} diff={diff}",
                original[c],
                buf[c]
            );
        }
        Ok(())
    }

    // ── Stats ─────────────────────────────────────────────────────────────────

    #[test]
    fn test_blend_stats_returned() -> Result<(), BlendError> {
        let src = vec![0u8; 4 * 4 * 4];
        let mut dst = vec![0u8; 4 * 4 * 4];
        let stats = BlendKernel::blend(&src, &mut dst, 4, 4, BlendMode::Screen, 200)?;
        assert_eq!(stats.pixels_blended, 16);
        assert_eq!(stats.mode, Some(BlendMode::Screen));
        assert_eq!(stats.opacity, 200);
        Ok(())
    }
}