forge
Explore
Log in

Don't you dare go Hollow

I420 scaler and fit geometry

Browse files at this commit

dd5430882a4249e3473fb43b5ec78db663b29fdfAhmet Kaan GümüşParent: 3395f94
  • feat
    • I420 scaler and fit geometry
Show full message
✨ feat(engine): I420 scaler and fit geometry

Bilinear 16.16 rescale, four fit policies handing back chroma-grid-aligned
placement and crop rects, and a canvas blit -- the primitive a project
resolution decoupled from media resolution needs. 3.82 ms/frame for
1280x720 -> 1920x1080 in release; nothing is wired to it yet.
crates/engine/src/lib.rsmodified+1 -0
@@ -14,6 +14,7 @@ pub mod hw;
14 pub mod mux;14 pub mod mux;
15 pub mod playback;15 pub mod playback;
16 pub mod project;16 pub mod project;
17+pub mod scale;
17 pub mod waveform;18 pub mod waveform;
18 19
19 pub use audio::{20 pub use audio::{
crates/engine/src/scale.rsadded+738 -0
@@ -0,0 +1,738 @@
1+//! I420 rescale and frame placement: the primitive a project resolution needs.
2+//!
3+//! A timeline has one resolution; the media on it does not. Everything a
4+//! mixed-resolution timeline asks for is these three pieces:
5+//!
6+//! * [`scale_i420`] resamples a planar frame to another size,
7+//! * [`fit_rect`] is the pure geometry -- where the scaled picture lands on the
8+//! project canvas, and which part of the source it comes from, under one of
9+//! four [`FitPolicy`] rules,
10+//! * [`compose_i420`] blits the scaled picture onto a canvas, so the pixels a
11+//! letterbox leaves over stay whatever the canvas was filled with
12+//! ([`black_i420`] is that fill).
13+//!
14+//! The filter is bilinear in 16.16 fixed point: two taps per axis, column
15+//! weights precomputed once per plane, no float and no division in the pixel
16+//! loop. That is the honest quality level for v1 -- a downscale by more than 2x
17+//! aliases, because two taps cannot carry a wider kernel. The upgrade path is a
18+//! separable Lanczos-3 (or a box prefilter before the bilinear pass) behind the
19+//! same signature: nothing here exposes the tap count. 1280x720 -> 1920x1080
20+//! measures 3.82 ms/frame in release (`perf_720p_to_1080p` below), against the
21+//! 4.7 ms the BGRA conversion next door already costs per frame.
22+//!
23+//! Sample siting: each plane is resampled as its own image with centre-aligned
24+//! mapping, `src = (dst + 0.5) * src_len / dst_len - 0.5`. For chroma that
25+//! treats I420 as centre-sited where MPEG-2 calls it left-sited, a quarter-
26+//! chroma-sample bias that no eye finds and that a siting-aware kernel would fix
27+//! in the same place the Lanczos upgrade goes.
28+
29+/// Limited-range black: what an untouched canvas pixel is.
30+pub const BLACK_Y: u8 = 16;
31+/// Neutral chroma: 128 in both planes.
32+pub const NEUTRAL_C: u8 = 128;
33+
34+/// A rectangle on one plane, in luma samples. Always inside the plane it
35+/// describes; `fit_rect` never hands back one that is not.
36+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37+pub struct Rect {
38+ pub x: u32,
39+ pub y: u32,
40+ pub w: u32,
41+ pub h: u32,
42+}
43+
44+impl Rect {
45+ pub fn is_empty(&self) -> bool {
46+ self.w == 0 || self.h == 0
47+ }
48+}
49+
50+/// How a source picture of one shape meets a canvas of another.
51+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52+pub enum FitPolicy {
53+ /// Whole picture, aspect kept, centred -- the leftover canvas is bars.
54+ #[default]
55+ Fit,
56+ /// Whole canvas, aspect kept, centred -- the leftover picture is cropped.
57+ Fill,
58+ /// Whole picture on the whole canvas; aspect is not kept.
59+ Stretch,
60+ /// No resampling at all: 1:1 samples, centred, padded or cropped per axis.
61+ Center,
62+}
63+
64+/// Placement and crop for one source on one canvas.
65+///
66+/// Returns `(dst placement rect on the canvas, src crop rect on the source)`.
67+/// The caller scales the crop to the placement size and composes it there; a
68+/// `Center` result has the two rects the same size, i.e. nothing to scale.
69+///
70+/// Rounding, and why it is what it is: both rects are aligned to the I420
71+/// chroma grid, so that one chroma sample of the scaled picture is one chroma
72+/// sample of the canvas and no colour lands half a sample off. `x` and `y` are
73+/// floored to even; `w` and `h` are floored to even *unless* the rect ends
74+/// exactly at the plane edge, where an odd size is fine because both grids end
75+/// together (that is what keeps an equal-size `Fit` a byte-exact pass-through
76+/// on an odd-width source). The alignment can therefore cost one sample of
77+/// aspect accuracy -- under a tenth of a percent at any real resolution.
78+///
79+/// A zero-sized canvas or source yields two empty rects. An extreme aspect
80+/// never rounds the picture away: the smallest rect is one chroma sample (2x2),
81+/// clipped to the plane. A plane one sample wide or high has no grid to align
82+/// to and keeps that single sample.
83+pub fn fit_rect(src_w: u32, src_h: u32, dst_w: u32, dst_h: u32, policy: FitPolicy) -> (Rect, Rect) {
84+ let empty = Rect {
85+ x: 0,
86+ y: 0,
87+ w: 0,
88+ h: 0,
89+ };
90+ if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 {
91+ return (empty, empty);
92+ }
93+ let full_src = Rect {
94+ x: 0,
95+ y: 0,
96+ w: src_w,
97+ h: src_h,
98+ };
99+ let full_dst = Rect {
100+ x: 0,
101+ y: 0,
102+ w: dst_w,
103+ h: dst_h,
104+ };
105+
106+ match policy {
107+ FitPolicy::Stretch => (full_dst, full_src),
108+ FitPolicy::Fit => {
109+ // Widest box with the source aspect that still fits the canvas.
110+ let (w, h) =
111+ if u64::from(src_w) * u64::from(dst_h) <= u64::from(dst_w) * u64::from(src_h) {
112+ (ratio(src_w, dst_h, src_h).min(dst_w), dst_h)
113+ } else {
114+ (dst_w, ratio(src_h, dst_w, src_w).min(dst_h))
115+ };
116+ (centred(w, h, dst_w, dst_h), full_src)
117+ }
118+ FitPolicy::Fill => {
119+ // Largest box with the canvas aspect that still fits the source.
120+ let (w, h) =
121+ if u64::from(src_w) * u64::from(dst_h) >= u64::from(dst_w) * u64::from(src_h) {
122+ (ratio(src_h, dst_w, dst_h).min(src_w), src_h)
123+ } else {
124+ (src_w, ratio(src_w, dst_h, dst_w).min(src_h))
125+ };
126+ (full_dst, centred(w, h, src_w, src_h))
127+ }
128+ FitPolicy::Center => {
129+ let w = src_w.min(dst_w);
130+ let h = src_h.min(dst_h);
131+ let dst = centred(w, h, dst_w, dst_h);
132+ let src = centred(w, h, src_w, src_h);
133+ // Even-alignment may have shrunk one of them; 1:1 means both carry
134+ // the same sample count, so take the smaller of the two.
135+ let w = dst.w.min(src.w);
136+ let h = dst.h.min(src.h);
137+ (Rect { w, h, ..dst }, Rect { w, h, ..src })
138+ }
139+ }
140+}
141+
142+/// `value * num / den`, rounded to nearest, in 64-bit so 8K x 8K cannot wrap.
143+fn ratio(value: u32, num: u32, den: u32) -> u32 {
144+ let den = u64::from(den).max(1);
145+ ((u64::from(value) * u64::from(num) + den / 2) / den) as u32
146+}
147+
148+/// A `w` x `h` box centred in `extent_w` x `extent_h`, chroma-grid aligned.
149+fn centred(w: u32, h: u32, extent_w: u32, extent_h: u32) -> Rect {
150+ let (x, w) = align(extent_w.saturating_sub(w) / 2, w, extent_w);
151+ let (y, h) = align(extent_h.saturating_sub(h) / 2, h, extent_h);
152+ Rect { x, y, w, h }
153+}
154+
155+/// Floors the offset to even, clips the size into the plane, and floors the
156+/// size to even unless the rect ends at the plane edge.
157+fn align(offset: u32, size: u32, extent: u32) -> (u32, u32) {
158+ let offset = (offset & !1).min(extent);
159+ let mut size = size.min(extent - offset);
160+ if offset + size < extent {
161+ size &= !1;
162+ }
163+ if size == 0 {
164+ // An extreme aspect (a 1-sample-wide source) would otherwise round its
165+ // picture away entirely. One chroma sample is the floor, not zero.
166+ size = extent.min(2);
167+ }
168+ (offset, size)
169+}
170+
171+/// Chroma plane size for a luma dimension: `(w + 1) / 2`, both axes.
172+pub fn chroma_dims(w: usize, h: usize) -> (usize, usize) {
173+ (w.div_ceil(2), h.div_ceil(2))
174+}
175+
176+/// A `w` x `h` I420 canvas filled with limited-range black.
177+pub fn black_i420(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
178+ let (cw, ch) = chroma_dims(w, h);
179+ (
180+ vec![BLACK_Y; w * h],
181+ vec![NEUTRAL_C; cw * ch],
182+ vec![NEUTRAL_C; cw * ch],
183+ )
184+}
185+
186+/// Resamples a tightly packed I420 frame (stride == width) into another one.
187+///
188+/// Equal dimensions copy byte for byte -- a project at the media's own
189+/// resolution is not a resample. Otherwise each plane is bilinear-filtered
190+/// independently, chroma at its own `(w + 1) / 2` size, so odd dimensions need
191+/// no special case: a 7x5 source has a 4x3 chroma plane and a 13x9 destination
192+/// wants a 7x5 one, and that is just another rescale.
193+///
194+/// Panics if a slice is not exactly its plane's size; a mis-sized buffer is a
195+/// caller bug, not a runtime condition, and every alternative silently produces
196+/// a sheared picture.
197+#[allow(clippy::too_many_arguments)]
198+pub fn scale_i420(
199+ src_y: &[u8],
200+ src_u: &[u8],
201+ src_v: &[u8],
202+ src_w: usize,
203+ src_h: usize,
204+ dst_y: &mut [u8],
205+ dst_u: &mut [u8],
206+ dst_v: &mut [u8],
207+ dst_w: usize,
208+ dst_h: usize,
209+) {
210+ let (src_cw, src_ch) = chroma_dims(src_w, src_h);
211+ let (dst_cw, dst_ch) = chroma_dims(dst_w, dst_h);
212+ assert_eq!(src_y.len(), src_w * src_h, "source luma plane");
213+ assert_eq!(src_u.len(), src_cw * src_ch, "source U plane");
214+ assert_eq!(src_v.len(), src_cw * src_ch, "source V plane");
215+ assert_eq!(dst_y.len(), dst_w * dst_h, "destination luma plane");
216+ assert_eq!(dst_u.len(), dst_cw * dst_ch, "destination U plane");
217+ assert_eq!(dst_v.len(), dst_cw * dst_ch, "destination V plane");
218+
219+ if src_w == dst_w && src_h == dst_h {
220+ dst_y.copy_from_slice(src_y);
221+ dst_u.copy_from_slice(src_u);
222+ dst_v.copy_from_slice(src_v);
223+ return;
224+ }
225+ plane(src_y, src_w, src_h, dst_y, dst_w, dst_h);
226+ plane(src_u, src_cw, src_ch, dst_u, dst_cw, dst_ch);
227+ plane(src_v, src_cw, src_ch, dst_v, dst_cw, dst_ch);
228+}
229+
230+/// 16.16 fixed point: one whole sample step.
231+const ONE: u32 = 1 << 16;
232+const HALF: u32 = ONE / 2;
233+
234+/// The two source samples and the weight of the second one, for one output
235+/// position: `src = (dst + 0.5) * src_len / dst_len - 0.5`, clamped to the
236+/// plane so the edges replicate instead of reading past it.
237+fn taps(dst_len: usize, src_len: usize) -> Vec<(u32, u32, u32)> {
238+ let step = (src_len as u64) * u64::from(ONE) / dst_len as u64;
239+ let last = src_len as u32 - 1;
240+ (0..dst_len)
241+ .map(|i| {
242+ // (i + 0.5) * step - 0.5, kept in u64 until the subtraction so the
243+ // clamp at 0 is the only place a negative could have appeared.
244+ let centre = (2 * i as u64 + 1) * step / 2;
245+ let pos = centre.saturating_sub(u64::from(HALF));
246+ let whole = ((pos >> 16) as u32).min(last);
247+ let frac = if whole == last {
248+ 0
249+ } else {
250+ (pos as u32) & (ONE - 1)
251+ };
252+ (whole, (whole + 1).min(last), frac)
253+ })
254+ .collect()
255+}
256+
257+/// Bilinear resample of one tightly packed 8-bit plane.
258+fn plane(src: &[u8], src_w: usize, src_h: usize, dst: &mut [u8], dst_w: usize, dst_h: usize) {
259+ if dst_w == 0 || dst_h == 0 || src_w == 0 || src_h == 0 {
260+ return;
261+ }
262+ let cols = taps(dst_w, src_w);
263+ let rows = taps(dst_h, src_h);
264+
265+ for (y, &(y0, y1, wy)) in rows.iter().enumerate() {
266+ let top = &src[y0 as usize * src_w..][..src_w];
267+ let bottom = &src[y1 as usize * src_w..][..src_w];
268+ let inv_wy = ONE - wy;
269+ let out = &mut dst[y * dst_w..][..dst_w];
270+ for (o, &(x0, x1, wx)) in out.iter_mut().zip(cols.iter()) {
271+ let inv_wx = ONE - wx;
272+ let (x0, x1) = (x0 as usize, x1 as usize);
273+ // Each stage stays under 255 * 65536 + 32768, well inside u32.
274+ let a = (u32::from(top[x0]) * inv_wx + u32::from(top[x1]) * wx + HALF) >> 16;
275+ let b = (u32::from(bottom[x0]) * inv_wx + u32::from(bottom[x1]) * wx + HALF) >> 16;
276+ *o = ((a * inv_wy + b * wy + HALF) >> 16) as u8;
277+ }
278+ }
279+}
280+
281+/// Blits a frame of exactly `rect.w` x `rect.h` onto a canvas at `rect`.
282+///
283+/// The rect is clipped to the canvas first, so a rect from anywhere (not just
284+/// [`fit_rect`]) is safe; a clipped blit copies the part that fits, from the
285+/// frame's top-left. Everything outside the rect keeps whatever the canvas
286+/// already held -- [`black_i420`] for a letterbox.
287+///
288+/// Chroma rounding: `rect.x/2` and `rect.y/2` address the canvas chroma plane,
289+/// which is exact because [`fit_rect`] hands back even offsets. An odd offset
290+/// would put the frame's chroma half a sample off its own grid, so it is
291+/// floored to even here rather than silently smeared.
292+#[allow(clippy::too_many_arguments)]
293+pub fn compose_i420(
294+ canvas_y: &mut [u8],
295+ canvas_u: &mut [u8],
296+ canvas_v: &mut [u8],
297+ canvas_w: usize,
298+ canvas_h: usize,
299+ frame_y: &[u8],
300+ frame_u: &[u8],
301+ frame_v: &[u8],
302+ rect: Rect,
303+) {
304+ let x = (rect.x & !1) as usize;
305+ let y = (rect.y & !1) as usize;
306+ if x >= canvas_w || y >= canvas_h {
307+ return;
308+ }
309+ let fw = rect.w as usize;
310+ let fh = rect.h as usize;
311+ let w = fw.min(canvas_w - x);
312+ let h = fh.min(canvas_h - y);
313+ if w == 0 || h == 0 {
314+ return;
315+ }
316+ for row in 0..h {
317+ canvas_y[(y + row) * canvas_w + x..][..w].copy_from_slice(&frame_y[row * fw..][..w]);
318+ }
319+
320+ let (canvas_cw, _) = chroma_dims(canvas_w, canvas_h);
321+ let (fcw, _) = chroma_dims(fw, fh);
322+ // Half-resolution copy of the clipped luma region, rounded up so an odd
323+ // width still carries its last (half-covered) chroma sample.
324+ let (cw, ch) = chroma_dims(w, h);
325+ let (cx, cy) = (x / 2, y / 2);
326+ for row in 0..ch {
327+ let dst = (cy + row) * canvas_cw + cx;
328+ canvas_u[dst..][..cw].copy_from_slice(&frame_u[row * fcw..][..cw]);
329+ canvas_v[dst..][..cw].copy_from_slice(&frame_v[row * fcw..][..cw]);
330+ }
331+}
332+
333+#[cfg(test)]
334+mod tests {
335+ use super::*;
336+
337+ /// Allocates the destination planes for a size and runs a scale into them.
338+ fn scaled(
339+ src: &(Vec<u8>, Vec<u8>, Vec<u8>),
340+ src_w: usize,
341+ src_h: usize,
342+ dst_w: usize,
343+ dst_h: usize,
344+ ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
345+ let (cw, ch) = chroma_dims(dst_w, dst_h);
346+ let mut dst = (
347+ vec![0u8; dst_w * dst_h],
348+ vec![0u8; cw * ch],
349+ vec![0u8; cw * ch],
350+ );
351+ scale_i420(
352+ &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
353+ );
354+ dst
355+ }
356+
357+ fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
358+ let (cw, ch) = chroma_dims(w, h);
359+ (
360+ (0..w * h).map(|i| (i % 256) as u8).collect(),
361+ (0..cw * ch).map(|i| (i % 251) as u8).collect(),
362+ (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
363+ )
364+ }
365+
366+ /// The pass-through invariant: a project at the media's own resolution must
367+ /// hand the decoder's bytes to the encoder unchanged.
368+ #[test]
369+ fn identity_scale_is_byte_identical() {
370+ for (w, h) in [(64, 48), (7, 5), (1, 1)] {
371+ let src = gradient(w, h);
372+ assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
373+ }
374+ }
375+
376+ /// Halving is the one case where bilinear is exactly a 2x2 box average:
377+ /// the output centre falls on the shared corner of four input samples.
378+ /// 0/254 averages to 127 with no rounding slack at all.
379+ #[test]
380+ fn downscale_by_two_averages_a_checkerboard() {
381+ let (w, h) = (32, 24);
382+ let (cw, ch) = chroma_dims(w, h);
383+ let checker = |i: usize, stride: usize| {
384+ if (i / stride + i % stride).is_multiple_of(2) {
385+ 0u8
386+ } else {
387+ 254
388+ }
389+ };
390+ let src = (
391+ (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
392+ (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
393+ (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
394+ );
395+ let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
396+ assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
397+ assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
398+ assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
399+ }
400+
401+ /// Nothing may leak in from outside a plane: a flat frame stays flat at
402+ /// every edge, upscaled and downscaled, odd sizes included.
403+ #[test]
404+ fn flat_frame_stays_flat() {
405+ let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
406+ for &(sw, sh) in &sizes {
407+ let (cw, ch) = chroma_dims(sw, sh);
408+ let src = (
409+ vec![80u8; sw * sh],
410+ vec![90u8; cw * ch],
411+ vec![200u8; cw * ch],
412+ );
413+ for &(dw, dh) in &sizes {
414+ let (y, u, v) = scaled(&src, sw, sh, dw, dh);
415+ assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
416+ assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
417+ assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
418+ }
419+ }
420+ }
421+
422+ /// Chroma alignment: an edge in the U plane must land at the *same* place
423+ /// after a 2x upscale, with a symmetric two-sample blend around it and
424+ /// untouched flats either side -- a half-sample bias shows up as an
425+ /// asymmetric pair here, which is colour bleeding one way.
426+ #[test]
427+ fn chroma_edge_keeps_its_position() {
428+ let (w, h) = (8, 8);
429+ let (cw, ch) = chroma_dims(w, h);
430+ // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
431+ let src = (
432+ vec![80u8; w * h],
433+ (0..cw * ch)
434+ .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
435+ .collect(),
436+ vec![128u8; cw * ch],
437+ );
438+ let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
439+ let (dcw, _) = chroma_dims(w * 2, h * 2);
440+ assert_eq!(dcw, 8);
441+ let row = &u[dcw * 3..][..dcw];
442+ assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
443+ assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
444+ // The two blend samples are 117.5 and 172.5 before rounding: symmetric
445+ // about the 145 midpoint, so they sum to 290. Round-half-up costs at
446+ // most 1; anything further means the edge moved.
447+ assert!(
448+ (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
449+ "blend is off centre, i.e. chroma bled one way: {row:?}"
450+ );
451+ }
452+
453+ /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
454+ /// `(src, dst, policy) -> (placement, crop)`.
455+ #[test]
456+ fn fit_rect_table() {
457+ let r = |x, y, w, h| Rect { x, y, w, h };
458+ let cases = [
459+ // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
460+ (
461+ (1920, 1080),
462+ (640, 480),
463+ FitPolicy::Fit,
464+ r(0, 60, 640, 360),
465+ r(0, 0, 1920, 1080),
466+ ),
467+ // ...and the same pair filled: the canvas is whole, the source is
468+ // cropped to 4:3 (1440 wide) about its centre.
469+ (
470+ (1920, 1080),
471+ (640, 480),
472+ FitPolicy::Fill,
473+ r(0, 0, 640, 480),
474+ r(240, 0, 1440, 1080),
475+ ),
476+ // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
477+ (
478+ (640, 480),
479+ (1920, 1080),
480+ FitPolicy::Fit,
481+ r(240, 0, 1440, 1080),
482+ r(0, 0, 640, 480),
483+ ),
484+ (
485+ (640, 480),
486+ (1920, 1080),
487+ FitPolicy::Fill,
488+ r(0, 0, 1920, 1080),
489+ r(0, 60, 640, 360),
490+ ),
491+ // Stretch ignores aspect entirely, both ways.
492+ (
493+ (1920, 1080),
494+ (640, 480),
495+ FitPolicy::Stretch,
496+ r(0, 0, 640, 480),
497+ r(0, 0, 1920, 1080),
498+ ),
499+ // 1:1 with a bigger source: cropped both ways, centred.
500+ (
501+ (1920, 1080),
502+ (640, 480),
503+ FitPolicy::Center,
504+ r(0, 0, 640, 480),
505+ r(640, 300, 640, 480),
506+ ),
507+ // 1:1 with a smaller source: padded both ways, centred.
508+ (
509+ (640, 480),
510+ (1920, 1080),
511+ FitPolicy::Center,
512+ r(640, 300, 640, 480),
513+ r(0, 0, 640, 480),
514+ ),
515+ // Odd sizes: offsets even, sizes even unless they reach the edge.
516+ ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
517+ (
518+ (7, 5),
519+ (13, 9),
520+ FitPolicy::Fit,
521+ r(0, 0, 13, 9),
522+ r(0, 0, 7, 5),
523+ ),
524+ // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
525+ // offset without putting chroma half a sample off, so the last one
526+ // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
527+ (
528+ (9, 9),
529+ (13, 9),
530+ FitPolicy::Center,
531+ r(2, 0, 8, 9),
532+ r(0, 0, 8, 9),
533+ ),
534+ (
535+ (13, 9),
536+ (9, 9),
537+ FitPolicy::Center,
538+ r(0, 0, 8, 9),
539+ r(2, 0, 8, 9),
540+ ),
541+ ];
542+ for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
543+ let got = fit_rect(sw, sh, dw, dh, policy);
544+ assert_eq!(
545+ got,
546+ (want_dst, want_src),
547+ "{sw}x{sh} -> {dw}x{dh} {policy:?}"
548+ );
549+ }
550+ // Degenerate input is empty, not a panic.
551+ assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
552+ assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
553+ }
554+
555+ /// Every rect a policy hands back must sit inside its plane, start on the
556+ /// chroma grid, and end on it or at the plane edge -- the invariant
557+ /// `compose_i420` relies on.
558+ #[test]
559+ fn fit_rect_stays_on_the_chroma_grid() {
560+ let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
561+ for policy in [
562+ FitPolicy::Fit,
563+ FitPolicy::Fill,
564+ FitPolicy::Stretch,
565+ FitPolicy::Center,
566+ ] {
567+ for &sw in &sizes {
568+ for &dh in &sizes {
569+ let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
570+ let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
571+ let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
572+ for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
573+ let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
574+ assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
575+ assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
576+ assert_eq!(rect.x % 2, 0, "{ctx} odd x");
577+ assert_eq!(rect.y % 2, 0, "{ctx} odd y");
578+ // A plane one sample wide or high has no chroma grid to
579+ // be on: `Center` from a 2-high source onto a 1-high
580+ // canvas is one row, and no size satisfies both edges.
581+ // Nothing real is that shape; it must merely not
582+ // escape its plane, which the two asserts above cover.
583+ if grid {
584+ assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
585+ assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
586+ }
587+ assert!(!rect.is_empty(), "{ctx} empty");
588+ }
589+ }
590+ }
591+ }
592+ }
593+
594+ #[test]
595+ fn compose_fills_the_rect_and_nothing_else() {
596+ let (cw2, ch2) = (640usize, 360usize);
597+ let (canvas_w, canvas_h) = (640usize, 480usize);
598+ let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
599+ let (fcw, fch) = chroma_dims(cw2, ch2);
600+ let frame = (
601+ vec![200u8; cw2 * ch2],
602+ vec![70u8; fcw * fch],
603+ vec![30u8; fcw * fch],
604+ );
605+ let rect = Rect {
606+ x: 0,
607+ y: 60,
608+ w: cw2 as u32,
609+ h: ch2 as u32,
610+ };
611+ compose_i420(
612+ &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
613+ );
614+
615+ for row in 0..canvas_h {
616+ let inside = (60..420).contains(&row);
617+ let want = if inside { 200 } else { BLACK_Y };
618+ assert!(
619+ y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
620+ "luma row {row}"
621+ );
622+ }
623+ let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
624+ for row in 0..cch {
625+ let inside = (30..210).contains(&row);
626+ let (wu, wv) = if inside {
627+ (70, 30)
628+ } else {
629+ (NEUTRAL_C, NEUTRAL_C)
630+ };
631+ assert!(
632+ u[row * ccw..][..ccw].iter().all(|&s| s == wu),
633+ "U row {row}"
634+ );
635+ assert!(
636+ v[row * ccw..][..ccw].iter().all(|&s| s == wv),
637+ "V row {row}"
638+ );
639+ }
640+ }
641+
642+ /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
643+ /// is public and a caller may compute a rect itself.
644+ #[test]
645+ fn compose_clips_a_rect_that_runs_off_the_canvas() {
646+ let (mut y, mut u, mut v) = black_i420(16, 16);
647+ let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
648+ let rect = Rect {
649+ x: 12,
650+ y: 12,
651+ w: 8,
652+ h: 8,
653+ };
654+ compose_i420(
655+ &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
656+ );
657+ assert_eq!(y[15 * 16 + 15], 99);
658+ assert_eq!(y[11 * 16 + 15], BLACK_Y);
659+ // Wholly outside: no write at all.
660+ let before = y.clone();
661+ compose_i420(
662+ &mut y,
663+ &mut u,
664+ &mut v,
665+ 16,
666+ 16,
667+ &frame.0,
668+ &frame.1,
669+ &frame.2,
670+ Rect {
671+ x: 100,
672+ y: 0,
673+ w: 8,
674+ h: 8,
675+ },
676+ );
677+ assert_eq!(y, before);
678+ }
679+
680+ /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
681+ /// project canvas, letterbox bars intact.
682+ #[test]
683+ fn fit_scale_compose_letterboxes() {
684+ let (sw, sh) = (640usize, 480usize);
685+ let (dw, dh) = (1920usize, 1080usize);
686+ let src = gradient(sw, sh);
687+ let (dst_rect, src_rect) =
688+ fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
689+ assert_eq!(
690+ src_rect,
691+ Rect {
692+ x: 0,
693+ y: 0,
694+ w: 640,
695+ h: 480
696+ }
697+ );
698+ let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
699+ let picture = scaled(&src, sw, sh, rw, rh);
700+ let (mut y, mut u, mut v) = black_i420(dw, dh);
701+ compose_i420(
702+ &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
703+ );
704+ // Pillarbox columns stay black, the picture area does not.
705+ let mid = (dh / 2) * dw;
706+ assert!(
707+ y[mid..mid + dst_rect.x as usize]
708+ .iter()
709+ .all(|&s| s == BLACK_Y)
710+ );
711+ assert_eq!(
712+ y[mid + dst_rect.x as usize..][..rw],
713+ picture.0[(rh / 2) * rw..][..rw]
714+ );
715+ }
716+
717+ /// Not asserted: only the release number means anything. Run with
718+ /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
719+ #[test]
720+ fn perf_720p_to_1080p() {
721+ let src = gradient(1280, 720);
722+ let (cw, ch) = chroma_dims(1920, 1080);
723+ let mut dst = (
724+ vec![0u8; 1920 * 1080],
725+ vec![0u8; cw * ch],
726+ vec![0u8; cw * ch],
727+ );
728+ let runs = 30;
729+ let t = std::time::Instant::now();
730+ for _ in 0..runs {
731+ scale_i420(
732+ &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
733+ );
734+ }
735+ let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
736+ println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
737+ }
738+}