libviprs 0.1.4

A pure-Rust, thread-safe image pyramiding engine for blueprint PDFs and raster images
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
use crate::raster::{Raster, RasterError};

/// Downscale a raster by 2x using a box filter (area averaging).
///
/// Each 2x2 block in the source maps to one pixel in the output.
/// For odd dimensions, the last row/column is averaged with fewer samples.
/// This is the workhorse of the pyramid builder: each pyramid level is
/// produced by applying `downscale_half` to the level above it.
///
/// # Example usage
///
/// - [test_resize_quarter](https://github.com/libviprs/libviprs-tests/blob/main/tests/ported_resample.rs)
///   chains two `downscale_half` calls to produce a quarter-size image and
///   verifies the resulting dimensions.
pub fn downscale_half(src: &Raster) -> Result<Raster, RasterError> {
    let fmt = src.format();

    if fmt.has_alpha() {
        downscale_half_alpha(src)
    } else {
        downscale_half_noalpha(src)
    }
}

/// Downscale without alpha — all channels averaged uniformly.
/// Matches libvips `SHRINK_TYPE_MEAN_INT`: `(sum + 2) >> 2` for 4 pixels.
fn downscale_half_noalpha(src: &Raster) -> Result<Raster, RasterError> {
    let dst_w = src.width().div_ceil(2);
    let dst_h = src.height().div_ceil(2);
    let fmt = src.format();
    let bpp = fmt.bytes_per_pixel();
    let bpc = fmt.bytes_per_channel();
    let channels = fmt.channels();
    let src_stride = src.stride();
    let src_data = src.data();

    let mut dst = vec![0u8; dst_w as usize * dst_h as usize * bpp];

    for dy in 0..dst_h {
        for dx in 0..dst_w {
            let sx = dx * 2;
            let sy = dy * 2;

            let x_count = if sx + 1 < src.width() { 2u32 } else { 1 };
            let y_count = if sy + 1 < src.height() { 2u32 } else { 1 };

            let dst_offset = (dy as usize * dst_w as usize + dx as usize) * bpp;

            for c in 0..channels {
                let mut sum: u32 = 0;
                let count = x_count * y_count;

                for oy in 0..y_count {
                    for ox in 0..x_count {
                        let src_offset =
                            (sy + oy) as usize * src_stride + (sx + ox) as usize * bpp + c * bpc;

                        if bpc == 1 {
                            sum += src_data[src_offset] as u32;
                        } else {
                            let val = u16::from_ne_bytes([
                                src_data[src_offset],
                                src_data[src_offset + 1],
                            ]);
                            sum += val as u32;
                        }
                    }
                }

                let avg = (sum + count / 2) / count;

                if bpc == 1 {
                    dst[dst_offset + c] = avg as u8;
                } else {
                    let bytes = (avg as u16).to_ne_bytes();
                    dst[dst_offset + c * 2] = bytes[0];
                    dst[dst_offset + c * 2 + 1] = bytes[1];
                }
            }
        }
    }

    Raster::new(dst_w, dst_h, fmt, dst)
}

/// Downscale with alpha-weighted averaging for color channels.
///
/// Matches libvips `SHRINK_ALPHA_TYPE` from `region.c`:
/// - Alpha channel (last band) is averaged normally: `(a1+a2+a3+a4) / 4`
/// - Color channels are weighted by their pixel's alpha:
///   `(a1*c1 + a2*c2 + a3*c3 + a4*c4) / (4 * avg_alpha)`
/// - If the averaged alpha is zero, all channels are set to zero
///
/// This prevents transparent pixels from darkening opaque neighbors
/// when averaged together.
fn downscale_half_alpha(src: &Raster) -> Result<Raster, RasterError> {
    let dst_w = src.width().div_ceil(2);
    let dst_h = src.height().div_ceil(2);
    let fmt = src.format();
    let bpp = fmt.bytes_per_pixel();
    let bpc = fmt.bytes_per_channel();
    let channels = fmt.channels();
    let alpha_idx = channels - 1;
    let src_stride = src.stride();
    let src_data = src.data();

    let mut dst = vec![0u8; dst_w as usize * dst_h as usize * bpp];

    for dy in 0..dst_h {
        for dx in 0..dst_w {
            let sx = dx * 2;
            let sy = dy * 2;

            let x_count = if sx + 1 < src.width() { 2u32 } else { 1 };
            let y_count = if sy + 1 < src.height() { 2u32 } else { 1 };
            let count = x_count * y_count;

            let dst_offset = (dy as usize * dst_w as usize + dx as usize) * bpp;

            // Gather alpha values from the contributing pixels
            let mut alphas = [0.0f64; 4];
            let mut pixel_offsets = [0usize; 4];
            let mut n = 0;
            for oy in 0..y_count {
                for ox in 0..x_count {
                    let off = (sy + oy) as usize * src_stride + (sx + ox) as usize * bpp;
                    pixel_offsets[n] = off;
                    alphas[n] = if bpc == 1 {
                        src_data[off + alpha_idx] as f64
                    } else {
                        u16::from_ne_bytes([
                            src_data[off + alpha_idx * 2],
                            src_data[off + alpha_idx * 2 + 1],
                        ]) as f64
                    };
                    n += 1;
                }
            }

            // Average alpha
            let alpha_sum: f64 = alphas[..n].iter().sum();
            let avg_alpha = alpha_sum / count as f64;

            if avg_alpha == 0.0 {
                // All transparent — zero all channels
                for c in 0..channels {
                    if bpc == 1 {
                        dst[dst_offset + c] = 0;
                    } else {
                        dst[dst_offset + c * 2] = 0;
                        dst[dst_offset + c * 2 + 1] = 0;
                    }
                }
            } else {
                // Alpha-weighted average for color channels
                for c in 0..alpha_idx {
                    let mut weighted_sum = 0.0f64;
                    for i in 0..n {
                        let val = if bpc == 1 {
                            src_data[pixel_offsets[i] + c] as f64
                        } else {
                            u16::from_ne_bytes([
                                src_data[pixel_offsets[i] + c * 2],
                                src_data[pixel_offsets[i] + c * 2 + 1],
                            ]) as f64
                        };
                        weighted_sum += alphas[i] * val;
                    }

                    let result = weighted_sum / (count as f64 * avg_alpha);

                    if bpc == 1 {
                        // vips truncates (C cast from double to int)
                        dst[dst_offset + c] = result as u8;
                    } else {
                        let bytes = (result as u16).to_ne_bytes();
                        dst[dst_offset + c * 2] = bytes[0];
                        dst[dst_offset + c * 2 + 1] = bytes[1];
                    }
                }

                // Alpha channel — simple average
                if bpc == 1 {
                    // vips truncates alpha too (C double→int cast)
                    dst[dst_offset + alpha_idx] = avg_alpha as u8;
                } else {
                    let bytes = (avg_alpha as u16).to_ne_bytes();
                    dst[dst_offset + alpha_idx * 2] = bytes[0];
                    dst[dst_offset + alpha_idx * 2 + 1] = bytes[1];
                }
            }
        }
    }

    Raster::new(dst_w, dst_h, fmt, dst)
}

/// Downscale a raster to arbitrary dimensions using simple bilinear-ish area averaging.
///
/// Maps each destination pixel to the corresponding rectangular region in the
/// source and averages all source samples within that region. This handles
/// non-power-of-two scale factors, unlike [`downscale_half`] which only
/// supports exact 2x reduction.
///
/// For pyramid generation, prefer `downscale_half` iteratively -- it is faster
/// and matches the level-halving semantics exactly.
///
/// # Example usage
///
/// - [test_resize_rounding](https://github.com/libviprs/libviprs-tests/blob/main/tests/ported_resample.rs)
///   exercises arbitrary-ratio downscaling and checks that output dimensions
///   are correctly rounded.
pub fn downscale_to(src: &Raster, dst_w: u32, dst_h: u32) -> Result<Raster, RasterError> {
    if dst_w == 0 || dst_h == 0 {
        return Err(RasterError::ZeroDimension {
            width: dst_w,
            height: dst_h,
        });
    }

    let fmt = src.format();
    let bpp = fmt.bytes_per_pixel();
    let bpc = fmt.bytes_per_channel();
    let channels = fmt.channels();
    let src_stride = src.stride();
    let src_data = src.data();
    let src_w = src.width();
    let src_h = src.height();

    let mut dst = vec![0u8; dst_w as usize * dst_h as usize * bpp];

    for dy in 0..dst_h {
        for dx in 0..dst_w {
            // Map destination pixel to source region
            let sx0 = (dx as u64 * src_w as u64 / dst_w as u64) as u32;
            let sy0 = (dy as u64 * src_h as u64 / dst_h as u64) as u32;
            let sx1 = (((dx + 1) as u64 * src_w as u64).div_ceil(dst_w as u64)) as u32;
            let sy1 = (((dy + 1) as u64 * src_h as u64).div_ceil(dst_h as u64)) as u32;
            let sx1 = sx1.min(src_w);
            let sy1 = sy1.min(src_h);

            let dst_offset = (dy as usize * dst_w as usize + dx as usize) * bpp;
            let count = (sx1 - sx0) * (sy1 - sy0);

            if count == 0 {
                continue;
            }

            for c in 0..channels {
                let mut sum: u64 = 0;
                for sy in sy0..sy1 {
                    for sx in sx0..sx1 {
                        let src_offset = sy as usize * src_stride + sx as usize * bpp + c * bpc;
                        if bpc == 1 {
                            sum += src_data[src_offset] as u64;
                        } else {
                            let val = u16::from_ne_bytes([
                                src_data[src_offset],
                                src_data[src_offset + 1],
                            ]);
                            sum += val as u64;
                        }
                    }
                }
                let avg = (sum + count as u64 / 2) / count as u64;
                if bpc == 1 {
                    dst[dst_offset + c] = avg as u8;
                } else {
                    let bytes = (avg as u16).to_ne_bytes();
                    dst[dst_offset + c * 2] = bytes[0];
                    dst[dst_offset + c * 2 + 1] = bytes[1];
                }
            }
        }
    }

    Raster::new(dst_w, dst_h, fmt, dst)
}

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

    fn solid_raster(w: u32, h: u32, pixel: &[u8], fmt: PixelFormat) -> Raster {
        let bpp = fmt.bytes_per_pixel();
        assert_eq!(pixel.len(), bpp);
        let mut data = Vec::with_capacity(w as usize * h as usize * bpp);
        for _ in 0..(w * h) {
            data.extend_from_slice(pixel);
        }
        Raster::new(w, h, fmt, data).unwrap()
    }

    /**
     * Tests that halving a raster with even dimensions produces exact half sizes.
     * Works by creating a 4x4 solid gray raster and verifying the output is 2x2
     * with all pixel values preserved.
     * Input: 4x4 Gray8 solid(200) → Output: 2x2 Gray8, all pixels == 200.
     */
    #[test]
    fn half_even_dimensions() {
        // 4x4 solid gray → 2x2 solid gray
        let src = solid_raster(4, 4, &[200], PixelFormat::Gray8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 2);
        assert_eq!(dst.height(), 2);
        assert!(dst.data().iter().all(|&b| b == 200));
    }

    /**
     * Tests that halving a raster with odd dimensions rounds up correctly.
     * Works by halving a 5x5 solid raster and verifying ceil(5/2)=3 for both axes.
     * Input: 5x5 Gray8 solid(100) → Output: 3x3 Gray8, all pixels == 100.
     */
    #[test]
    fn half_odd_dimensions() {
        // 5x5 → 3x3
        let src = solid_raster(5, 5, &[100], PixelFormat::Gray8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 3);
        assert_eq!(dst.height(), 3);
        assert!(dst.data().iter().all(|&b| b == 100));
    }

    /**
     * Tests that halving a 1x1 raster returns a 1x1 raster unchanged.
     * Works by verifying the minimum size boundary — cannot shrink below 1x1.
     * Input: 1x1 Gray8 [42] → Output: 1x1 Gray8 [42].
     */
    #[test]
    fn half_1x1_stays_1x1() {
        let src = solid_raster(1, 1, &[42], PixelFormat::Gray8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 1);
        assert_eq!(dst.height(), 1);
        assert_eq!(dst.data(), &[42]);
    }

    /**
     * Tests that downscale_half correctly averages pixel values.
     * Works by using a 2x2 image with known distinct values and checking
     * the single output pixel equals their arithmetic mean.
     * Input: 2x2 Gray8 [10,20,30,40] → Output: 1x1 Gray8 [25].
     */
    #[test]
    fn half_averaging_works() {
        // 2x2 with known pixel values → 1x1 with average
        let data = vec![10, 20, 30, 40]; // Four Gray8 pixels
        let src = Raster::new(2, 2, PixelFormat::Gray8, data).unwrap();
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 1);
        assert_eq!(dst.height(), 1);
        // Average of 10,20,30,40 = 25
        assert_eq!(dst.data()[0], 25);
    }

    /**
     * Tests that downscale_half works correctly with RGB8 (3-channel) images.
     * Works by halving a 2x2 solid red image and verifying the 1x1 result
     * preserves the exact RGB values.
     * Input: 2x2 Rgb8 solid(255,0,0) → Output: 1x1 Rgb8 [255,0,0].
     */
    #[test]
    fn half_rgb8() {
        // 2x2 solid red → 1x1 solid red
        let src = solid_raster(2, 2, &[255, 0, 0], PixelFormat::Rgb8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 1);
        assert_eq!(dst.height(), 1);
        assert_eq!(dst.data(), &[255, 0, 0]);
    }

    /**
     * Tests that downscale_half works correctly with RGBA8 (4-channel) images.
     * Works by halving a 4x4 solid RGBA image and verifying all 2x2 output
     * pixels preserve the exact channel values including alpha.
     * Input: 4x4 Rgba8 solid(100,150,200,255) → Output: 2x2 Rgba8, same values.
     */
    #[test]
    fn half_rgba8() {
        let src = solid_raster(4, 4, &[100, 150, 200, 255], PixelFormat::Rgba8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 2);
        assert_eq!(dst.height(), 2);
        // All pixels should be the same solid color
        for chunk in dst.data().chunks(4) {
            assert_eq!(chunk, &[100, 150, 200, 255]);
        }
    }

    /**
     * Tests that downscale_half preserves the PixelFormat of the source.
     * Works by halving images in Gray8, Rgb8, and Rgba8 and asserting the
     * output format matches the input format.
     * Input: 8x8 in each format → Output: 4x4 with same format.
     */
    #[test]
    fn half_preserves_format() {
        for fmt in [PixelFormat::Gray8, PixelFormat::Rgb8, PixelFormat::Rgba8] {
            let bpp = fmt.bytes_per_pixel();
            let pixel: Vec<u8> = (0..bpp).map(|i| (i * 50) as u8).collect();
            let src = solid_raster(8, 8, &pixel, fmt);
            let dst = downscale_half(&src).unwrap();
            assert_eq!(dst.format(), fmt);
        }
    }

    /**
     * Tests that repeatedly halving converges to a 1x1 image without error.
     * Works by iteratively halving a 256x256 solid raster until 1x1 and
     * verifying the final pixel value is preserved (no drift from rounding).
     * Input: 256x256 Gray8 solid(128) → Output: 1x1 Gray8 [128].
     */
    #[test]
    fn half_iterative_to_1x1() {
        let mut r = solid_raster(256, 256, &[128], PixelFormat::Gray8);
        while r.width() > 1 || r.height() > 1 {
            r = downscale_half(&r).unwrap();
        }
        assert_eq!(r.width(), 1);
        assert_eq!(r.height(), 1);
        assert_eq!(r.data()[0], 128);
    }

    /**
     * Tests that downscaling to the same dimensions is a no-op.
     * Works by calling downscale_to with identical width/height and
     * verifying pixel values are unchanged.
     * Input: 10x10 Gray8 solid(77) → Output: 10x10 Gray8, all pixels == 77.
     */
    #[test]
    fn downscale_to_same_size() {
        let src = solid_raster(10, 10, &[77], PixelFormat::Gray8);
        let dst = downscale_to(&src, 10, 10).unwrap();
        assert_eq!(dst.width(), 10);
        assert_eq!(dst.height(), 10);
        assert!(dst.data().iter().all(|&b| b == 77));
    }

    /**
     * Tests that downscale_to rejects zero target dimensions.
     * Works by passing width=0 or height=0 and asserting an Err is returned.
     * Input: downscale_to(10x10, 0, 5) → Output: Err.
     */
    #[test]
    fn downscale_to_zero_rejected() {
        let src = solid_raster(10, 10, &[1], PixelFormat::Gray8);
        assert!(downscale_to(&src, 0, 5).is_err());
        assert!(downscale_to(&src, 5, 0).is_err());
    }

    /**
     * Tests that downscaling a solid-color image preserves the color exactly.
     * Works by area-averaging a uniform RGB image to an arbitrary smaller size
     * and verifying every output pixel matches the original color.
     * Input: 100x100 Rgb8 solid(200,100,50) → Output: 33x25 Rgb8, same color.
     */
    #[test]
    fn downscale_to_solid_preserved() {
        let src = solid_raster(100, 100, &[200, 100, 50], PixelFormat::Rgb8);
        let dst = downscale_to(&src, 33, 25).unwrap();
        assert_eq!(dst.width(), 33);
        assert_eq!(dst.height(), 25);
        for chunk in dst.data().chunks(3) {
            assert_eq!(chunk, &[200, 100, 50]);
        }
    }

    // -- Alpha-weighted averaging tests --

    /// Alpha-weighted: solid RGBA with full alpha preserves color exactly.
    #[test]
    fn half_rgba_solid_opaque() {
        let src = solid_raster(4, 4, &[100, 150, 200, 255], PixelFormat::Rgba8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 2);
        assert_eq!(dst.height(), 2);
        for chunk in dst.data().chunks(4) {
            assert_eq!(chunk, &[100, 150, 200, 255]);
        }
    }

    /// Alpha-weighted: fully transparent pixels produce all-zero output.
    #[test]
    fn half_rgba_fully_transparent() {
        let src = solid_raster(2, 2, &[100, 200, 50, 0], PixelFormat::Rgba8);
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.data(), &[0, 0, 0, 0]);
    }

    /// Alpha-weighted: when alpha varies, color channels are weighted by alpha.
    /// Two opaque red pixels and two transparent green pixels should produce
    /// pure red (not a red/green average), since the green pixels have zero
    /// weight.
    #[test]
    fn half_rgba_alpha_weights_color() {
        // Top-left: opaque red, top-right: opaque red
        // Bottom-left: transparent green, bottom-right: transparent green
        let data = vec![
            255, 0, 0, 255, // red, alpha=255
            255, 0, 0, 255, // red, alpha=255
            0, 255, 0, 0, // green, alpha=0
            0, 255, 0, 0, // green, alpha=0
        ];
        let src = Raster::new(2, 2, PixelFormat::Rgba8, data).unwrap();
        let dst = downscale_half(&src).unwrap();

        // Alpha average = (255+255+0+0)/4 = 127 (truncated from 127.5)
        // R = (255*255 + 255*255 + 0*0 + 0*0) / (4 * 127.5) = 130050/510 = 255
        // G = (255*0 + 255*0 + 0*255 + 0*255) / (4 * 127.5) = 0
        // B = 0
        assert_eq!(dst.data()[0], 255, "R should be 255 (alpha-weighted)");
        assert_eq!(
            dst.data()[1],
            0,
            "G should be 0 (transparent pixels ignored)"
        );
        assert_eq!(dst.data()[2], 0, "B should be 0");
        assert_eq!(dst.data()[3], 127, "A should be 127 (truncated from 127.5)");
    }

    /// Alpha-weighted: partial alpha correctly weights the contribution.
    #[test]
    fn half_rgba_partial_alpha() {
        // One pixel at alpha=200 with value 100, one pixel at alpha=50 with value 200
        // Others transparent
        let data = vec![
            100, 0, 0, 200, // pixel 0: R=100, A=200
            200, 0, 0, 50, // pixel 1: R=200, A=50
            0, 0, 0, 0, // pixel 2: transparent
            0, 0, 0, 0, // pixel 3: transparent
        ];
        let src = Raster::new(2, 2, PixelFormat::Rgba8, data).unwrap();
        let dst = downscale_half(&src).unwrap();

        // Alpha = (200+50+0+0)/4 = 62.5 → 62 (truncated)
        // R = (200*100 + 50*200 + 0 + 0) / (4 * 62.5) = 30000/250 = 120
        let avg_alpha = (200.0 + 50.0) / 4.0;
        let expected_r = (200.0 * 100.0 + 50.0 * 200.0) / (4.0 * avg_alpha);
        assert_eq!(dst.data()[0], expected_r as u8, "R alpha-weighted");
        assert_eq!(dst.data()[3], avg_alpha as u8, "A averaged");
    }

    /// Alpha-weighted averaging with odd dimensions handles edge pixels.
    #[test]
    fn half_rgba_odd_dimensions() {
        // 3x1 RGBA: only 2 pixels contribute to first output, 1 to second
        let data = vec![
            255, 0, 0, 255, // opaque red
            0, 255, 0, 255, // opaque green
            0, 0, 255, 128, // semi-transparent blue
        ];
        let src = Raster::new(3, 1, PixelFormat::Rgba8, data).unwrap();
        let dst = downscale_half(&src).unwrap();
        assert_eq!(dst.width(), 2);
        assert_eq!(dst.height(), 1);
        // First pixel: average of red+green (both alpha=255) → (127,127,0,255)
        // (with alpha-weighted: same as uniform since alpha is equal)
        assert_eq!(dst.data()[0], 127); // R: (255*255+255*0)/(2*255) = 127
        assert_eq!(dst.data()[1], 127); // G: (255*0+255*255)/(2*255) = 127 (truncated)
        assert_eq!(dst.data()[3], 255); // A: (255+255)/2 = 255
    }
}