1
//! Pure-functional image resampling: the reference scaler.
2
//!
3
//! ONE piece of sampling math, shared by the places that must agree on how an
4
//! image is resized:
5
//!
6
//! - the CPU rasterizer's on-screen image blit (display),
7
//! - the capture pipeline producing a consumer's requested size — a local 100×200 preview AND a
8
//!   remote 500×200 stream cut from ONE captured frame, so the camera is read once and sampled per
9
//!   consumer,
10
//! - anywhere a `RawImage` must be resized without pulling in the `image` crate.
11
//!
12
//! THE CONTRACT: every output pixel is a PURE function of the source and its
13
//! own destination coordinates ([`sample`]). A caller may therefore compute
14
//! any subset of the output on any thread — the whole-image [`resample_rgba`]
15
//! is just the serial walk, and a future threaded or platform-accelerated
16
//! backend (Accelerate / vImage on macOS, MPS on the GPU) plugs in behind the
17
//! same signature. This module is the portable fallback and the golden
18
//! reference the tests pin; no threading lives here on purpose.
19
//!
20
//! QUALITY: nearest-neighbour aliases badly on a downscale (the capture
21
//! preview's shimmer). [`sample`] area-averages a bounded grid of taps across
22
//! each destination pixel's source footprint on a downscale, and bilinearly
23
//! interpolates on an upscale — so a huge source feeding a tiny preview only
24
//! reads the pixels its taps land on, never the whole image.
25

            
26
use alloc::vec::Vec;
27

            
28
use azul_core::{
29
    resources::RawImageFormat,
30
    video::{ConsumerFrame, FrameConsumer, VideoFrame},
31
};
32

            
33
/// The most taps taken along ONE axis of a destination pixel's footprint.
34
/// Caps area-averaging cost at `MAX_TAPS²` reads per output pixel regardless
35
/// of how extreme the downscale is (a 40× downscale still costs 16 taps, not
36
/// 1600) — a bounded box filter, not a true area integral, which is the right
37
/// trade for a live preview.
38
const MAX_TAPS: u32 = 4;
39

            
40
/// A straight-RGBA view over tightly-packed image bytes, addressed per pixel
41
/// format. Borrows the source; holds no allocation of its own.
42
#[derive(Debug, Clone, Copy)]
43
pub struct SrcImage<'a> {
44
    /// Tightly-packed pixel bytes (`width * height * bytes_per_pixel(format)`).
45
    pub bytes: &'a [u8],
46
    /// The byte layout of `bytes`.
47
    pub format: RawImageFormat,
48
    /// Source width in pixels.
49
    pub width: u32,
50
    /// Source height in pixels.
51
    pub height: u32,
52
}
53

            
54
/// Bytes per pixel for the formats [`SrcImage::pixel`] can read. `None` for a
55
/// format this scaler does not sample (16-bit / float / two-channel) — the
56
/// caller renders those some other way.
57
#[must_use]
58
499318
pub const fn bytes_per_pixel(format: RawImageFormat) -> Option<usize> {
59
499318
    match format {
60
6153
        RawImageFormat::R8 => Some(1),
61
12305
        RawImageFormat::RGB8 | RawImageFormat::BGR8 => Some(3),
62
480859
        RawImageFormat::RGBA8 | RawImageFormat::BGRA8 => Some(4),
63
1
        _ => None,
64
    }
65
499318
}
66

            
67
impl SrcImage<'_> {
68
    /// Whether this scaler can sample the view's format and its `bytes` are
69
    /// long enough for `width × height`.
70
    #[must_use]
71
154
    pub fn is_sampleable(&self) -> bool {
72
154
        bytes_per_pixel(self.format).is_some_and(|bpp| {
73
154
            (self.width as usize)
74
154
                .checked_mul(self.height as usize)
75
154
                .and_then(|px| px.checked_mul(bpp))
76
154
                .is_some_and(|need| self.bytes.len() >= need)
77
154
        })
78
154
    }
79

            
80
    /// One source pixel as straight RGBA, clamped to the image edge (so a tap
81
    /// off the border repeats the border, never reads out of bounds). Returns
82
    /// opaque black for an unsupported format or a truncated buffer — callers
83
    /// gate on [`Self::is_sampleable`] first.
84
    #[must_use]
85
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)] // clamped to [0, dim)
86
495139
    pub fn pixel(&self, x: i32, y: i32) -> [u8; 4] {
87
495139
        if self.width == 0 || self.height == 0 {
88
            return [0, 0, 0, 255];
89
495139
        }
90
495139
        let Some(bpp) = bytes_per_pixel(self.format) else {
91
1
            return [0, 0, 0, 255];
92
        };
93
495138
        let x = x.clamp(0, self.width as i32 - 1) as usize;
94
495138
        let y = y.clamp(0, self.height as i32 - 1) as usize;
95
495138
        let i = (y * self.width as usize + x) * bpp;
96
495138
        if i + bpp > self.bytes.len() {
97
            return [0, 0, 0, 255];
98
495138
        }
99
495138
        let b = self.bytes;
100
495138
        match self.format {
101
470750
            RawImageFormat::RGBA8 => [b[i], b[i + 1], b[i + 2], b[i + 3]],
102
6097
            RawImageFormat::BGRA8 => [b[i + 2], b[i + 1], b[i], b[i + 3]],
103
6097
            RawImageFormat::RGB8 => [b[i], b[i + 1], b[i + 2], 255],
104
6097
            RawImageFormat::BGR8 => [b[i + 2], b[i + 1], b[i], 255],
105
            // R8: replicated to RGB with an OPAQUE alpha (a coverage/luma
106
            // plane is not a transparency plane).
107
6097
            RawImageFormat::R8 => [b[i], b[i], b[i], 255],
108
            _ => [0, 0, 0, 255],
109
        }
110
495139
    }
111
}
112

            
113
/// The straight-RGBA value of destination pixel `(dx, dy)` when `src` is
114
/// resampled to `dst_w × dst_h`.
115
///
116
/// PURE — depends only on its arguments, so any subset of the destination can
117
/// be evaluated on any thread. Area-averages a bounded tap grid on a
118
/// downscale (kills aliasing), bilinear on an upscale (no blocky enlargement),
119
/// nearest at 1:1.
120
#[must_use]
121
#[allow(
122
    clippy::cast_precision_loss,
123
    clippy::cast_possible_truncation,
124
    clippy::cast_sign_loss
125
)]
126
#[allow(clippy::many_single_char_names)] // r/g/b/a channel accumulators + tap coords
127
37566
pub fn sample(src: &SrcImage<'_>, dst_w: u32, dst_h: u32, dx: u32, dy: u32) -> [u8; 4] {
128
37566
    let scale_x = src.width as f32 / dst_w.max(1) as f32;
129
37566
    let scale_y = src.height as f32 / dst_h.max(1) as f32;
130
    // Source-space centre of this destination pixel.
131
37566
    let cx = (dx as f32 + 0.5) * scale_x;
132
37566
    let cy = (dy as f32 + 0.5) * scale_y;
133

            
134
37566
    if scale_x <= 1.0 && scale_y <= 1.0 {
135
7496
        return bilinear(src, cx - 0.5, cy - 0.5);
136
30070
    }
137

            
138
    // Downscale on at least one axis: average a grid of taps spread across the
139
    // footprint [cx ± scale_x/2] × [cy ± scale_y/2]. An axis that is actually
140
    // an UPSCALE (scale < 1) takes a single centred tap.
141
30070
    let nx = (scale_x.ceil() as u32).clamp(1, MAX_TAPS);
142
30070
    let ny = (scale_y.ceil() as u32).clamp(1, MAX_TAPS);
143
30070
    let (mut r, mut g, mut b, mut a) = (0u32, 0u32, 0u32, 0u32);
144
117847
    for ty in 0..ny {
145
        // Tap centres at the (k + 0.5)/n fractions of the footprint.
146
117847
        let fy = cy + ((ty as f32 + 0.5) / ny as f32 - 0.5) * scale_y;
147
465145
        for tx in 0..nx {
148
465145
            let fx = cx + ((tx as f32 + 0.5) / nx as f32 - 0.5) * scale_x;
149
465145
            let p = src.pixel(fx.floor() as i32, fy.floor() as i32);
150
465145
            r += u32::from(p[0]);
151
465145
            g += u32::from(p[1]);
152
465145
            b += u32::from(p[2]);
153
465145
            a += u32::from(p[3]);
154
465145
        }
155
    }
156
30070
    let n = nx * ny;
157
30070
    [
158
30070
        ((r + n / 2) / n) as u8,
159
30070
        ((g + n / 2) / n) as u8,
160
30070
        ((b + n / 2) / n) as u8,
161
30070
        ((a + n / 2) / n) as u8,
162
30070
    ]
163
37566
}
164

            
165
/// Bilinear sample at source coordinate `(fx, fy)` in pixel units (a pixel's
166
/// centre is at its integer index). Used on an upscale.
167
#[allow(
168
    clippy::cast_possible_truncation,
169
    clippy::cast_sign_loss,
170
    clippy::cast_precision_loss
171
)]
172
#[allow(clippy::many_single_char_names)] // p00/p10/.. corners + tx/ty weights
173
7496
fn bilinear(src: &SrcImage<'_>, fx: f32, fy: f32) -> [u8; 4] {
174
7496
    let x0 = fx.floor();
175
7496
    let y0 = fy.floor();
176
7496
    let tx = fx - x0;
177
7496
    let ty = fy - y0;
178
7496
    let (x0, y0) = (x0 as i32, y0 as i32);
179
7496
    let p00 = src.pixel(x0, y0);
180
7496
    let p10 = src.pixel(x0 + 1, y0);
181
7496
    let p01 = src.pixel(x0, y0 + 1);
182
7496
    let p11 = src.pixel(x0 + 1, y0 + 1);
183
7496
    let mut out = [0u8; 4];
184
37480
    for c in 0..4 {
185
29984
        let top = f32::from(p00[c]) * (1.0 - tx) + f32::from(p10[c]) * tx;
186
29984
        let bot = f32::from(p01[c]) * (1.0 - tx) + f32::from(p11[c]) * tx;
187
29984
        out[c] = (top * (1.0 - ty) + bot * ty).round().clamp(0.0, 255.0) as u8;
188
29984
    }
189
7496
    out
190
7496
}
191

            
192
/// Resample `src` to a tightly-packed `dst_w × dst_h` RGBA8 buffer.
193
///
194
/// The serial whole-image walk over [`sample`] — the frame scaler the capture
195
/// pipeline uses to cut each consumer's size from one captured frame, and the
196
/// convenience path for a one-off `RawImage` resize. Returns an empty `Vec`
197
/// for a zero destination or an unsampleable source.
198
#[must_use]
199
12
pub fn resample_rgba(src: &SrcImage<'_>, dst_w: u32, dst_h: u32) -> Vec<u8> {
200
12
    if dst_w == 0 || dst_h == 0 || !src.is_sampleable() {
201
2
        return Vec::new();
202
10
    }
203
10
    let mut out = alloc::vec![0u8; dst_w as usize * dst_h as usize * 4];
204
225
    for dy in 0..dst_h {
205
29759
        for dx in 0..dst_w {
206
29759
            let px = sample(src, dst_w, dst_h, dx, dy);
207
29759
            let i = (dy as usize * dst_w as usize + dx as usize) * 4;
208
29759
            out[i..i + 4].copy_from_slice(&px);
209
29759
        }
210
    }
211
10
    out
212
12
}
213

            
214
/// A whole-frame scaler: `(source, dst_w, dst_h) -> tightly-packed RGBA8`
215
/// (`dst_w * dst_h * 4` bytes, or empty on failure). [`resample_rgba`] is
216
/// the portable one; the dll may register a platform-accelerated one
217
/// (Accelerate/vImage on macOS) with the same signature — see
218
/// `widgets::capture_common::register_frame_resampler`. Every implementation
219
/// must be a pure function of its inputs so the fan-out can run per consumer
220
/// on any thread.
221
pub type ResampleFn = fn(&SrcImage<'_>, u32, u32) -> Vec<u8>;
222

            
223
/// The smallest capture size that covers every requested size: the per-axis
224
/// maximum. Zero-sized entries are ignored; `None` when nothing is left.
225
///
226
/// "Client Bob wants 500x200, the local preview is 100x200" -> capture at
227
/// 500x200: every consumer is then a downscale of the captured frame (never
228
/// an upscale, which would only invent pixels) and the device is never asked
229
/// for more than the largest consumer can use.
230
#[must_use]
231
33
pub fn covering_size<I: IntoIterator<Item = (u32, u32)>>(sizes: I) -> Option<(u32, u32)> {
232
33
    sizes
233
33
        .into_iter()
234
44
        .filter(|&(w, h)| w > 0 && h > 0)
235
33
        .reduce(|(aw, ah), (w, h)| (aw.max(w), ah.max(h)))
236
33
}
237

            
238
/// Cut `src` to `width x height` RGBA8 with `resample`. A same-size RGBA8
239
/// source is copied, not resampled (the common "the camera already captures
240
/// at the largest consumer's size" case costs one memcpy).
241
#[must_use]
242
8
pub fn cut(src: &SrcImage<'_>, width: u32, height: u32, resample: ResampleFn) -> Vec<u8> {
243
8
    if width == 0 || height == 0 || !src.is_sampleable() {
244
2
        return Vec::new();
245
6
    }
246
6
    if src.width == width && src.height == height && src.format == RawImageFormat::RGBA8 {
247
1
        return src.bytes.to_vec();
248
5
    }
249
5
    resample(src, width, height)
250
8
}
251

            
252
/// Cut ONE captured frame to every consumer's requested size.
253
///
254
/// Each element is independent of the others (a pure function of `src` and
255
/// its own consumer), so this serial loop can become a parallel map without
256
/// touching the callers. Invalid consumers (zero size, the reserved preview
257
/// id) and failed cuts are skipped, so the result may be shorter than the
258
/// input; match results to requests by `ConsumerFrame::consumer.id`.
259
#[must_use]
260
8
pub fn fan_out(
261
8
    src: &SrcImage<'_>,
262
8
    consumers: &[FrameConsumer],
263
8
    resample: ResampleFn,
264
8
) -> Vec<ConsumerFrame> {
265
8
    consumers
266
8
        .iter()
267
8
        .copied()
268
8
        .filter(FrameConsumer::is_valid)
269
8
        .filter_map(|c| {
270
3
            let rgba = cut(src, c.width, c.height, resample);
271
3
            (!rgba.is_empty())
272
3
                .then(|| ConsumerFrame::new(c, VideoFrame::new(c.width, c.height, rgba.into())))
273
3
        })
274
8
        .collect()
275
8
}
276

            
277
#[cfg(test)]
278
mod tests {
279
    use super::*;
280

            
281
11
    fn rgba(bytes: &[u8], w: u32, h: u32) -> SrcImage<'_> {
282
11
        SrcImage {
283
11
            bytes,
284
11
            format: RawImageFormat::RGBA8,
285
11
            width: w,
286
11
            height: h,
287
11
        }
288
11
    }
289

            
290
    // --- consumers ---------------------------------------------------------
291

            
292
    #[test]
293
1
    fn the_covering_size_is_the_per_axis_max_ignoring_zero_entries() {
294
        // Bob 500x200 + a 100x200 preview -> 500x200 captured, once.
295
1
        assert_eq!(covering_size([(500, 200), (100, 200)]), Some((500, 200)));
296
        // A tall and a wide consumer cover each other's axis.
297
1
        assert_eq!(covering_size([(100, 900), (800, 50)]), Some((800, 900)));
298
1
        assert_eq!(
299
1
            covering_size([(0, 0), (0, 480)]),
300
            None,
301
            "zero sizes are not requests"
302
        );
303
1
        assert_eq!(covering_size([]), None);
304
1
    }
305

            
306
    #[test]
307
1
    fn fan_out_cuts_one_frame_to_every_valid_consumer() {
308
        // a 4x2 solid-green frame
309
1
        let bytes = [0u8, 200, 0, 255].repeat(8);
310
1
        let src = rgba(&bytes, 4, 2);
311
1
        let consumers = [
312
1
            FrameConsumer::new(7, 2, 1),  // Bob, a downscale
313
1
            FrameConsumer::new(8, 4, 2),  // the recorder at the captured size -> copy
314
1
            FrameConsumer::new(0, 4, 2),  // the preview id is NOT a fan-out consumer
315
1
            FrameConsumer::new(9, 0, 10), // a zero size is skipped
316
1
        ];
317
1
        let cuts = fan_out(&src, &consumers, resample_rgba);
318
1
        let ids: Vec<u32> = cuts.iter().map(|c| c.consumer.id).collect();
319
1
        assert_eq!(
320
            ids,
321
1
            vec![7, 8],
322
            "only the valid consumers get a frame: {ids:?}"
323
        );
324
1
        assert_eq!(cuts[0].frame.width, 2);
325
1
        assert_eq!(cuts[0].frame.height, 1);
326
1
        assert_eq!(
327
1
            cuts[0].frame.bytes.as_ref(),
328
            &[0, 200, 0, 255, 0, 200, 0, 255]
329
        );
330
1
        assert_eq!(
331
1
            cuts[1].frame.bytes.as_ref(),
332
1
            &bytes[..],
333
            "a same-size RGBA8 consumer is a copy of the captured frame"
334
        );
335
1
    }
336

            
337
    #[test]
338
1
    fn a_cut_never_upscales_past_what_was_asked_and_rejects_bad_input() {
339
1
        let bytes = [9u8; 4];
340
1
        let src = rgba(&bytes, 1, 1);
341
1
        assert_eq!(cut(&src, 3, 2, resample_rgba).len(), 3 * 2 * 4);
342
1
        assert!(cut(&src, 0, 2, resample_rgba).is_empty());
343
1
        let truncated = SrcImage {
344
1
            bytes: &bytes[..2],
345
1
            ..src
346
1
        };
347
1
        assert!(
348
1
            cut(&truncated, 1, 1, resample_rgba).is_empty(),
349
            "an unsampleable source cuts nothing"
350
        );
351
1
    }
352

            
353
    #[test]
354
1
    fn a_pixel_reads_each_format_as_straight_rgba() {
355
        // one pixel, four formats
356
1
        assert_eq!(rgba(&[10, 20, 30, 40], 1, 1).pixel(0, 0), [10, 20, 30, 40]);
357
1
        assert_eq!(
358
1
            SrcImage {
359
1
                bytes: &[10, 20, 30, 40],
360
1
                format: RawImageFormat::BGRA8,
361
1
                width: 1,
362
1
                height: 1
363
1
            }
364
1
            .pixel(0, 0),
365
            [30, 20, 10, 40]
366
        );
367
1
        assert_eq!(
368
1
            SrcImage {
369
1
                bytes: &[10, 20, 30],
370
1
                format: RawImageFormat::RGB8,
371
1
                width: 1,
372
1
                height: 1
373
1
            }
374
1
            .pixel(0, 0),
375
            [10, 20, 30, 255]
376
        );
377
1
        assert_eq!(
378
1
            SrcImage {
379
1
                bytes: &[10, 20, 30],
380
1
                format: RawImageFormat::BGR8,
381
1
                width: 1,
382
1
                height: 1
383
1
            }
384
1
            .pixel(0, 0),
385
            [30, 20, 10, 255]
386
        );
387
1
        assert_eq!(
388
1
            SrcImage {
389
1
                bytes: &[77],
390
1
                format: RawImageFormat::R8,
391
1
                width: 1,
392
1
                height: 1
393
1
            }
394
1
            .pixel(0, 0),
395
            [77, 77, 77, 255]
396
        );
397
1
    }
398

            
399
    #[test]
400
1
    fn a_tap_off_the_edge_repeats_the_border_and_never_reads_out_of_bounds() {
401
1
        let img = rgba(&[1, 2, 3, 4], 1, 1);
402
4
        for (x, y) in [(-5, -5), (99, 0), (0, 99), (i32::MIN, i32::MAX)] {
403
4
            assert_eq!(img.pixel(x, y), [1, 2, 3, 4]);
404
        }
405
        // Unsupported format / short buffer → opaque black, no panic.
406
1
        assert_eq!(
407
1
            SrcImage {
408
1
                bytes: &[],
409
1
                format: RawImageFormat::RGBAF32,
410
1
                width: 1,
411
1
                height: 1
412
1
            }
413
1
            .pixel(0, 0),
414
            [0, 0, 0, 255]
415
        );
416
1
    }
417

            
418
    #[test]
419
1
    fn a_2x2_downscaled_to_1x1_is_the_area_average() {
420
        // corners 0, 40, 80, 120 in every channel
421
1
        let bytes = [
422
1
            0, 0, 0, 0, 40, 40, 40, 40, 80, 80, 80, 80, 120, 120, 120, 120,
423
1
        ];
424
1
        let out = sample(&rgba(&bytes, 2, 2), 1, 1, 0, 0);
425
        // (0+40+80+120)/4 = 60, exact
426
1
        assert_eq!(
427
            out,
428
            [60, 60, 60, 60],
429
            "a 2x downscale must average, not pick one (nearest)"
430
        );
431
1
    }
432

            
433
    #[test]
434
1
    fn a_solid_source_survives_any_scale_unchanged() {
435
        // A 3x3 of a single colour resamples to that colour at any size, both
436
        // directions — no averaging drift, no edge darkening.
437
1
        let px = [90u8, 110, 130, 200];
438
1
        let mut bytes = Vec::new();
439
10
        for _ in 0..9 {
440
9
            bytes.extend_from_slice(&px);
441
9
        }
442
1
        let src = rgba(&bytes, 3, 3);
443
4
        for (w, h) in [(1, 1), (2, 2), (7, 5), (30, 30)] {
444
4
            let out = resample_rgba(&src, w, h);
445
4
            assert_eq!(out.len(), w as usize * h as usize * 4);
446
940
            for chunk in out.chunks_exact(4) {
447
940
                assert_eq!(chunk, px, "solid colour changed at {w}x{h}");
448
            }
449
        }
450
1
    }
451

            
452
    #[test]
453
1
    fn an_upscale_is_bilinear_not_blocky() {
454
        // A 2x1 gradient 0 -> 100 upscaled to 5x1: the middle samples must lie
455
        // strictly between the ends (nearest would jump 0 -> 100 with no
456
        // in-between value).
457
1
        let bytes = [0, 0, 0, 255, 100, 100, 100, 255];
458
1
        let src = rgba(&bytes, 2, 1);
459
1
        let out = resample_rgba(&src, 5, 1);
460
5
        let reds: Vec<u8> = out.chunks_exact(4).map(|c| c[0]).collect();
461
1
        assert!(
462
1
            reds[0] < reds[2] && reds[2] < reds[4],
463
            "not monotone: {reds:?}"
464
        );
465
1
        assert!(
466
1
            (1..100).contains(&reds[2]),
467
            "the middle must interpolate: {reds:?}"
468
        );
469
1
    }
470

            
471
    #[test]
472
1
    fn an_extreme_downscale_is_bounded_and_does_not_panic() {
473
        // 400x400 -> 1x1: a true area average would read 160 000 pixels; the
474
        // bounded grid reads at most MAX_TAPS^2 = 16.
475
1
        let bytes = alloc::vec![128u8; 400 * 400 * 4];
476
1
        let out = sample(&rgba(&bytes, 400, 400), 1, 1, 0, 0);
477
1
        assert_eq!(out, [128, 128, 128, 128]);
478
1
    }
479

            
480
    #[test]
481
1
    fn resample_rejects_a_zero_destination_or_unsampleable_source() {
482
1
        let bytes = [1u8, 2, 3, 4];
483
1
        assert!(resample_rgba(&rgba(&bytes, 1, 1), 0, 4).is_empty());
484
        // buffer too short for the claimed dimensions
485
1
        assert!(!rgba(&[1, 2, 3], 2, 2).is_sampleable());
486
1
        assert!(resample_rgba(&rgba(&[1, 2, 3], 2, 2), 4, 4).is_empty());
487
1
    }
488
}