forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

scale.rs1687 lines, 69.0 KiBHistoryRawDownload
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
29use crate::transform::TransformParams;
30
31/// Limited-range black: what an untouched canvas pixel is.
32pub const BLACK_Y: u8 = 16;
33/// Neutral chroma: 128 in both planes.
34pub const NEUTRAL_C: u8 = 128;
35
36/// A rectangle on one plane, in luma samples. Always inside the plane it
37/// describes; `fit_rect` never hands back one that is not.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct Rect {
40 pub x: u32,
41 pub y: u32,
42 pub w: u32,
43 pub h: u32,
44}
45
46impl Rect {
47 pub fn is_empty(&self) -> bool {
48 self.w == 0 || self.h == 0
49 }
50}
51
52/// How a source picture of one shape meets a canvas of another.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum FitPolicy {
55 /// Whole picture, aspect kept, centred -- the leftover canvas is bars.
56 #[default]
57 Fit,
58 /// Whole canvas, aspect kept, centred -- the leftover picture is cropped.
59 Fill,
60 /// Whole picture on the whole canvas; aspect is not kept.
61 Stretch,
62 /// No resampling at all: 1:1 samples, centred, padded or cropped per axis.
63 Center,
64}
65
66/// Placement and crop for one source on one canvas.
67///
68/// Returns `(dst placement rect on the canvas, src crop rect on the source)`.
69/// The caller scales the crop to the placement size and composes it there; a
70/// `Center` result has the two rects the same size, i.e. nothing to scale.
71///
72/// Rounding, and why it is what it is: both rects are aligned to the I420
73/// chroma grid, so that one chroma sample of the scaled picture is one chroma
74/// sample of the canvas and no colour lands half a sample off. `x` and `y` are
75/// floored to even; `w` and `h` are floored to even *unless* the rect ends
76/// exactly at the plane edge, where an odd size is fine because both grids end
77/// together (that is what keeps an equal-size `Fit` a byte-exact pass-through
78/// on an odd-width source). The alignment can therefore cost one sample of
79/// aspect accuracy -- under a tenth of a percent at any real resolution.
80///
81/// A zero-sized canvas or source yields two empty rects. An extreme aspect
82/// never rounds the picture away: the smallest rect is one chroma sample (2x2),
83/// clipped to the plane. A plane one sample wide or high has no grid to align
84/// to and keeps that single sample.
85pub fn fit_rect(src_w: u32, src_h: u32, dst_w: u32, dst_h: u32, policy: FitPolicy) -> (Rect, Rect) {
86 let empty = Rect {
87 x: 0,
88 y: 0,
89 w: 0,
90 h: 0,
91 };
92 if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 {
93 return (empty, empty);
94 }
95 let full_src = Rect {
96 x: 0,
97 y: 0,
98 w: src_w,
99 h: src_h,
100 };
101 let full_dst = Rect {
102 x: 0,
103 y: 0,
104 w: dst_w,
105 h: dst_h,
106 };
107
108 match policy {
109 FitPolicy::Stretch => (full_dst, full_src),
110 FitPolicy::Fit => {
111 // Widest box with the source aspect that still fits the canvas.
112 let (w, h) =
113 if u64::from(src_w) * u64::from(dst_h) <= u64::from(dst_w) * u64::from(src_h) {
114 (ratio(src_w, dst_h, src_h).min(dst_w), dst_h)
115 } else {
116 (dst_w, ratio(src_h, dst_w, src_w).min(dst_h))
117 };
118 (centred(w, h, dst_w, dst_h), full_src)
119 }
120 FitPolicy::Fill => {
121 // Largest box with the canvas aspect that still fits the source.
122 let (w, h) =
123 if u64::from(src_w) * u64::from(dst_h) >= u64::from(dst_w) * u64::from(src_h) {
124 (ratio(src_h, dst_w, dst_h).min(src_w), src_h)
125 } else {
126 (src_w, ratio(src_w, dst_h, dst_w).min(src_h))
127 };
128 (full_dst, centred(w, h, src_w, src_h))
129 }
130 FitPolicy::Center => {
131 let w = src_w.min(dst_w);
132 let h = src_h.min(dst_h);
133 let dst = centred(w, h, dst_w, dst_h);
134 let src = centred(w, h, src_w, src_h);
135 // Even-alignment may have shrunk one of them; 1:1 means both carry
136 // the same sample count, so take the smaller of the two.
137 let w = dst.w.min(src.w);
138 let h = dst.h.min(src.h);
139 (Rect { w, h, ..dst }, Rect { w, h, ..src })
140 }
141 }
142}
143
144/// `value * num / den`, rounded to nearest, in 64-bit so 8K x 8K cannot wrap.
145fn ratio(value: u32, num: u32, den: u32) -> u32 {
146 let den = u64::from(den).max(1);
147 ((u64::from(value) * u64::from(num) + den / 2) / den) as u32
148}
149
150/// A `w` x `h` box centred in `extent_w` x `extent_h`, chroma-grid aligned.
151fn centred(w: u32, h: u32, extent_w: u32, extent_h: u32) -> Rect {
152 let (x, w) = align(extent_w.saturating_sub(w) / 2, w, extent_w);
153 let (y, h) = align(extent_h.saturating_sub(h) / 2, h, extent_h);
154 Rect { x, y, w, h }
155}
156
157/// Floors the offset to even, clips the size into the plane, and floors the
158/// size to even unless the rect ends at the plane edge.
159fn align(offset: u32, size: u32, extent: u32) -> (u32, u32) {
160 let offset = (offset & !1).min(extent);
161 let mut size = size.min(extent - offset);
162 if offset + size < extent {
163 size &= !1;
164 }
165 if size == 0 {
166 // An extreme aspect (a 1-sample-wide source) would otherwise round its
167 // picture away entirely. One chroma sample is the floor, not zero.
168 size = extent.min(2);
169 }
170 (offset, size)
171}
172
173/// Chroma plane size for a luma dimension: `(w + 1) / 2`, both axes.
174pub fn chroma_dims(w: usize, h: usize) -> (usize, usize) {
175 (w.div_ceil(2), h.div_ceil(2))
176}
177
178/// A `w` x `h` I420 canvas filled with limited-range black.
179pub fn black_i420(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
180 let (cw, ch) = chroma_dims(w, h);
181 (
182 vec![BLACK_Y; w * h],
183 vec![NEUTRAL_C; cw * ch],
184 vec![NEUTRAL_C; cw * ch],
185 )
186}
187
188/// Resamples a tightly packed I420 frame (stride == width) into another one.
189///
190/// Equal dimensions copy byte for byte -- a project at the media's own
191/// resolution is not a resample. Otherwise each plane is bilinear-filtered
192/// independently, chroma at its own `(w + 1) / 2` size, so odd dimensions need
193/// no special case: a 7x5 source has a 4x3 chroma plane and a 13x9 destination
194/// wants a 7x5 one, and that is just another rescale.
195///
196/// Panics if a slice is not exactly its plane's size; a mis-sized buffer is a
197/// caller bug, not a runtime condition, and every alternative silently produces
198/// a sheared picture.
199#[allow(clippy::too_many_arguments)]
200pub fn scale_i420(
201 src_y: &[u8],
202 src_u: &[u8],
203 src_v: &[u8],
204 src_w: usize,
205 src_h: usize,
206 dst_y: &mut [u8],
207 dst_u: &mut [u8],
208 dst_v: &mut [u8],
209 dst_w: usize,
210 dst_h: usize,
211) {
212 let (src_cw, src_ch) = chroma_dims(src_w, src_h);
213 let (dst_cw, dst_ch) = chroma_dims(dst_w, dst_h);
214 assert_eq!(src_y.len(), src_w * src_h, "source luma plane");
215 assert_eq!(src_u.len(), src_cw * src_ch, "source U plane");
216 assert_eq!(src_v.len(), src_cw * src_ch, "source V plane");
217 assert_eq!(dst_y.len(), dst_w * dst_h, "destination luma plane");
218 assert_eq!(dst_u.len(), dst_cw * dst_ch, "destination U plane");
219 assert_eq!(dst_v.len(), dst_cw * dst_ch, "destination V plane");
220
221 if src_w == dst_w && src_h == dst_h {
222 dst_y.copy_from_slice(src_y);
223 dst_u.copy_from_slice(src_u);
224 dst_v.copy_from_slice(src_v);
225 return;
226 }
227 plane(src_y, src_w, src_h, dst_y, dst_w, dst_h);
228 plane(src_u, src_cw, src_ch, dst_u, dst_cw, dst_ch);
229 plane(src_v, src_cw, src_ch, dst_v, dst_cw, dst_ch);
230}
231
232/// 16.16 fixed point: one whole sample step.
233const ONE: u32 = 1 << 16;
234const HALF: u32 = ONE / 2;
235
236/// The two source samples and the weight of the second one, for one output
237/// position: `src = (dst + 0.5) * src_len / dst_len - 0.5`, clamped to the
238/// plane so the edges replicate instead of reading past it.
239fn taps(dst_len: usize, src_len: usize) -> Vec<(u32, u32, u32)> {
240 let step = (src_len as u64) * u64::from(ONE) / dst_len as u64;
241 let last = src_len as u32 - 1;
242 (0..dst_len)
243 .map(|i| {
244 // (i + 0.5) * step - 0.5, kept in u64 until the subtraction so the
245 // clamp at 0 is the only place a negative could have appeared.
246 let centre = (2 * i as u64 + 1) * step / 2;
247 let pos = centre.saturating_sub(u64::from(HALF));
248 let whole = ((pos >> 16) as u32).min(last);
249 let frac = if whole == last {
250 0
251 } else {
252 (pos as u32) & (ONE - 1)
253 };
254 (whole, (whole + 1).min(last), frac)
255 })
256 .collect()
257}
258
259/// Bilinear resample of one tightly packed 8-bit plane.
260fn plane(src: &[u8], src_w: usize, src_h: usize, dst: &mut [u8], dst_w: usize, dst_h: usize) {
261 if dst_w == 0 || dst_h == 0 || src_w == 0 || src_h == 0 {
262 return;
263 }
264 let cols = taps(dst_w, src_w);
265 let rows = taps(dst_h, src_h);
266
267 for (y, &(y0, y1, wy)) in rows.iter().enumerate() {
268 let top = &src[y0 as usize * src_w..][..src_w];
269 let bottom = &src[y1 as usize * src_w..][..src_w];
270 let inv_wy = ONE - wy;
271 let out = &mut dst[y * dst_w..][..dst_w];
272 for (o, &(x0, x1, wx)) in out.iter_mut().zip(cols.iter()) {
273 let inv_wx = ONE - wx;
274 let (x0, x1) = (x0 as usize, x1 as usize);
275 // Each stage stays under 255 * 65536 + 32768, well inside u32.
276 let a = (u32::from(top[x0]) * inv_wx + u32::from(top[x1]) * wx + HALF) >> 16;
277 let b = (u32::from(bottom[x0]) * inv_wx + u32::from(bottom[x1]) * wx + HALF) >> 16;
278 *o = ((a * inv_wy + b * wy + HALF) >> 16) as u8;
279 }
280 }
281}
282
283/// Blits a frame of exactly `rect.w` x `rect.h` onto a canvas at `rect`.
284///
285/// The rect is clipped to the canvas first, so a rect from anywhere (not just
286/// [`fit_rect`]) is safe; a clipped blit copies the part that fits, from the
287/// frame's top-left. Everything outside the rect keeps whatever the canvas
288/// already held -- [`black_i420`] for a letterbox.
289///
290/// Chroma rounding: `rect.x/2` and `rect.y/2` address the canvas chroma plane,
291/// which is exact because [`fit_rect`] hands back even offsets. An odd offset
292/// would put the frame's chroma half a sample off its own grid, so it is
293/// floored to even here rather than silently smeared.
294#[allow(clippy::too_many_arguments)]
295pub fn compose_i420(
296 canvas_y: &mut [u8],
297 canvas_u: &mut [u8],
298 canvas_v: &mut [u8],
299 canvas_w: usize,
300 canvas_h: usize,
301 frame_y: &[u8],
302 frame_u: &[u8],
303 frame_v: &[u8],
304 rect: Rect,
305) {
306 let x = (rect.x & !1) as usize;
307 let y = (rect.y & !1) as usize;
308 if x >= canvas_w || y >= canvas_h {
309 return;
310 }
311 let fw = rect.w as usize;
312 let fh = rect.h as usize;
313 let w = fw.min(canvas_w - x);
314 let h = fh.min(canvas_h - y);
315 if w == 0 || h == 0 {
316 return;
317 }
318 for row in 0..h {
319 canvas_y[(y + row) * canvas_w + x..][..w].copy_from_slice(&frame_y[row * fw..][..w]);
320 }
321
322 let (canvas_cw, _) = chroma_dims(canvas_w, canvas_h);
323 let (fcw, _) = chroma_dims(fw, fh);
324 // Half-resolution copy of the clipped luma region, rounded up so an odd
325 // width still carries its last (half-covered) chroma sample.
326 let (cw, ch) = chroma_dims(w, h);
327 let (cx, cy) = (x / 2, y / 2);
328 for row in 0..ch {
329 let dst = (cy + row) * canvas_cw + cx;
330 canvas_u[dst..][..cw].copy_from_slice(&frame_u[row * fcw..][..cw]);
331 canvas_v[dst..][..cw].copy_from_slice(&frame_v[row * fcw..][..cw]);
332 }
333}
334
335/// The source rect [`TransformParams`]'s crop fractions cut out of a `src_w` x
336/// `src_h` picture, chroma-grid aligned exactly as [`fit_rect`]'s rects are.
337/// Fractions are clamped to `0.0..=0.5` a side, so opposing crops can never
338/// meet or cross -- the smallest surviving rect is one chroma sample, for
339/// [`align`]'s reason.
340pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect {
341 if src_w == 0 || src_h == 0 {
342 return Rect { x: 0, y: 0, w: 0, h: 0 };
343 }
344 let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5));
345 let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5));
346 let x0 = (f64::from(src_w) * f64::from(cl)).round() as u32;
347 let x1 = (f64::from(src_w) * (1.0 - f64::from(cr))).round() as u32;
348 let y0 = (f64::from(src_h) * f64::from(ct)).round() as u32;
349 let y1 = (f64::from(src_h) * (1.0 - f64::from(cb))).round() as u32;
350 let (x, w) = align(x0.min(src_w), x1.saturating_sub(x0), src_w);
351 let (y, h) = align(y0.min(src_h), y1.saturating_sub(y0), src_h);
352 Rect { x, y, w, h }
353}
354
355/// `dst` -- a placement [`fit_rect`] already worked out, paired with the `src`
356/// rect (inside a `src_w` x `src_h` picture) it is sourced from -- moved by
357/// [`TransformParams::pos_x`]/`pos_y` (canvas fractions, about `dst`'s own
358/// centre) and resized by `scale` (about that same centre).
359///
360/// Translation and scale never distort the picture: the placed box keeps the
361/// aspect its size and `scale` give it, full stop. What moving it off-canvas
362/// does is clip -- the part of the box that falls outside `0..canvas_w` /
363/// `0..canvas_h` is dropped, and the matching fraction of `src` is trimmed
364/// off the same sides, so what remains on screen is an unscaled slice of the
365/// source, not the whole source squeezed into whatever box survived
366/// clamping. Both rects come back chroma-grid aligned like every other rect
367/// here; a placement pushed entirely off the canvas comes back as two empty
368/// rects, which is what [`compose_i420`] already treats as nothing to draw.
369pub fn transformed_dst_rect(
370 dst: Rect,
371 src: Rect,
372 src_w: u32,
373 src_h: u32,
374 t: &TransformParams,
375 canvas_w: u32,
376 canvas_h: u32,
377) -> (Rect, Rect) {
378 let empty = Rect { x: 0, y: 0, w: 0, h: 0 };
379 if dst.is_empty() || src.is_empty() || canvas_w == 0 || canvas_h == 0 {
380 return (dst, src);
381 }
382 let scale = if t.scale.is_finite() && t.scale > 0.0 {
383 f64::from(t.scale)
384 } else {
385 1.0
386 };
387 // Bounded well above any real canvas so the src-trim ratios below cannot
388 // overflow i64, however extreme a stored scale value is.
389 let cap_w = i64::from(canvas_w.max(1)) * 1024;
390 let cap_h = i64::from(canvas_h.max(1)) * 1024;
391 let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, cap_w);
392 let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, cap_h);
393 let pos_x = if t.pos_x.is_finite() { f64::from(t.pos_x) } else { 0.0 };
394 let pos_y = if t.pos_y.is_finite() { f64::from(t.pos_y) } else { 0.0 };
395 let cx = i64::from(dst.x) + i64::from(dst.w) / 2 + (f64::from(canvas_w) * pos_x).round() as i64;
396 let cy = i64::from(dst.y) + i64::from(dst.h) / 2 + (f64::from(canvas_h) * pos_y).round() as i64;
397 // The full box the transform describes, unclamped -- it may start
398 // negative or run past either edge, which is exactly what "moved off the
399 // canvas" means.
400 let bx = cx - new_w / 2;
401 let by = cy - new_h / 2;
402
403 // How much of that box, in the box's own pixels, falls outside the
404 // canvas on each side.
405 let left = (-bx).clamp(0, new_w);
406 let top = (-by).clamp(0, new_h);
407 let right = (bx + new_w - i64::from(canvas_w)).clamp(0, new_w);
408 let bottom = (by + new_h - i64::from(canvas_h)).clamp(0, new_h);
409 if left + right >= new_w || top + bottom >= new_h {
410 return (empty, empty);
411 }
412
413 let dst_x = (bx + left).clamp(0, i64::from(canvas_w)) as u32;
414 let dst_y = (by + top).clamp(0, i64::from(canvas_h)) as u32;
415 let (dst_x, dst_w) = align(dst_x, (new_w - left - right) as u32, canvas_w);
416 let (dst_y, dst_h) = align(dst_y, (new_h - top - bottom) as u32, canvas_h);
417
418 // The same fraction trimmed off `src`, on the matching side: uniform
419 // scale means the ratio of trimmed-box-pixels to source-pixels is the
420 // same on both axes as the ratio of the box's own size to `src`'s.
421 let src_left = i64::from(src.w) * left / new_w;
422 let src_right = i64::from(src.w) * right / new_w;
423 let src_top = i64::from(src.h) * top / new_h;
424 let src_bottom = i64::from(src.h) * bottom / new_h;
425 let src_x = src.x + src_left as u32;
426 let src_y = src.y + src_top as u32;
427 let (src_x, src_w_) = align(src_x, src.w.saturating_sub((src_left + src_right) as u32), src_w);
428 let (src_y, src_h_) = align(src_y, src.h.saturating_sub((src_top + src_bottom) as u32), src_h);
429
430 (
431 Rect { x: dst_x, y: dst_y, w: dst_w, h: dst_h },
432 Rect { x: src_x, y: src_y, w: src_w_, h: src_h_ },
433 )
434}
435
436/// Nearest 90-degree step `degrees` renders at: `0` (0deg), `1` (90deg
437/// clockwise), `2` (180deg) or `3` (270deg). Continuous rotation is not
438/// rendered at all -- see the [`crate::transform`] module docs -- so this is
439/// the one lossy step between what a project *stores* and what a frame
440/// *shows*. Non-finite folds to `0`.
441pub fn nearest_90_steps(degrees: f32) -> u8 {
442 if !degrees.is_finite() {
443 return 0;
444 }
445 let norm = degrees.rem_euclid(360.0);
446 ((norm / 90.0).round() as i64).rem_euclid(4) as u8
447}
448
449/// Rotates a tightly packed I420 frame by `steps` quarter turns clockwise
450/// (`steps % 4`; see [`nearest_90_steps`]). `0` and `2` keep the frame's
451/// shape, `1` and `3` swap it -- the chroma planes rotate the same way at
452/// their own `(w+1)/2` x `(h+1)/2` size, which stays exact because it is
453/// exactly the luma size's, swapped the same way.
454pub fn rotate_i420_90s(
455 y: &[u8],
456 u: &[u8],
457 v: &[u8],
458 w: u32,
459 h: u32,
460 steps: u8,
461) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
462 let steps = steps % 4;
463 if steps == 0 || w == 0 || h == 0 {
464 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
465 }
466 let (cw, ch) = chroma_dims(w as usize, h as usize);
467 let (ry, rw, rh) = rotate_plane(y, w as usize, h as usize, steps);
468 let (ru, ..) = rotate_plane(u, cw, ch, steps);
469 let (rv, ..) = rotate_plane(v, cw, ch, steps);
470 (ry, ru, rv, rw as u32, rh as u32)
471}
472
473/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise.
474fn rotate_plane(src: &[u8], w: usize, h: usize, steps: u8) -> (Vec<u8>, usize, usize) {
475 match steps {
476 1 => {
477 let (nw, nh) = (h, w);
478 let mut out = vec![0u8; nw * nh];
479 for yp in 0..nh {
480 for xp in 0..nw {
481 out[yp * nw + xp] = src[(h - 1 - xp) * w + yp];
482 }
483 }
484 (out, nw, nh)
485 }
486 2 => {
487 let mut out = vec![0u8; w * h];
488 for yp in 0..h {
489 for xp in 0..w {
490 out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)];
491 }
492 }
493 (out, w, h)
494 }
495 3 => {
496 let (nw, nh) = (h, w);
497 let mut out = vec![0u8; nw * nh];
498 for yp in 0..nh {
499 for xp in 0..nw {
500 out[yp * nw + xp] = src[xp * w + (w - 1 - yp)];
501 }
502 }
503 (out, nw, nh)
504 }
505 _ => unreachable!("steps % 4 is 1, 2 or 3 here"),
506 }
507}
508
509/// One clip's pictures placed on the project canvas: the geometry, plus the
510/// buffers it composes into so a frame costs no allocation.
511///
512/// This is the *one* definition of what a mixed-resolution timeline looks like:
513/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
514/// decoded planes to [`place`](Composer::place), so what is watched and what is
515/// written cannot drift apart.
516///
517/// **Order against the colour grade: grade first, place second.** A grade
518/// belongs to the clip's own pixels -- it is graded at the resolution it was
519/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
520/// letterbox bars are *not* the clip: a brightness grade that reached them would
521/// lift the black frame around the picture. Callers therefore grade the source
522/// planes and place the result; the bars stay exactly [`black_i420`].
523///
524/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of
525/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a
526/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at
527/// 4096x2160 (the floor), all measured. A worker holds one more than this in its
528/// hand, so a burst off a full queue is `queue_depth + 1`.
529///
530/// The floor of 2 is the bound this engine ran on everywhere before there was
531/// any decode-ahead; the ceiling keeps a small picture from queueing a second of
532/// video the consumer would have to walk through after a seek.
533pub(crate) fn queue_depth(width: u32, height: u32) -> usize {
534 const BUDGET: usize = 96 << 20;
535 let bytes = width as usize * height as usize * 4;
536 if bytes == 0 {
537 return 2;
538 }
539 (BUDGET / bytes).clamp(2, 16)
540}
541
542/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
543/// hands the caller's own planes straight back, allocates nothing and touches no
544/// byte, which is what keeps a project at its media's resolution the byte-for-byte
545/// path it was before there was a project resolution at all.
546///
547/// [`place`]: Composer::place
548pub struct Composer {
549 width: u32,
550 height: u32,
551 policy: FitPolicy,
552 /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
553 /// `Center` ever crop, so this stays empty for a letterboxed project.
554 crop: (Vec<u8>, Vec<u8>, Vec<u8>),
555 /// The crop resampled to the placement rect.
556 scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
557 /// The canvas itself, refilled with black every frame -- a memset against a
558 /// decode, and the only way a policy change cannot leave last frame's bars
559 /// showing through.
560 canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
561}
562
563impl Composer {
564 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
565 let empty = || (Vec::new(), Vec::new(), Vec::new());
566 Self {
567 width,
568 height,
569 policy,
570 crop: empty(),
571 scaled: empty(),
572 canvas: empty(),
573 }
574 }
575
576 /// A composer that places nothing: every picture passes through at its own
577 /// size. What the file-level decode API opens with, where there is no
578 /// project and therefore no canvas.
579 pub fn passthrough() -> Self {
580 Self::new(0, 0, FitPolicy::Fit)
581 }
582
583 /// Whether this canvas is the one that places nothing
584 /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand,
585 /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that
586 /// needs it is sizing a queue before anything has been decoded.
587 pub(crate) fn places_nothing(&self) -> bool {
588 self.width == 0 || self.height == 0
589 }
590
591 /// How many decoded pictures a worker over this canvas may keep ahead of
592 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
593 /// than a 1080p one instead of the same number of far bigger frames.
594 ///
595 /// A **pass-through** canvas has no size of its own -- the pictures come out
596 /// at the source's -- so it cannot answer, and the caller that knows the
597 /// stream asks [`queue_depth`] with those dimensions instead. Answering 2
598 /// here would be the pre-decode-ahead bound, which is exactly the bug this
599 /// pair exists to keep out of the file-open path.
600 pub(crate) fn queue_depth(&self) -> usize {
601 queue_depth(self.width, self.height)
602 }
603
604 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
605 /// composer would hand it back untouched. What lets a caller keep a fused
606 /// fast path (the graded conversion) for the common case.
607 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
608 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
609 }
610
611 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
612 /// caller's own planes (pass-through) or the canvas with the fitted picture
613 /// composed onto it. The dimensions come back because those two differ.
614 ///
615 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
616 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
617 pub fn place<'a>(
618 &'a mut self,
619 y: &'a [u8],
620 u: &'a [u8],
621 v: &'a [u8],
622 src_w: u32,
623 src_h: u32,
624 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
625 if self.is_passthrough(src_w, src_h) {
626 return (y, u, v, src_w, src_h);
627 }
628 let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
629 let (sw, sh) = (src_w as usize, src_h as usize);
630
631 // Crop first, so the scaler only ever sees a tightly packed plane. Fit
632 // and Stretch never crop, which is the whole cost of the common case.
633 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
634 (y, u, v)
635 } else {
636 crop_i420(&mut self.crop, y, u, v, sw, sh, src);
637 (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
638 };
639 // ...then resample it to the placement, unless it already is that size
640 // (`Center` never resamples, and neither does an exact-fit upscale).
641 let (cw, ch) = (src.w as usize, src.h as usize);
642 let (dw, dh) = (dst.w as usize, dst.h as usize);
643 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
644 (src_y, src_u, src_v)
645 } else {
646 let (ccw, cch) = chroma_dims(dw, dh);
647 let (sy, su, sv) = &mut self.scaled;
648 sy.resize(dw * dh, 0);
649 su.resize(ccw * cch, 0);
650 sv.resize(ccw * cch, 0);
651 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
652 (&sy[..], &su[..], &sv[..])
653 };
654
655 let (w, h) = (self.width as usize, self.height as usize);
656 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
657 let (ky, ku, kv) = &mut self.canvas;
658 fill(ky, w * h, BLACK_Y);
659 fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
660 fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
661 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
662 (ky, ku, kv, self.width, self.height)
663 }
664
665 /// [`place`](Self::place) with a per-clip [`TransformParams`] applied on
666 /// top of the fit policy: the source is cropped to [`crop_rect`], rotated
667 /// by [`rotate_i420_90s`] to [`nearest_90_steps`] of `t.rotate`, fit to the
668 /// canvas exactly as an untransformed picture is, and the fitted
669 /// placement is then moved/resized/clipped by [`transformed_dst_rect`],
670 /// which also trims the matching slice off the source rect so an
671 /// off-canvas move clips instead of squeezing.
672 /// `t.is_identity()` takes the exact [`place`](Self::place) path.
673 ///
674 /// corner-cut: unlike `place`, this always allocates its crop and rotate
675 /// buffers fresh rather than reusing `self`'s -- the grade path already
676 /// pays the same per-frame cost for a graded clip
677 /// ([`crate::decode::Render::frame`]'s `graded` copy), so a transformed
678 /// clip follows that precedent instead of adding a second steady-state
679 /// buffer budget. Upgrade path if this shows up in a measurement: give
680 /// `Composer` its own crop/rotate scratch fields, sized once like `crop`
681 /// and `scaled` already are.
682 pub fn place_transformed(
683 &mut self,
684 y: &[u8],
685 u: &[u8],
686 v: &[u8],
687 src_w: u32,
688 src_h: u32,
689 t: &TransformParams,
690 ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
691 if t.is_identity() {
692 let (y, u, v, w, h) = self.place(y, u, v, src_w, src_h);
693 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
694 }
695 // A pass-through canvas still has a picture to place a transform on;
696 // treat it as a canvas the exact size of the incoming picture, so a
697 // transformed clip at the project's own resolution still crops,
698 // rotates and moves instead of skipping straight through.
699 let (canvas_w, canvas_h) = if self.width == 0 || self.height == 0 {
700 (src_w, src_h)
701 } else {
702 (self.width, self.height)
703 };
704
705 let crop = crop_rect(src_w, src_h, t);
706 let mut buf1 = (Vec::new(), Vec::new(), Vec::new());
707 let (cy, cu, cv) = if (crop.w, crop.h) == (src_w, src_h) {
708 (y, u, v)
709 } else {
710 crop_i420(&mut buf1, y, u, v, src_w as usize, src_h as usize, crop);
711 (&buf1.0[..], &buf1.1[..], &buf1.2[..])
712 };
713
714 // No rotation is the overwhelmingly common case (a move or a scale,
715 // never a quarter turn); `rotate_i420_90s` always copies its whole
716 // picture even at zero steps, so that copy -- three full-resolution
717 // planes, every decoded frame -- is skipped here rather than paid on
718 // a transform that never rotates. This is the settle-lag fix: it is
719 // what made a plain position/scale edit visibly slower to catch up
720 // to than a colour grade, which never copies the picture at all.
721 let steps = nearest_90_steps(t.rotate);
722 let rot_buf;
723 let (ry, ru, rv, rw, rh) = if steps == 0 {
724 (cy, cu, cv, crop.w, crop.h)
725 } else {
726 rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);
727 (&rot_buf.0[..], &rot_buf.1[..], &rot_buf.2[..], rot_buf.3, rot_buf.4)
728 };
729
730 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy);
731 let (dst, src) = transformed_dst_rect(dst, src, rw, rh, t, canvas_w, canvas_h);
732 let (rw_u, rh_u) = (rw as usize, rh as usize);
733 let mut buf2 = (Vec::new(), Vec::new(), Vec::new());
734 let (fy, fu, fv) = if (src.w, src.h) == (rw, rh) {
735 (ry, ru, rv)
736 } else {
737 crop_i420(&mut buf2, ry, ru, rv, rw_u, rh_u, src);
738 (&buf2.0[..], &buf2.1[..], &buf2.2[..])
739 };
740
741 let (sw, sh) = (src.w as usize, src.h as usize);
742 let (dw, dh) = (dst.w as usize, dst.h as usize);
743 let mut scaled = (Vec::new(), Vec::new(), Vec::new());
744 let (py, pu, pv) = if (sw, sh) == (dw, dh) {
745 (fy, fu, fv)
746 } else {
747 let (ccw, cch) = chroma_dims(dw, dh);
748 scaled.0.resize(dw * dh, 0);
749 scaled.1.resize(ccw * cch, 0);
750 scaled.2.resize(ccw * cch, 0);
751 scale_i420(
752 fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh,
753 );
754 (&scaled.0[..], &scaled.1[..], &scaled.2[..])
755 };
756
757 let (w, h) = (canvas_w as usize, canvas_h as usize);
758 let mut canvas = black_i420(w, h);
759 compose_i420(
760 &mut canvas.0,
761 &mut canvas.1,
762 &mut canvas.2,
763 w,
764 h,
765 py,
766 pu,
767 pv,
768 dst,
769 );
770 (canvas.0, canvas.1, canvas.2, canvas_w, canvas_h)
771 }
772}
773
774/// Per-byte lerp of two same-sized I420 frames: `out = a + (b - a) * t`, on
775/// every plane. `t` is clamped to `[0, 1]` -- a caller ramping across a
776/// cross-dissolve window hands back an in-range fraction already, this is the
777/// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U
778/// with U, V with V); a mismatched pair panics rather than silently
779/// truncating a picture.
780pub fn blend_i420(a: (&[u8], &[u8], &[u8]), b: (&[u8], &[u8], &[u8]), t: f32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
781 let t = t.clamp(0.0, 1.0);
782 let plane = |a: &[u8], b: &[u8]| -> Vec<u8> {
783 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");
784 a.iter()
785 .zip(b)
786 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
787 .collect()
788 };
789 (plane(a.0, b.0), plane(a.1, b.1), plane(a.2, b.2))
790}
791
792/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
793/// across frames is refilled, not reallocated.
794fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
795 plane.clear();
796 plane.resize(len, value);
797}
798
799/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
800/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
801/// crop is exactly half of it.
802fn crop_i420(
803 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
804 y: &[u8],
805 u: &[u8],
806 v: &[u8],
807 src_w: usize,
808 src_h: usize,
809 rect: Rect,
810) {
811 let (w, h) = (rect.w as usize, rect.h as usize);
812 let (x, cy0) = (rect.x as usize, rect.y as usize);
813 let (src_cw, _) = chroma_dims(src_w, src_h);
814 let (cw, ch) = chroma_dims(w, h);
815 let (oy, ou, ov) = out;
816 oy.clear();
817 ou.clear();
818 ov.clear();
819 for row in 0..h {
820 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
821 }
822 let (cx, cy0) = (x / 2, cy0 / 2);
823 for row in 0..ch {
824 let at = (cy0 + row) * src_cw + cx;
825 ou.extend_from_slice(&u[at..][..cw]);
826 ov.extend_from_slice(&v[at..][..cw]);
827 }
828 debug_assert_eq!(oy.len(), w * h);
829 debug_assert_eq!(ou.len(), cw * ch);
830}
831
832#[cfg(test)]
833mod tests {
834 use super::*;
835
836 /// Allocates the destination planes for a size and runs a scale into them.
837 fn scaled(
838 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
839 src_w: usize,
840 src_h: usize,
841 dst_w: usize,
842 dst_h: usize,
843 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
844 let (cw, ch) = chroma_dims(dst_w, dst_h);
845 let mut dst = (
846 vec![0u8; dst_w * dst_h],
847 vec![0u8; cw * ch],
848 vec![0u8; cw * ch],
849 );
850 scale_i420(
851 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
852 );
853 dst
854 }
855
856 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
857 let (cw, ch) = chroma_dims(w, h);
858 (
859 (0..w * h).map(|i| (i % 256) as u8).collect(),
860 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
861 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
862 )
863 }
864
865 /// The pass-through invariant: a project at the media's own resolution must
866 /// hand the decoder's bytes to the encoder unchanged.
867 #[test]
868 fn identity_scale_is_byte_identical() {
869 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
870 let src = gradient(w, h);
871 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
872 }
873 }
874
875 /// Halving is the one case where bilinear is exactly a 2x2 box average:
876 /// the output centre falls on the shared corner of four input samples.
877 /// 0/254 averages to 127 with no rounding slack at all.
878 #[test]
879 fn downscale_by_two_averages_a_checkerboard() {
880 let (w, h) = (32, 24);
881 let (cw, ch) = chroma_dims(w, h);
882 let checker = |i: usize, stride: usize| {
883 if (i / stride + i % stride).is_multiple_of(2) {
884 0u8
885 } else {
886 254
887 }
888 };
889 let src = (
890 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
891 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
892 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
893 );
894 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
895 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
896 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
897 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
898 }
899
900 /// Nothing may leak in from outside a plane: a flat frame stays flat at
901 /// every edge, upscaled and downscaled, odd sizes included.
902 #[test]
903 fn flat_frame_stays_flat() {
904 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
905 for &(sw, sh) in &sizes {
906 let (cw, ch) = chroma_dims(sw, sh);
907 let src = (
908 vec![80u8; sw * sh],
909 vec![90u8; cw * ch],
910 vec![200u8; cw * ch],
911 );
912 for &(dw, dh) in &sizes {
913 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
914 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
915 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
916 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
917 }
918 }
919 }
920
921 /// Chroma alignment: an edge in the U plane must land at the *same* place
922 /// after a 2x upscale, with a symmetric two-sample blend around it and
923 /// untouched flats either side -- a half-sample bias shows up as an
924 /// asymmetric pair here, which is colour bleeding one way.
925 #[test]
926 fn chroma_edge_keeps_its_position() {
927 let (w, h) = (8, 8);
928 let (cw, ch) = chroma_dims(w, h);
929 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
930 let src = (
931 vec![80u8; w * h],
932 (0..cw * ch)
933 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
934 .collect(),
935 vec![128u8; cw * ch],
936 );
937 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
938 let (dcw, _) = chroma_dims(w * 2, h * 2);
939 assert_eq!(dcw, 8);
940 let row = &u[dcw * 3..][..dcw];
941 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
942 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
943 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
944 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
945 // most 1; anything further means the edge moved.
946 assert!(
947 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
948 "blend is off centre, i.e. chroma bled one way: {row:?}"
949 );
950 }
951
952 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
953 /// `(src, dst, policy) -> (placement, crop)`.
954 #[test]
955 fn fit_rect_table() {
956 let r = |x, y, w, h| Rect { x, y, w, h };
957 let cases = [
958 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
959 (
960 (1920, 1080),
961 (640, 480),
962 FitPolicy::Fit,
963 r(0, 60, 640, 360),
964 r(0, 0, 1920, 1080),
965 ),
966 // ...and the same pair filled: the canvas is whole, the source is
967 // cropped to 4:3 (1440 wide) about its centre.
968 (
969 (1920, 1080),
970 (640, 480),
971 FitPolicy::Fill,
972 r(0, 0, 640, 480),
973 r(240, 0, 1440, 1080),
974 ),
975 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
976 (
977 (640, 480),
978 (1920, 1080),
979 FitPolicy::Fit,
980 r(240, 0, 1440, 1080),
981 r(0, 0, 640, 480),
982 ),
983 (
984 (640, 480),
985 (1920, 1080),
986 FitPolicy::Fill,
987 r(0, 0, 1920, 1080),
988 r(0, 60, 640, 360),
989 ),
990 // Stretch ignores aspect entirely, both ways.
991 (
992 (1920, 1080),
993 (640, 480),
994 FitPolicy::Stretch,
995 r(0, 0, 640, 480),
996 r(0, 0, 1920, 1080),
997 ),
998 // 1:1 with a bigger source: cropped both ways, centred.
999 (
1000 (1920, 1080),
1001 (640, 480),
1002 FitPolicy::Center,
1003 r(0, 0, 640, 480),
1004 r(640, 300, 640, 480),
1005 ),
1006 // 1:1 with a smaller source: padded both ways, centred.
1007 (
1008 (640, 480),
1009 (1920, 1080),
1010 FitPolicy::Center,
1011 r(640, 300, 640, 480),
1012 r(0, 0, 640, 480),
1013 ),
1014 // Odd sizes: offsets even, sizes even unless they reach the edge.
1015 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
1016 (
1017 (7, 5),
1018 (13, 9),
1019 FitPolicy::Fit,
1020 r(0, 0, 13, 9),
1021 r(0, 0, 7, 5),
1022 ),
1023 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
1024 // offset without putting chroma half a sample off, so the last one
1025 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
1026 (
1027 (9, 9),
1028 (13, 9),
1029 FitPolicy::Center,
1030 r(2, 0, 8, 9),
1031 r(0, 0, 8, 9),
1032 ),
1033 (
1034 (13, 9),
1035 (9, 9),
1036 FitPolicy::Center,
1037 r(0, 0, 8, 9),
1038 r(2, 0, 8, 9),
1039 ),
1040 ];
1041 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
1042 let got = fit_rect(sw, sh, dw, dh, policy);
1043 assert_eq!(
1044 got,
1045 (want_dst, want_src),
1046 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
1047 );
1048 }
1049 // Degenerate input is empty, not a panic.
1050 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
1051 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
1052 }
1053
1054 /// Every rect a policy hands back must sit inside its plane, start on the
1055 /// chroma grid, and end on it or at the plane edge -- the invariant
1056 /// `compose_i420` relies on.
1057 #[test]
1058 fn fit_rect_stays_on_the_chroma_grid() {
1059 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
1060 for policy in [
1061 FitPolicy::Fit,
1062 FitPolicy::Fill,
1063 FitPolicy::Stretch,
1064 FitPolicy::Center,
1065 ] {
1066 for &sw in &sizes {
1067 for &dh in &sizes {
1068 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
1069 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
1070 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
1071 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
1072 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
1073 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
1074 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
1075 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
1076 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
1077 // A plane one sample wide or high has no chroma grid to
1078 // be on: `Center` from a 2-high source onto a 1-high
1079 // canvas is one row, and no size satisfies both edges.
1080 // Nothing real is that shape; it must merely not
1081 // escape its plane, which the two asserts above cover.
1082 if grid {
1083 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
1084 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
1085 }
1086 assert!(!rect.is_empty(), "{ctx} empty");
1087 }
1088 }
1089 }
1090 }
1091 }
1092
1093 #[test]
1094 fn compose_fills_the_rect_and_nothing_else() {
1095 let (cw2, ch2) = (640usize, 360usize);
1096 let (canvas_w, canvas_h) = (640usize, 480usize);
1097 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
1098 let (fcw, fch) = chroma_dims(cw2, ch2);
1099 let frame = (
1100 vec![200u8; cw2 * ch2],
1101 vec![70u8; fcw * fch],
1102 vec![30u8; fcw * fch],
1103 );
1104 let rect = Rect {
1105 x: 0,
1106 y: 60,
1107 w: cw2 as u32,
1108 h: ch2 as u32,
1109 };
1110 compose_i420(
1111 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
1112 );
1113
1114 for row in 0..canvas_h {
1115 let inside = (60..420).contains(&row);
1116 let want = if inside { 200 } else { BLACK_Y };
1117 assert!(
1118 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
1119 "luma row {row}"
1120 );
1121 }
1122 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
1123 for row in 0..cch {
1124 let inside = (30..210).contains(&row);
1125 let (wu, wv) = if inside {
1126 (70, 30)
1127 } else {
1128 (NEUTRAL_C, NEUTRAL_C)
1129 };
1130 assert!(
1131 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
1132 "U row {row}"
1133 );
1134 assert!(
1135 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
1136 "V row {row}"
1137 );
1138 }
1139 }
1140
1141 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
1142 /// is public and a caller may compute a rect itself.
1143 #[test]
1144 fn compose_clips_a_rect_that_runs_off_the_canvas() {
1145 let (mut y, mut u, mut v) = black_i420(16, 16);
1146 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
1147 let rect = Rect {
1148 x: 12,
1149 y: 12,
1150 w: 8,
1151 h: 8,
1152 };
1153 compose_i420(
1154 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
1155 );
1156 assert_eq!(y[15 * 16 + 15], 99);
1157 assert_eq!(y[11 * 16 + 15], BLACK_Y);
1158 // Wholly outside: no write at all.
1159 let before = y.clone();
1160 compose_i420(
1161 &mut y,
1162 &mut u,
1163 &mut v,
1164 16,
1165 16,
1166 &frame.0,
1167 &frame.1,
1168 &frame.2,
1169 Rect {
1170 x: 100,
1171 y: 0,
1172 w: 8,
1173 h: 8,
1174 },
1175 );
1176 assert_eq!(y, before);
1177 }
1178
1179 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
1180 /// project canvas, letterbox bars intact.
1181 #[test]
1182 fn fit_scale_compose_letterboxes() {
1183 let (sw, sh) = (640usize, 480usize);
1184 let (dw, dh) = (1920usize, 1080usize);
1185 let src = gradient(sw, sh);
1186 let (dst_rect, src_rect) =
1187 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
1188 assert_eq!(
1189 src_rect,
1190 Rect {
1191 x: 0,
1192 y: 0,
1193 w: 640,
1194 h: 480
1195 }
1196 );
1197 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
1198 let picture = scaled(&src, sw, sh, rw, rh);
1199 let (mut y, mut u, mut v) = black_i420(dw, dh);
1200 compose_i420(
1201 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
1202 );
1203 // Pillarbox columns stay black, the picture area does not.
1204 let mid = (dh / 2) * dw;
1205 assert!(
1206 y[mid..mid + dst_rect.x as usize]
1207 .iter()
1208 .all(|&s| s == BLACK_Y)
1209 );
1210 assert_eq!(
1211 y[mid + dst_rect.x as usize..][..rw],
1212 picture.0[(rh / 2) * rw..][..rw]
1213 );
1214 }
1215
1216 /// The wiring invariant: a project at its media's own resolution hands the
1217 /// decoder's own slices back, not a copy that happens to be equal. Asserted
1218 /// on the pointer, because "identical bytes" is cheap and "no work at all"
1219 /// is what the common case is promised.
1220 #[test]
1221 fn a_canvas_of_the_source_size_is_a_pass_through() {
1222 let (w, h) = (64usize, 48usize);
1223 let src = gradient(w, h);
1224 for mut canvas in [
1225 Composer::new(w as u32, h as u32, FitPolicy::Fit),
1226 Composer::new(w as u32, h as u32, FitPolicy::Fill),
1227 Composer::new(w as u32, h as u32, FitPolicy::Center),
1228 Composer::passthrough(),
1229 ] {
1230 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
1231 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
1232 assert_eq!(u.as_ptr(), src.1.as_ptr());
1233 assert_eq!(v.as_ptr(), src.2.as_ptr());
1234 assert_eq!((cw, ch), (w as u32, h as u32));
1235 }
1236 }
1237
1238 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
1239 /// the pillarbox columns are limited-range black, exactly -- a bar that is
1240 /// merely dark is a bar the grade reached.
1241 #[test]
1242 fn fit_pillarboxes_with_exact_black_bars() {
1243 let (sw, sh) = (640u32, 480u32);
1244 let (dw, dh) = (1920u32, 1080u32);
1245 let src = (
1246 vec![200u8; (sw * sh) as usize],
1247 vec![70u8; (sw * sh / 4) as usize],
1248 vec![30u8; (sw * sh / 4) as usize],
1249 );
1250 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
1251 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1252 assert_eq!((w, h), (dw, dh));
1253 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
1254 assert_eq!(
1255 rect,
1256 Rect {
1257 x: 240,
1258 y: 0,
1259 w: 1440,
1260 h: 1080
1261 },
1262 "geometry moved"
1263 );
1264 let (w, h) = (w as usize, h as usize);
1265 let row = &y[(h / 2) * w..][..w];
1266 let x = rect.x as usize;
1267 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
1268 assert!(
1269 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
1270 "right bar not black"
1271 );
1272 assert!(
1273 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
1274 "picture"
1275 );
1276 // ...and the bars are neutral in chroma too, or they would be a colour.
1277 let (cw, _) = chroma_dims(w, h);
1278 let crow = &u[(h / 4) * cw..][..cw];
1279 assert!(
1280 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
1281 "bar has colour"
1282 );
1283 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
1284 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
1285 }
1286
1287 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
1288 /// the canvas (no bar anywhere), `Center` pads without resampling.
1289 #[test]
1290 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
1291 let (sw, sh) = (640u32, 480u32);
1292 let (dw, dh) = (1920u32, 1080u32);
1293 let src = (
1294 vec![200u8; (sw * sh) as usize],
1295 vec![70u8; (sw * sh / 4) as usize],
1296 vec![30u8; (sw * sh / 4) as usize],
1297 );
1298 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
1299 let mut canvas = Composer::new(dw, dh, policy);
1300 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1301 assert!(
1302 y.iter().all(|&s| s == 200),
1303 "{policy:?} left a bar: the canvas is not covered"
1304 );
1305 }
1306 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1307 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1308 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1309 assert_eq!(rect.w, sw, "Center resampled the picture");
1310 let (w, h) = (w as usize, h as usize);
1311 let row = &y[(h / 2) * w..][..w];
1312 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1313 assert!(
1314 row[rect.x as usize..][..sw as usize]
1315 .iter()
1316 .all(|&s| s == 200)
1317 );
1318 }
1319
1320 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1321 /// picture, chroma with it: a marked band at a known column has to come out
1322 /// at the column the geometry puts it at.
1323 #[test]
1324 fn fill_crops_about_the_centre() {
1325 let (sw, sh) = (32usize, 8usize);
1326 let (dw, dh) = (8u32, 8u32);
1327 // Column 16 (the centre) is bright, everything else is dark.
1328 let y: Vec<u8> = (0..sw * sh)
1329 .map(|i| if i % sw == 16 { 240 } else { 40 })
1330 .collect();
1331 let (cw, ch) = chroma_dims(sw, sh);
1332 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1333 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1334 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1335 assert_eq!((w, h), (dw, dh));
1336 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1337 assert_eq!(
1338 dst,
1339 Rect {
1340 x: 0,
1341 y: 0,
1342 w: 8,
1343 h: 8
1344 },
1345 "Fill must cover"
1346 );
1347 assert_eq!(
1348 crop,
1349 Rect {
1350 x: 12,
1351 y: 0,
1352 w: 8,
1353 h: 8
1354 },
1355 "crop off centre"
1356 );
1357 // The bright column is crop-relative column 4 of 8, untouched by the
1358 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1359 let row = &y[..8];
1360 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1361 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1362 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1363 }
1364
1365 /// Not asserted: only the release number means anything. Run with
1366 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1367 #[test]
1368 fn perf_720p_to_1080p() {
1369 let src = gradient(1280, 720);
1370 let (cw, ch) = chroma_dims(1920, 1080);
1371 let mut dst = (
1372 vec![0u8; 1920 * 1080],
1373 vec![0u8; cw * ch],
1374 vec![0u8; cw * ch],
1375 );
1376 let runs = 30;
1377 let t = std::time::Instant::now();
1378 for _ in 0..runs {
1379 scale_i420(
1380 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1381 );
1382 }
1383 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1384 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1385 }
1386
1387 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1388 /// scale and blit -- which is what the playback budget has to hold. Printed,
1389 /// not asserted, like every other perf test here.
1390 #[test]
1391 fn perf_compose_720p_onto_1080p() {
1392 let src = gradient(1280, 720);
1393 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1394 let runs = 30;
1395 let t = std::time::Instant::now();
1396 for _ in 0..runs {
1397 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1398 }
1399 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1400 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1401 }
1402
1403 /// [`blend_i420`] at the midpoint of two solid-colour frames lands exactly
1404 /// on the 50/50 average, on every plane -- the synthetic stand-in for "the
1405 /// dissolve's midpoint frame looks like the average colour" the export
1406 /// path is built on.
1407 #[test]
1408 fn blend_i420_is_50_50_at_the_midpoint() {
1409 let a = (vec![0u8; 16], vec![10u8; 4], vec![20u8; 4]);
1410 let b = (vec![100u8; 16], vec![50u8; 4], vec![120u8; 4]);
1411 let (y, u, v) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.5);
1412 assert!(y.iter().all(|&p| p == 50), "Y midpoint: {y:?}");
1413 assert!(u.iter().all(|&p| p == 30), "U midpoint: {u:?}");
1414 assert!(v.iter().all(|&p| p == 70), "V midpoint: {v:?}");
1415 // The edges hand back each frame untouched.
1416 let (y0, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.0);
1417 assert_eq!(y0, a.0);
1418 let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0);
1419 assert_eq!(y1, b.0);
1420 }
1421
1422 /// The crop fractions cut a rect out of a 100x100 source at the very
1423 /// pixels the maths says, chroma-grid aligned like every other rect here.
1424 #[test]
1425 fn crop_rect_math() {
1426 let t = TransformParams {
1427 crop_l: 0.1,
1428 crop_r: 0.2,
1429 crop_t: 0.0,
1430 crop_b: 0.0,
1431 ..Default::default()
1432 };
1433 assert_eq!(
1434 crop_rect(100, 100, &t),
1435 Rect { x: 10, y: 0, w: 70, h: 100 },
1436 "10% off the left, 20% off the right, nothing off top or bottom"
1437 );
1438 // Opposing crops clamp to 0.5 a side rather than meeting or crossing.
1439 let extreme = TransformParams {
1440 crop_l: 0.9,
1441 crop_r: 0.9,
1442 ..Default::default()
1443 };
1444 let r = crop_rect(100, 100, &extreme);
1445 assert!(r.w >= 2, "the smallest surviving rect is one chroma sample");
1446 // A zero-sized source has nothing to crop.
1447 assert_eq!(crop_rect(0, 100, &TransformParams::default()), Rect { x: 0, y: 0, w: 0, h: 0 });
1448 }
1449
1450 /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own
1451 /// centre) and resized by `scale`, both about that same centre. Neither
1452 /// case here clips, so the source rect comes back untouched.
1453 #[test]
1454 fn transformed_dst_rect_at_pos_and_scale() {
1455 let dst = Rect { x: 0, y: 0, w: 100, h: 100 };
1456 let src = Rect { x: 0, y: 0, w: 100, h: 100 };
1457 // Moved a quarter of the canvas to the right, untouched vertically.
1458 let moved = TransformParams {
1459 pos_x: 0.25,
1460 ..Default::default()
1461 };
1462 assert_eq!(
1463 transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200),
1464 (Rect { x: 50, y: 0, w: 100, h: 100 }, src),
1465 "25% of a 200-wide canvas is 50 pixels, about the placement's own centre"
1466 );
1467 // Doubled in place, box already centred on the canvas: the centre
1468 // stays, the box fills the canvas, nothing clips.
1469 let centred_dst = Rect { x: 50, y: 50, w: 100, h: 100 };
1470 let grown = TransformParams {
1471 scale: 2.0,
1472 ..Default::default()
1473 };
1474 assert_eq!(
1475 transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200),
1476 (Rect { x: 0, y: 0, w: 200, h: 200 }, src),
1477 "a 100x100 box doubled about its own centre on a 200x200 canvas fills it"
1478 );
1479 }
1480
1481 /// The defect this replaces: a positive offset used to SHRINK the dst
1482 /// rect (squeezing the whole source into what remained) and a negative
1483 /// offset used to render pixel-identical to the identity (the clamp at 0
1484 /// killed it). Real translation keeps the box's size and clips instead:
1485 /// the src rect trims by the same fraction that fell off-canvas, on the
1486 /// side that fell off, and the surviving box size never shrinks below
1487 /// what `scale` alone gives it.
1488 #[test]
1489 fn transformed_dst_rect_clips_instead_of_squeezing() {
1490 let dst = Rect { x: 0, y: 0, w: 100, h: 100 };
1491 let src = Rect { x: 0, y: 0, w: 100, h: 100 };
1492 // +30% of a 100-wide canvas: the box moves 30px right, half of it
1493 // (50px) falls off the right edge -- half the source is trimmed off
1494 // its right, not the whole source squeezed into 70px.
1495 let pos = TransformParams { pos_x: 0.30, ..Default::default() };
1496 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100);
1497 assert_eq!(d, Rect { x: 30, y: 0, w: 70, h: 100 }, "dst size must not shrink below what clipping removes");
1498 assert_eq!(s, Rect { x: 0, y: 0, w: 70, h: 100 }, "src trims off its right, does not squeeze");
1499
1500 // -30%: symmetric on the left, and no longer identical to identity.
1501 let neg = TransformParams { pos_x: -0.30, ..Default::default() };
1502 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100);
1503 assert_eq!(d, Rect { x: 0, y: 0, w: 70, h: 100 });
1504 assert_eq!(s, Rect { x: 30, y: 0, w: 70, h: 100 }, "src trims off its left");
1505 assert_ne!((d, s), (dst, src), "a negative offset must move the picture, not no-op");
1506
1507 // Fully off canvas: both rects empty.
1508 let gone = TransformParams { pos_x: 2.0, ..Default::default() };
1509 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100);
1510 assert!(d.is_empty() && s.is_empty(), "wholly off-canvas has nothing to draw");
1511 }
1512
1513 /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a
1514 /// non-finite value to the identity.
1515 #[test]
1516 fn nearest_90_steps_rounds_and_wraps() {
1517 assert_eq!(nearest_90_steps(0.0), 0);
1518 assert_eq!(nearest_90_steps(89.0), 1);
1519 assert_eq!(nearest_90_steps(91.0), 1);
1520 assert_eq!(nearest_90_steps(180.0), 2);
1521 assert_eq!(nearest_90_steps(-90.0), 3);
1522 assert_eq!(nearest_90_steps(360.0 + 90.0), 1);
1523 assert_eq!(nearest_90_steps(f32::NAN), 0);
1524 }
1525
1526 /// A marked corner pixel lands where a clockwise quarter turn puts it:
1527 /// top-left to top-right at 90 degrees, to bottom-right at 180, to
1528 /// bottom-left at 270 -- and the plane's own shape swaps at 90 and 270
1529 /// and stays put at 180.
1530 #[test]
1531 fn rotate_i420_90s_places_a_marked_pixel() {
1532 let (w, h) = (4usize, 3usize);
1533 let mut y = vec![0u8; w * h];
1534 y[0] = 99; // (x=0, y=0), the top-left corner.
1535 let (u, v) = (vec![128u8; 2 * 2], vec![128u8; 2 * 2]);
1536
1537 let mark_at = |plane: &[u8], w: u32, x: u32, y: u32| plane[(y * w + x) as usize];
1538
1539 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1);
1540 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees");
1541 assert_eq!(mark_at(&ry, rw, rw - 1, 0), 99, "top-left moves to top-right");
1542
1543 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2);
1544 assert_eq!((rw, rh), (w as u32, h as u32), "dims stay put at 180 degrees");
1545 assert_eq!(
1546 mark_at(&ry, rw, rw - 1, rh - 1),
1547 99,
1548 "top-left moves to bottom-right"
1549 );
1550
1551 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 3);
1552 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 270 degrees");
1553 assert_eq!(
1554 mark_at(&ry, rw, 0, rh - 1),
1555 99,
1556 "top-left moves to bottom-left"
1557 );
1558
1559 // Zero steps, and four of them, are both the identity.
1560 let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0);
1561 assert_eq!((ry, ru, rv, rw, rh), (y.clone(), u.clone(), v.clone(), w as u32, h as u32));
1562 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4);
1563 assert_eq!((ry, rw, rh), (y, w as u32, h as u32), "four quarter turns is the identity");
1564 }
1565
1566 /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..64
1567 /// are 40. A vertical edge to track through a horizontal move.
1568 fn vsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1569 let y = (0..64 * 64).map(|i| if i % 64 < 32 { 200u8 } else { 40u8 }).collect();
1570 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1571 }
1572
1573 /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge
1574 /// to track through a vertical move.
1575 fn hsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1576 let y = (0..64 * 64).map(|i| if i / 64 < 32 { 200u8 } else { 40u8 }).collect();
1577 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1578 }
1579
1580 /// [`Composer::place_transformed`] at compose level, with the exact
1581 /// defect the geometry used to have: a positive `pos_x` squeezed the
1582 /// whole source into a shrunk box (content narrower, not just displaced)
1583 /// and a negative one rendered pixel-identical to the identity. These
1584 /// assert on the DISPLACED CONTENT (where the source's own edge lands),
1585 /// not on any rect field, so a squeeze that happens to leave rect sizes
1586 /// looking plausible cannot pass silently.
1587 #[test]
1588 fn place_transformed_displaces_content_not_just_a_rect() {
1589 let (src_w, src_h) = (64u32, 64u32);
1590 let (y, u, v) = vsplit_64();
1591 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1592
1593 // Identity: the source's own edge stays at column 32, everywhere.
1594 let (iy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default());
1595 for row in 0..64 {
1596 let r = &iy[row * 64..][..64];
1597 assert!(r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40), "row {row}: {r:?}");
1598 }
1599
1600 // +25%: the box moves right by 16 and does NOT shrink -- content
1601 // width stays 64 (the source's own 32/32 split), clipped to what
1602 // still fits. The edge (originally at box-column 32) now sits at
1603 // canvas column 16 + 32 = 48, not squeezed inward.
1604 let plus = TransformParams { pos_x: 0.25, ..Default::default() };
1605 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1606 for row in 0..64 {
1607 let r = &py[row * 64..][..64];
1608 assert!(r[..16].iter().all(|&p| p == BLACK_Y), "row {row} left of box: {r:?}");
1609 assert!(r[16..48].iter().all(|&p| p == 200), "row {row} squeezed inward: {r:?}");
1610 assert!(r[48..].iter().all(|&p| p == 40), "row {row} edge moved: {r:?}");
1611 }
1612
1613 // -25%: mirror image -- this used to be pixel-identical to identity.
1614 let minus = TransformParams { pos_x: -0.25, ..Default::default() };
1615 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1616 assert_ne!(ny, iy, "a negative offset must move the picture, not no-op");
1617 for row in 0..64 {
1618 let r = &ny[row * 64..][..64];
1619 assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}");
1620 assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}");
1621 assert!(r[48..].iter().all(|&p| p == BLACK_Y), "row {row} right of box: {r:?}");
1622 }
1623
1624 // Wholly off-canvas: nothing to draw, all black.
1625 let gone = TransformParams { pos_x: 2.0, ..Default::default() };
1626 let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone);
1627 assert!(gy.iter().all(|&p| p == BLACK_Y), "off-canvas must render background");
1628 }
1629
1630 /// The same defect on the vertical axis: `pos_y` moves content up/down,
1631 /// clipped, never squeezed.
1632 #[test]
1633 fn place_transformed_displaces_content_vertically() {
1634 let (src_w, src_h) = (64u32, 64u32);
1635 let (y, u, v) = hsplit_64();
1636 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1637
1638 let plus = TransformParams { pos_y: 0.25, ..Default::default() };
1639 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1640 for row in 0..16 {
1641 assert!(py[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} above the box");
1642 }
1643 for row in 16..48 {
1644 assert!(py[row * 64..][..64].iter().all(|&p| p == 200), "row {row} squeezed: {:?}", &py[row * 64..][..4]);
1645 }
1646 for row in 48..64 {
1647 assert!(py[row * 64..][..64].iter().all(|&p| p == 40), "row {row} edge moved");
1648 }
1649
1650 let minus = TransformParams { pos_y: -0.25, ..Default::default() };
1651 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1652 for row in 0..16 {
1653 assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}");
1654 }
1655 for row in 16..48 {
1656 assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}");
1657 }
1658 for row in 48..64 {
1659 assert!(ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} below the box");
1660 }
1661 }
1662
1663 /// Position and scale together: a halved box moved right must place its
1664 /// (also halved) content at the moved-and-scaled location, not squeeze
1665 /// the full source into whatever survived clamping.
1666 #[test]
1667 fn place_transformed_displaces_content_with_scale() {
1668 let (src_w, src_h) = (64u32, 64u32);
1669 let (y, u, v) = vsplit_64();
1670 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1671 // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16),
1672 // fully on-canvas. The source's column-32 edge, halved, sits at
1673 // box-local column 16, i.e. canvas column 32 + 16 = 48.
1674 let t = TransformParams { scale: 0.5, pos_x: 0.25, ..Default::default() };
1675 let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t);
1676 for row in 0..64 {
1677 let r = &sy[row * 64..][..64];
1678 let inside = (16..48).contains(&row);
1679 let want_bg = if inside { r[0] } else { BLACK_Y };
1680 assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}");
1681 if inside {
1682 assert!(r[40].abs_diff(200) <= 1, "row {row} col 40 should be the left half: {r:?}");
1683 assert!(r[56].abs_diff(40) <= 1, "row {row} col 56 should be the right half: {r:?}");
1684 }
1685 }
1686 }
1687}