capsule_core/media/resize.rs
1//! Capsule-owned downscale for the derivative tiers.
2//!
3//! `rawshift-image` has no resize — it offers crop, flips, rotations, blur and lens correction,
4//! and nothing that changes the sample grid — so tier sizing is Capsule's, not the codec's.
5//!
6//! # Why integer area-averaging, specifically
7//!
8//! A derivative's bytes are content-addressed by a **signed** `DerivativeManifest`, so two runs
9//! over the same source must produce the same bytes. That rules out floating-point accumulation
10//! whose order or width could differ between builds and targets, and it rules out any resampler
11//! with platform-tuned SIMD paths that are not required to be bit-identical. What is left is a
12//! box filter accumulated in integers and divided by an exact sample count: deterministic on
13//! every target, and the right filter for a large downscale anyway (a box average over the full
14//! source rect is alias-free, where a bilinear tap would ignore most of the source pixels).
15//!
16//! Every product here is computed in `u64`, never in `usize`, because two of the CI-gated
17//! targets (`armv7-linux-androideabi`, `i686-linux-android`) are 32-bit and both the
18//! destination-to-source boundary and the channel accumulator reach past `u32` for shapes this
19//! function accepts.
20//!
21//! Determinism here is **necessary, not sufficient**, and the distinction matters: the bytes a
22//! manifest actually signs come out of the encoder (gamut's AV1 or libjxl), and a version bump can change
23//! them for the same input. That is fine — each generation signs the bytes it produced, and
24//! manifests of a role chain in order — but it means "the resample is deterministic" buys
25//! reproducibility of *this* step, not a stable content address across toolchains.
26//!
27//! Upscaling is not a thing this performs: a tier only ever caps a long edge, and a source
28//! already inside the cap takes the `format = "original"` sentinel path instead
29//! ([`DerivativeTier`](super::DerivativeTier)).
30
31use crate::lqip::RgbaImage;
32
33/// The dimensions a `width` x `height` frame takes when its long edge is capped at
34/// `max_long_edge`, preserving aspect ratio.
35///
36/// Returns the input unchanged when it already fits, so a caller can compare and skip — and
37/// unchanged for an empty frame, which is the one case where "never zero" cannot hold: there is
38/// no non-degenerate size for a frame with no pixels, and inventing one would have
39/// [`downscale_rgba8`] read a buffer that has nothing in it.
40pub fn capped_dimensions(width: u32, height: u32, max_long_edge: u32) -> (u32, u32) {
41 if width == 0 || height == 0 {
42 return (width, height);
43 }
44 let cap = max_long_edge.max(1);
45 let long_edge = width.max(height);
46 if long_edge <= cap {
47 return (width, height);
48 }
49 // Rounded rather than truncated so a 3:2 frame keeps its ratio as closely as an integer
50 // grid allows; `.max(1)` because a very lopsided frame (e.g. 8000x3) would otherwise round
51 // its short edge to zero and produce an empty buffer.
52 let scale = |edge: u32| -> u32 {
53 let numerator = u64::from(edge) * u64::from(cap);
54 let denominator = u64::from(long_edge);
55 (((numerator + denominator / 2) / denominator) as u32).max(1)
56 };
57 (scale(width), scale(height))
58}
59
60/// Downscale packed RGBA8 so its long edge is at most `max_long_edge`.
61///
62/// A frame already within the cap — or an empty one — is returned unchanged (cloned), which is
63/// what makes this safe to call unconditionally. Deterministic: identical input yields
64/// byte-identical output on every target.
65pub fn downscale_rgba8(source: &RgbaImage, max_long_edge: u32) -> RgbaImage {
66 let (dst_w, dst_h) = capped_dimensions(source.width, source.height, max_long_edge);
67 if (dst_w, dst_h) == (source.width, source.height) {
68 return source.clone();
69 }
70
71 let (src_w, src_h) = (source.width as usize, source.height as usize);
72 // `u64`, not `usize`: on a 32-bit target `w * h * 4` overflows above ~1 Gpx, and the whole
73 // point of this branch is to be reached rather than to panic on its own arithmetic.
74 if source.rgba.len() as u64 != u64::from(source.width) * u64::from(source.height) * 4 {
75 // Defensive: this is a `pub` entry point and the very next thing it does is index the
76 // buffer by those dimensions. Every in-tree caller passes a `DecodedImage`, whose
77 // invariant this is, so a mismatch is a bug in a *new* caller — reported and returned
78 // unchanged rather than turned into a panic inside an import.
79 tracing::error!(
80 width = source.width,
81 height = source.height,
82 len = source.rgba.len(),
83 "media: downscale refused a buffer that does not match its dimensions"
84 );
85 return source.clone();
86 }
87 let (dw, dh) = (dst_w as usize, dst_h as usize);
88 let mut out = Vec::with_capacity(dw * dh * 4);
89
90 // Boundary products and the channel accumulator are `u64`, not `usize`/`u32`, and both
91 // widths are load-bearing rather than defensive habit:
92 //
93 // - `(y + 1) * src_h` reaches `dst_edge * src_edge`. For a 1 x 256M frame reduced to a
94 // 256 px long edge that is 6.5e10, which overflows a 32-bit `usize` — and two of the
95 // CI-gated targets (`armv7-linux-androideabi`, `i686-linux-android`) are 32-bit.
96 // - the per-channel sum reaches `count * 255`, and `count` is the whole frame when this is
97 // called with a cap of 1 (a `pub` entry point, so that is reachable), i.e. 6.5e10 again —
98 // past `u32::MAX`.
99 //
100 // Neither is hypothetical-only: a debug build panics on the overflow and a release build
101 // wraps into wrong pixels or an out-of-bounds index.
102 for y in 0..dh {
103 // The source rows this destination row averages. Floor boundaries, so the destination
104 // grid is an exact partition of the source grid — every source pixel contributes to
105 // exactly one output pixel. Widened to at least one row because a lopsided cap can put
106 // two destination rows inside one source row, and an empty rect would divide by zero.
107 let y0 = (y as u64 * src_h as u64 / dh as u64) as usize;
108 let y1 = (((y as u64 + 1) * src_h as u64 / dh as u64) as usize)
109 .max(y0 + 1)
110 .min(src_h);
111 for x in 0..dw {
112 let x0 = (x as u64 * src_w as u64 / dw as u64) as usize;
113 let x1 = (((x as u64 + 1) * src_w as u64 / dw as u64) as usize)
114 .max(x0 + 1)
115 .min(src_w);
116
117 let mut acc = [0u64; 4];
118 let count = ((y1 - y0) * (x1 - x0)) as u64;
119 for sy in y0..y1 {
120 let row = sy * src_w * 4;
121 for sx in x0..x1 {
122 let i = row + sx * 4;
123 acc[0] += u64::from(source.rgba[i]);
124 acc[1] += u64::from(source.rgba[i + 1]);
125 acc[2] += u64::from(source.rgba[i + 2]);
126 acc[3] += u64::from(source.rgba[i + 3]);
127 }
128 }
129 // Round-half-up on the mean, so a uniform region reproduces its own value exactly
130 // rather than drifting down by up to one level per reduction.
131 for channel in acc {
132 out.push(((channel + count / 2) / count) as u8);
133 }
134 }
135 }
136
137 RgbaImage {
138 width: dst_w,
139 height: dst_h,
140 rgba: out,
141 }
142}