forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

scale.rs1721 lines, 70.2 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 mut out = (Vec::new(), Vec::new(), Vec::new());
463 let (rw, rh) = rotate_i420_90s_into(y, u, v, w, h, steps, &mut out);
464 (out.0, out.1, out.2, rw, rh)
465}
466
467/// [`rotate_i420_90s`] into a caller's own buffers: the top-left of a phone
468/// file's display matrix has to be made on **every decoded frame**, so the
469/// three plane allocations are a steady-state cost to pay once rather than a
470/// per-frame one. The output is exactly what the allocating form returns; the
471/// scratch tuple is resized and refilled, never appended to.
472pub fn rotate_i420_90s_into(
473 y: &[u8],
474 u: &[u8],
475 v: &[u8],
476 w: u32,
477 h: u32,
478 steps: u8,
479 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
480) -> (u32, u32) {
481 let steps = steps % 4;
482 if steps == 0 || w == 0 || h == 0 {
483 out.0.clear();
484 out.0.extend_from_slice(y);
485 out.1.clear();
486 out.1.extend_from_slice(u);
487 out.2.clear();
488 out.2.extend_from_slice(v);
489 return (w, h);
490 }
491 let (cw, ch) = chroma_dims(w as usize, h as usize);
492 rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0);
493 rotate_plane_into(u, cw, ch, steps, &mut out.1);
494 rotate_plane_into(v, cw, ch, steps, &mut out.2);
495 if steps == 2 {
496 (w, h)
497 } else {
498 (h, w)
499 }
500}
501
502/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise,
503/// written into `out` -- resized to the turned size, which is the source's
504/// swapped at 90 and 270 and its own at 180.
505fn rotate_plane_into(src: &[u8], w: usize, h: usize, steps: u8, out: &mut Vec<u8>) {
506 match steps {
507 1 => {
508 out.resize(h * w, 0);
509 for yp in 0..w {
510 for xp in 0..h {
511 out[yp * h + xp] = src[(h - 1 - xp) * w + yp];
512 }
513 }
514 }
515 2 => {
516 out.resize(w * h, 0);
517 for yp in 0..h {
518 for xp in 0..w {
519 out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)];
520 }
521 }
522 }
523 3 => {
524 out.resize(h * w, 0);
525 for yp in 0..w {
526 for xp in 0..h {
527 out[yp * h + xp] = src[xp * w + (w - 1 - yp)];
528 }
529 }
530 }
531 _ => unreachable!("steps % 4 is 1, 2 or 3 here"),
532 }
533}
534
535/// One clip's pictures placed on the project canvas: the geometry, plus the
536/// buffers it composes into so a frame costs no allocation.
537///
538/// This is the *one* definition of what a mixed-resolution timeline looks like:
539/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
540/// decoded planes to [`place`](Composer::place), so what is watched and what is
541/// written cannot drift apart.
542///
543/// **Order against the colour grade: grade first, place second.** A grade
544/// belongs to the clip's own pixels -- it is graded at the resolution it was
545/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
546/// letterbox bars are *not* the clip: a brightness grade that reached them would
547/// lift the black frame around the picture. Callers therefore grade the source
548/// planes and place the result; the bars stay exactly [`black_i420`].
549///
550/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of
551/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a
552/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at
553/// 4096x2160 (the floor), all measured. A worker holds one more than this in its
554/// hand, so a burst off a full queue is `queue_depth + 1`.
555///
556/// The floor of 2 is the bound this engine ran on everywhere before there was
557/// any decode-ahead; the ceiling keeps a small picture from queueing a second of
558/// video the consumer would have to walk through after a seek.
559pub(crate) fn queue_depth(width: u32, height: u32) -> usize {
560 const BUDGET: usize = 96 << 20;
561 let bytes = width as usize * height as usize * 4;
562 if bytes == 0 {
563 return 2;
564 }
565 (BUDGET / bytes).clamp(2, 16)
566}
567
568/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
569/// hands the caller's own planes straight back, allocates nothing and touches no
570/// byte, which is what keeps a project at its media's resolution the byte-for-byte
571/// path it was before there was a project resolution at all.
572///
573/// [`place`]: Composer::place
574pub struct Composer {
575 width: u32,
576 height: u32,
577 policy: FitPolicy,
578 /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
579 /// `Center` ever crop, so this stays empty for a letterboxed project.
580 crop: (Vec<u8>, Vec<u8>, Vec<u8>),
581 /// The crop resampled to the placement rect.
582 scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
583 /// The canvas itself, refilled with black every frame -- a memset against a
584 /// decode, and the only way a policy change cannot leave last frame's bars
585 /// showing through.
586 canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
587}
588
589impl Composer {
590 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
591 let empty = || (Vec::new(), Vec::new(), Vec::new());
592 Self {
593 width,
594 height,
595 policy,
596 crop: empty(),
597 scaled: empty(),
598 canvas: empty(),
599 }
600 }
601
602 /// A composer that places nothing: every picture passes through at its own
603 /// size. What the file-level decode API opens with, where there is no
604 /// project and therefore no canvas.
605 pub fn passthrough() -> Self {
606 Self::new(0, 0, FitPolicy::Fit)
607 }
608
609 /// Whether this canvas is the one that places nothing
610 /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand,
611 /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that
612 /// needs it is sizing a queue before anything has been decoded.
613 pub(crate) fn places_nothing(&self) -> bool {
614 self.width == 0 || self.height == 0
615 }
616
617 /// The canvas this composer places onto, for the painter that fills it
618 /// directly at this size -- a picture authored at the canvas's own
619 /// dimensions takes the pass-through path [`is_passthrough`](Self::is_passthrough)
620 /// answers for, and it needs the numbers before there is a picture.
621 pub(crate) fn dims(&self) -> (u32, u32) {
622 (self.width, self.height)
623 }
624
625 /// How many decoded pictures a worker over this canvas may keep ahead of
626 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
627 /// than a 1080p one instead of the same number of far bigger frames.
628 ///
629 /// A **pass-through** canvas has no size of its own -- the pictures come out
630 /// at the source's -- so it cannot answer, and the caller that knows the
631 /// stream asks [`queue_depth`] with those dimensions instead. Answering 2
632 /// here would be the pre-decode-ahead bound, which is exactly the bug this
633 /// pair exists to keep out of the file-open path.
634 pub(crate) fn queue_depth(&self) -> usize {
635 queue_depth(self.width, self.height)
636 }
637
638 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
639 /// composer would hand it back untouched. What lets a caller keep a fused
640 /// fast path (the graded conversion) for the common case.
641 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
642 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
643 }
644
645 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
646 /// caller's own planes (pass-through) or the canvas with the fitted picture
647 /// composed onto it. The dimensions come back because those two differ.
648 ///
649 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
650 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
651 pub fn place<'a>(
652 &'a mut self,
653 y: &'a [u8],
654 u: &'a [u8],
655 v: &'a [u8],
656 src_w: u32,
657 src_h: u32,
658 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
659 if self.is_passthrough(src_w, src_h) {
660 return (y, u, v, src_w, src_h);
661 }
662 let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
663 let (sw, sh) = (src_w as usize, src_h as usize);
664
665 // Crop first, so the scaler only ever sees a tightly packed plane. Fit
666 // and Stretch never crop, which is the whole cost of the common case.
667 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
668 (y, u, v)
669 } else {
670 crop_i420(&mut self.crop, y, u, v, sw, sh, src);
671 (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
672 };
673 // ...then resample it to the placement, unless it already is that size
674 // (`Center` never resamples, and neither does an exact-fit upscale).
675 let (cw, ch) = (src.w as usize, src.h as usize);
676 let (dw, dh) = (dst.w as usize, dst.h as usize);
677 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
678 (src_y, src_u, src_v)
679 } else {
680 let (ccw, cch) = chroma_dims(dw, dh);
681 let (sy, su, sv) = &mut self.scaled;
682 sy.resize(dw * dh, 0);
683 su.resize(ccw * cch, 0);
684 sv.resize(ccw * cch, 0);
685 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
686 (&sy[..], &su[..], &sv[..])
687 };
688
689 let (w, h) = (self.width as usize, self.height as usize);
690 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
691 let (ky, ku, kv) = &mut self.canvas;
692 fill(ky, w * h, BLACK_Y);
693 fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
694 fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
695 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
696 (ky, ku, kv, self.width, self.height)
697 }
698
699 /// [`place`](Self::place) with a per-clip [`TransformParams`] applied on
700 /// top of the fit policy: the source is cropped to [`crop_rect`], rotated
701 /// by [`rotate_i420_90s`] to [`nearest_90_steps`] of `t.rotate`, fit to the
702 /// canvas exactly as an untransformed picture is, and the fitted
703 /// placement is then moved/resized/clipped by [`transformed_dst_rect`],
704 /// which also trims the matching slice off the source rect so an
705 /// off-canvas move clips instead of squeezing.
706 /// `t.is_identity()` takes the exact [`place`](Self::place) path.
707 ///
708 /// corner-cut: unlike `place`, this always allocates its crop and rotate
709 /// buffers fresh rather than reusing `self`'s -- the grade path already
710 /// pays the same per-frame cost for a graded clip
711 /// ([`crate::decode::Render::frame`]'s `graded` copy), so a transformed
712 /// clip follows that precedent instead of adding a second steady-state
713 /// buffer budget. Upgrade path if this shows up in a measurement: give
714 /// `Composer` its own crop/rotate scratch fields, sized once like `crop`
715 /// and `scaled` already are.
716 pub fn place_transformed(
717 &mut self,
718 y: &[u8],
719 u: &[u8],
720 v: &[u8],
721 src_w: u32,
722 src_h: u32,
723 t: &TransformParams,
724 ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
725 if t.is_identity() {
726 let (y, u, v, w, h) = self.place(y, u, v, src_w, src_h);
727 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
728 }
729 // A pass-through canvas still has a picture to place a transform on;
730 // treat it as a canvas the exact size of the incoming picture, so a
731 // transformed clip at the project's own resolution still crops,
732 // rotates and moves instead of skipping straight through.
733 let (canvas_w, canvas_h) = if self.width == 0 || self.height == 0 {
734 (src_w, src_h)
735 } else {
736 (self.width, self.height)
737 };
738
739 let crop = crop_rect(src_w, src_h, t);
740 let mut buf1 = (Vec::new(), Vec::new(), Vec::new());
741 let (cy, cu, cv) = if (crop.w, crop.h) == (src_w, src_h) {
742 (y, u, v)
743 } else {
744 crop_i420(&mut buf1, y, u, v, src_w as usize, src_h as usize, crop);
745 (&buf1.0[..], &buf1.1[..], &buf1.2[..])
746 };
747
748 // No rotation is the overwhelmingly common case (a move or a scale,
749 // never a quarter turn); `rotate_i420_90s` always copies its whole
750 // picture even at zero steps, so that copy -- three full-resolution
751 // planes, every decoded frame -- is skipped here rather than paid on
752 // a transform that never rotates. This is the settle-lag fix: it is
753 // what made a plain position/scale edit visibly slower to catch up
754 // to than a colour grade, which never copies the picture at all.
755 let steps = nearest_90_steps(t.rotate);
756 let rot_buf;
757 let (ry, ru, rv, rw, rh) = if steps == 0 {
758 (cy, cu, cv, crop.w, crop.h)
759 } else {
760 rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);
761 (&rot_buf.0[..], &rot_buf.1[..], &rot_buf.2[..], rot_buf.3, rot_buf.4)
762 };
763
764 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy);
765 let (dst, src) = transformed_dst_rect(dst, src, rw, rh, t, canvas_w, canvas_h);
766 let (rw_u, rh_u) = (rw as usize, rh as usize);
767 let mut buf2 = (Vec::new(), Vec::new(), Vec::new());
768 let (fy, fu, fv) = if (src.w, src.h) == (rw, rh) {
769 (ry, ru, rv)
770 } else {
771 crop_i420(&mut buf2, ry, ru, rv, rw_u, rh_u, src);
772 (&buf2.0[..], &buf2.1[..], &buf2.2[..])
773 };
774
775 let (sw, sh) = (src.w as usize, src.h as usize);
776 let (dw, dh) = (dst.w as usize, dst.h as usize);
777 let mut scaled = (Vec::new(), Vec::new(), Vec::new());
778 let (py, pu, pv) = if (sw, sh) == (dw, dh) {
779 (fy, fu, fv)
780 } else {
781 let (ccw, cch) = chroma_dims(dw, dh);
782 scaled.0.resize(dw * dh, 0);
783 scaled.1.resize(ccw * cch, 0);
784 scaled.2.resize(ccw * cch, 0);
785 scale_i420(
786 fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh,
787 );
788 (&scaled.0[..], &scaled.1[..], &scaled.2[..])
789 };
790
791 let (w, h) = (canvas_w as usize, canvas_h as usize);
792 let mut canvas = black_i420(w, h);
793 compose_i420(
794 &mut canvas.0,
795 &mut canvas.1,
796 &mut canvas.2,
797 w,
798 h,
799 py,
800 pu,
801 pv,
802 dst,
803 );
804 (canvas.0, canvas.1, canvas.2, canvas_w, canvas_h)
805 }
806}
807
808/// Per-byte lerp of two same-sized I420 frames: `out = a + (b - a) * t`, on
809/// every plane. `t` is clamped to `[0, 1]` -- a caller ramping across a
810/// cross-dissolve window hands back an in-range fraction already, this is the
811/// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U
812/// with U, V with V); a mismatched pair panics rather than silently
813/// truncating a picture.
814pub fn blend_i420(a: (&[u8], &[u8], &[u8]), b: (&[u8], &[u8], &[u8]), t: f32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
815 let t = t.clamp(0.0, 1.0);
816 let plane = |a: &[u8], b: &[u8]| -> Vec<u8> {
817 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");
818 a.iter()
819 .zip(b)
820 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
821 .collect()
822 };
823 (plane(a.0, b.0), plane(a.1, b.1), plane(a.2, b.2))
824}
825
826/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
827/// across frames is refilled, not reallocated.
828fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
829 plane.clear();
830 plane.resize(len, value);
831}
832
833/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
834/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
835/// crop is exactly half of it.
836fn crop_i420(
837 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
838 y: &[u8],
839 u: &[u8],
840 v: &[u8],
841 src_w: usize,
842 src_h: usize,
843 rect: Rect,
844) {
845 let (w, h) = (rect.w as usize, rect.h as usize);
846 let (x, cy0) = (rect.x as usize, rect.y as usize);
847 let (src_cw, _) = chroma_dims(src_w, src_h);
848 let (cw, ch) = chroma_dims(w, h);
849 let (oy, ou, ov) = out;
850 oy.clear();
851 ou.clear();
852 ov.clear();
853 for row in 0..h {
854 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
855 }
856 let (cx, cy0) = (x / 2, cy0 / 2);
857 for row in 0..ch {
858 let at = (cy0 + row) * src_cw + cx;
859 ou.extend_from_slice(&u[at..][..cw]);
860 ov.extend_from_slice(&v[at..][..cw]);
861 }
862 debug_assert_eq!(oy.len(), w * h);
863 debug_assert_eq!(ou.len(), cw * ch);
864}
865
866#[cfg(test)]
867mod tests {
868 use super::*;
869
870 /// Allocates the destination planes for a size and runs a scale into them.
871 fn scaled(
872 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
873 src_w: usize,
874 src_h: usize,
875 dst_w: usize,
876 dst_h: usize,
877 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
878 let (cw, ch) = chroma_dims(dst_w, dst_h);
879 let mut dst = (
880 vec![0u8; dst_w * dst_h],
881 vec![0u8; cw * ch],
882 vec![0u8; cw * ch],
883 );
884 scale_i420(
885 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
886 );
887 dst
888 }
889
890 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
891 let (cw, ch) = chroma_dims(w, h);
892 (
893 (0..w * h).map(|i| (i % 256) as u8).collect(),
894 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
895 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
896 )
897 }
898
899 /// The pass-through invariant: a project at the media's own resolution must
900 /// hand the decoder's bytes to the encoder unchanged.
901 #[test]
902 fn identity_scale_is_byte_identical() {
903 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
904 let src = gradient(w, h);
905 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
906 }
907 }
908
909 /// Halving is the one case where bilinear is exactly a 2x2 box average:
910 /// the output centre falls on the shared corner of four input samples.
911 /// 0/254 averages to 127 with no rounding slack at all.
912 #[test]
913 fn downscale_by_two_averages_a_checkerboard() {
914 let (w, h) = (32, 24);
915 let (cw, ch) = chroma_dims(w, h);
916 let checker = |i: usize, stride: usize| {
917 if (i / stride + i % stride).is_multiple_of(2) {
918 0u8
919 } else {
920 254
921 }
922 };
923 let src = (
924 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
925 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
926 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
927 );
928 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
929 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
930 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
931 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
932 }
933
934 /// Nothing may leak in from outside a plane: a flat frame stays flat at
935 /// every edge, upscaled and downscaled, odd sizes included.
936 #[test]
937 fn flat_frame_stays_flat() {
938 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
939 for &(sw, sh) in &sizes {
940 let (cw, ch) = chroma_dims(sw, sh);
941 let src = (
942 vec![80u8; sw * sh],
943 vec![90u8; cw * ch],
944 vec![200u8; cw * ch],
945 );
946 for &(dw, dh) in &sizes {
947 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
948 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
949 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
950 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
951 }
952 }
953 }
954
955 /// Chroma alignment: an edge in the U plane must land at the *same* place
956 /// after a 2x upscale, with a symmetric two-sample blend around it and
957 /// untouched flats either side -- a half-sample bias shows up as an
958 /// asymmetric pair here, which is colour bleeding one way.
959 #[test]
960 fn chroma_edge_keeps_its_position() {
961 let (w, h) = (8, 8);
962 let (cw, ch) = chroma_dims(w, h);
963 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
964 let src = (
965 vec![80u8; w * h],
966 (0..cw * ch)
967 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
968 .collect(),
969 vec![128u8; cw * ch],
970 );
971 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
972 let (dcw, _) = chroma_dims(w * 2, h * 2);
973 assert_eq!(dcw, 8);
974 let row = &u[dcw * 3..][..dcw];
975 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
976 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
977 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
978 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
979 // most 1; anything further means the edge moved.
980 assert!(
981 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
982 "blend is off centre, i.e. chroma bled one way: {row:?}"
983 );
984 }
985
986 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
987 /// `(src, dst, policy) -> (placement, crop)`.
988 #[test]
989 fn fit_rect_table() {
990 let r = |x, y, w, h| Rect { x, y, w, h };
991 let cases = [
992 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
993 (
994 (1920, 1080),
995 (640, 480),
996 FitPolicy::Fit,
997 r(0, 60, 640, 360),
998 r(0, 0, 1920, 1080),
999 ),
1000 // ...and the same pair filled: the canvas is whole, the source is
1001 // cropped to 4:3 (1440 wide) about its centre.
1002 (
1003 (1920, 1080),
1004 (640, 480),
1005 FitPolicy::Fill,
1006 r(0, 0, 640, 480),
1007 r(240, 0, 1440, 1080),
1008 ),
1009 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
1010 (
1011 (640, 480),
1012 (1920, 1080),
1013 FitPolicy::Fit,
1014 r(240, 0, 1440, 1080),
1015 r(0, 0, 640, 480),
1016 ),
1017 (
1018 (640, 480),
1019 (1920, 1080),
1020 FitPolicy::Fill,
1021 r(0, 0, 1920, 1080),
1022 r(0, 60, 640, 360),
1023 ),
1024 // Stretch ignores aspect entirely, both ways.
1025 (
1026 (1920, 1080),
1027 (640, 480),
1028 FitPolicy::Stretch,
1029 r(0, 0, 640, 480),
1030 r(0, 0, 1920, 1080),
1031 ),
1032 // 1:1 with a bigger source: cropped both ways, centred.
1033 (
1034 (1920, 1080),
1035 (640, 480),
1036 FitPolicy::Center,
1037 r(0, 0, 640, 480),
1038 r(640, 300, 640, 480),
1039 ),
1040 // 1:1 with a smaller source: padded both ways, centred.
1041 (
1042 (640, 480),
1043 (1920, 1080),
1044 FitPolicy::Center,
1045 r(640, 300, 640, 480),
1046 r(0, 0, 640, 480),
1047 ),
1048 // Odd sizes: offsets even, sizes even unless they reach the edge.
1049 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
1050 (
1051 (7, 5),
1052 (13, 9),
1053 FitPolicy::Fit,
1054 r(0, 0, 13, 9),
1055 r(0, 0, 7, 5),
1056 ),
1057 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
1058 // offset without putting chroma half a sample off, so the last one
1059 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
1060 (
1061 (9, 9),
1062 (13, 9),
1063 FitPolicy::Center,
1064 r(2, 0, 8, 9),
1065 r(0, 0, 8, 9),
1066 ),
1067 (
1068 (13, 9),
1069 (9, 9),
1070 FitPolicy::Center,
1071 r(0, 0, 8, 9),
1072 r(2, 0, 8, 9),
1073 ),
1074 ];
1075 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
1076 let got = fit_rect(sw, sh, dw, dh, policy);
1077 assert_eq!(
1078 got,
1079 (want_dst, want_src),
1080 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
1081 );
1082 }
1083 // Degenerate input is empty, not a panic.
1084 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
1085 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
1086 }
1087
1088 /// Every rect a policy hands back must sit inside its plane, start on the
1089 /// chroma grid, and end on it or at the plane edge -- the invariant
1090 /// `compose_i420` relies on.
1091 #[test]
1092 fn fit_rect_stays_on_the_chroma_grid() {
1093 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
1094 for policy in [
1095 FitPolicy::Fit,
1096 FitPolicy::Fill,
1097 FitPolicy::Stretch,
1098 FitPolicy::Center,
1099 ] {
1100 for &sw in &sizes {
1101 for &dh in &sizes {
1102 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
1103 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
1104 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
1105 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
1106 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
1107 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
1108 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
1109 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
1110 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
1111 // A plane one sample wide or high has no chroma grid to
1112 // be on: `Center` from a 2-high source onto a 1-high
1113 // canvas is one row, and no size satisfies both edges.
1114 // Nothing real is that shape; it must merely not
1115 // escape its plane, which the two asserts above cover.
1116 if grid {
1117 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
1118 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
1119 }
1120 assert!(!rect.is_empty(), "{ctx} empty");
1121 }
1122 }
1123 }
1124 }
1125 }
1126
1127 #[test]
1128 fn compose_fills_the_rect_and_nothing_else() {
1129 let (cw2, ch2) = (640usize, 360usize);
1130 let (canvas_w, canvas_h) = (640usize, 480usize);
1131 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
1132 let (fcw, fch) = chroma_dims(cw2, ch2);
1133 let frame = (
1134 vec![200u8; cw2 * ch2],
1135 vec![70u8; fcw * fch],
1136 vec![30u8; fcw * fch],
1137 );
1138 let rect = Rect {
1139 x: 0,
1140 y: 60,
1141 w: cw2 as u32,
1142 h: ch2 as u32,
1143 };
1144 compose_i420(
1145 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
1146 );
1147
1148 for row in 0..canvas_h {
1149 let inside = (60..420).contains(&row);
1150 let want = if inside { 200 } else { BLACK_Y };
1151 assert!(
1152 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
1153 "luma row {row}"
1154 );
1155 }
1156 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
1157 for row in 0..cch {
1158 let inside = (30..210).contains(&row);
1159 let (wu, wv) = if inside {
1160 (70, 30)
1161 } else {
1162 (NEUTRAL_C, NEUTRAL_C)
1163 };
1164 assert!(
1165 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
1166 "U row {row}"
1167 );
1168 assert!(
1169 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
1170 "V row {row}"
1171 );
1172 }
1173 }
1174
1175 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
1176 /// is public and a caller may compute a rect itself.
1177 #[test]
1178 fn compose_clips_a_rect_that_runs_off_the_canvas() {
1179 let (mut y, mut u, mut v) = black_i420(16, 16);
1180 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
1181 let rect = Rect {
1182 x: 12,
1183 y: 12,
1184 w: 8,
1185 h: 8,
1186 };
1187 compose_i420(
1188 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
1189 );
1190 assert_eq!(y[15 * 16 + 15], 99);
1191 assert_eq!(y[11 * 16 + 15], BLACK_Y);
1192 // Wholly outside: no write at all.
1193 let before = y.clone();
1194 compose_i420(
1195 &mut y,
1196 &mut u,
1197 &mut v,
1198 16,
1199 16,
1200 &frame.0,
1201 &frame.1,
1202 &frame.2,
1203 Rect {
1204 x: 100,
1205 y: 0,
1206 w: 8,
1207 h: 8,
1208 },
1209 );
1210 assert_eq!(y, before);
1211 }
1212
1213 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
1214 /// project canvas, letterbox bars intact.
1215 #[test]
1216 fn fit_scale_compose_letterboxes() {
1217 let (sw, sh) = (640usize, 480usize);
1218 let (dw, dh) = (1920usize, 1080usize);
1219 let src = gradient(sw, sh);
1220 let (dst_rect, src_rect) =
1221 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
1222 assert_eq!(
1223 src_rect,
1224 Rect {
1225 x: 0,
1226 y: 0,
1227 w: 640,
1228 h: 480
1229 }
1230 );
1231 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
1232 let picture = scaled(&src, sw, sh, rw, rh);
1233 let (mut y, mut u, mut v) = black_i420(dw, dh);
1234 compose_i420(
1235 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
1236 );
1237 // Pillarbox columns stay black, the picture area does not.
1238 let mid = (dh / 2) * dw;
1239 assert!(
1240 y[mid..mid + dst_rect.x as usize]
1241 .iter()
1242 .all(|&s| s == BLACK_Y)
1243 );
1244 assert_eq!(
1245 y[mid + dst_rect.x as usize..][..rw],
1246 picture.0[(rh / 2) * rw..][..rw]
1247 );
1248 }
1249
1250 /// The wiring invariant: a project at its media's own resolution hands the
1251 /// decoder's own slices back, not a copy that happens to be equal. Asserted
1252 /// on the pointer, because "identical bytes" is cheap and "no work at all"
1253 /// is what the common case is promised.
1254 #[test]
1255 fn a_canvas_of_the_source_size_is_a_pass_through() {
1256 let (w, h) = (64usize, 48usize);
1257 let src = gradient(w, h);
1258 for mut canvas in [
1259 Composer::new(w as u32, h as u32, FitPolicy::Fit),
1260 Composer::new(w as u32, h as u32, FitPolicy::Fill),
1261 Composer::new(w as u32, h as u32, FitPolicy::Center),
1262 Composer::passthrough(),
1263 ] {
1264 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
1265 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
1266 assert_eq!(u.as_ptr(), src.1.as_ptr());
1267 assert_eq!(v.as_ptr(), src.2.as_ptr());
1268 assert_eq!((cw, ch), (w as u32, h as u32));
1269 }
1270 }
1271
1272 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
1273 /// the pillarbox columns are limited-range black, exactly -- a bar that is
1274 /// merely dark is a bar the grade reached.
1275 #[test]
1276 fn fit_pillarboxes_with_exact_black_bars() {
1277 let (sw, sh) = (640u32, 480u32);
1278 let (dw, dh) = (1920u32, 1080u32);
1279 let src = (
1280 vec![200u8; (sw * sh) as usize],
1281 vec![70u8; (sw * sh / 4) as usize],
1282 vec![30u8; (sw * sh / 4) as usize],
1283 );
1284 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
1285 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1286 assert_eq!((w, h), (dw, dh));
1287 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
1288 assert_eq!(
1289 rect,
1290 Rect {
1291 x: 240,
1292 y: 0,
1293 w: 1440,
1294 h: 1080
1295 },
1296 "geometry moved"
1297 );
1298 let (w, h) = (w as usize, h as usize);
1299 let row = &y[(h / 2) * w..][..w];
1300 let x = rect.x as usize;
1301 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
1302 assert!(
1303 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
1304 "right bar not black"
1305 );
1306 assert!(
1307 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
1308 "picture"
1309 );
1310 // ...and the bars are neutral in chroma too, or they would be a colour.
1311 let (cw, _) = chroma_dims(w, h);
1312 let crow = &u[(h / 4) * cw..][..cw];
1313 assert!(
1314 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
1315 "bar has colour"
1316 );
1317 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
1318 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
1319 }
1320
1321 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
1322 /// the canvas (no bar anywhere), `Center` pads without resampling.
1323 #[test]
1324 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
1325 let (sw, sh) = (640u32, 480u32);
1326 let (dw, dh) = (1920u32, 1080u32);
1327 let src = (
1328 vec![200u8; (sw * sh) as usize],
1329 vec![70u8; (sw * sh / 4) as usize],
1330 vec![30u8; (sw * sh / 4) as usize],
1331 );
1332 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
1333 let mut canvas = Composer::new(dw, dh, policy);
1334 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1335 assert!(
1336 y.iter().all(|&s| s == 200),
1337 "{policy:?} left a bar: the canvas is not covered"
1338 );
1339 }
1340 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1341 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1342 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1343 assert_eq!(rect.w, sw, "Center resampled the picture");
1344 let (w, h) = (w as usize, h as usize);
1345 let row = &y[(h / 2) * w..][..w];
1346 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1347 assert!(
1348 row[rect.x as usize..][..sw as usize]
1349 .iter()
1350 .all(|&s| s == 200)
1351 );
1352 }
1353
1354 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1355 /// picture, chroma with it: a marked band at a known column has to come out
1356 /// at the column the geometry puts it at.
1357 #[test]
1358 fn fill_crops_about_the_centre() {
1359 let (sw, sh) = (32usize, 8usize);
1360 let (dw, dh) = (8u32, 8u32);
1361 // Column 16 (the centre) is bright, everything else is dark.
1362 let y: Vec<u8> = (0..sw * sh)
1363 .map(|i| if i % sw == 16 { 240 } else { 40 })
1364 .collect();
1365 let (cw, ch) = chroma_dims(sw, sh);
1366 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1367 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1368 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1369 assert_eq!((w, h), (dw, dh));
1370 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1371 assert_eq!(
1372 dst,
1373 Rect {
1374 x: 0,
1375 y: 0,
1376 w: 8,
1377 h: 8
1378 },
1379 "Fill must cover"
1380 );
1381 assert_eq!(
1382 crop,
1383 Rect {
1384 x: 12,
1385 y: 0,
1386 w: 8,
1387 h: 8
1388 },
1389 "crop off centre"
1390 );
1391 // The bright column is crop-relative column 4 of 8, untouched by the
1392 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1393 let row = &y[..8];
1394 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1395 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1396 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1397 }
1398
1399 /// Not asserted: only the release number means anything. Run with
1400 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1401 #[test]
1402 fn perf_720p_to_1080p() {
1403 let src = gradient(1280, 720);
1404 let (cw, ch) = chroma_dims(1920, 1080);
1405 let mut dst = (
1406 vec![0u8; 1920 * 1080],
1407 vec![0u8; cw * ch],
1408 vec![0u8; cw * ch],
1409 );
1410 let runs = 30;
1411 let t = std::time::Instant::now();
1412 for _ in 0..runs {
1413 scale_i420(
1414 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1415 );
1416 }
1417 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1418 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1419 }
1420
1421 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1422 /// scale and blit -- which is what the playback budget has to hold. Printed,
1423 /// not asserted, like every other perf test here.
1424 #[test]
1425 fn perf_compose_720p_onto_1080p() {
1426 let src = gradient(1280, 720);
1427 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1428 let runs = 30;
1429 let t = std::time::Instant::now();
1430 for _ in 0..runs {
1431 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1432 }
1433 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1434 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1435 }
1436
1437 /// [`blend_i420`] at the midpoint of two solid-colour frames lands exactly
1438 /// on the 50/50 average, on every plane -- the synthetic stand-in for "the
1439 /// dissolve's midpoint frame looks like the average colour" the export
1440 /// path is built on.
1441 #[test]
1442 fn blend_i420_is_50_50_at_the_midpoint() {
1443 let a = (vec![0u8; 16], vec![10u8; 4], vec![20u8; 4]);
1444 let b = (vec![100u8; 16], vec![50u8; 4], vec![120u8; 4]);
1445 let (y, u, v) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.5);
1446 assert!(y.iter().all(|&p| p == 50), "Y midpoint: {y:?}");
1447 assert!(u.iter().all(|&p| p == 30), "U midpoint: {u:?}");
1448 assert!(v.iter().all(|&p| p == 70), "V midpoint: {v:?}");
1449 // The edges hand back each frame untouched.
1450 let (y0, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.0);
1451 assert_eq!(y0, a.0);
1452 let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0);
1453 assert_eq!(y1, b.0);
1454 }
1455
1456 /// The crop fractions cut a rect out of a 100x100 source at the very
1457 /// pixels the maths says, chroma-grid aligned like every other rect here.
1458 #[test]
1459 fn crop_rect_math() {
1460 let t = TransformParams {
1461 crop_l: 0.1,
1462 crop_r: 0.2,
1463 crop_t: 0.0,
1464 crop_b: 0.0,
1465 ..Default::default()
1466 };
1467 assert_eq!(
1468 crop_rect(100, 100, &t),
1469 Rect { x: 10, y: 0, w: 70, h: 100 },
1470 "10% off the left, 20% off the right, nothing off top or bottom"
1471 );
1472 // Opposing crops clamp to 0.5 a side rather than meeting or crossing.
1473 let extreme = TransformParams {
1474 crop_l: 0.9,
1475 crop_r: 0.9,
1476 ..Default::default()
1477 };
1478 let r = crop_rect(100, 100, &extreme);
1479 assert!(r.w >= 2, "the smallest surviving rect is one chroma sample");
1480 // A zero-sized source has nothing to crop.
1481 assert_eq!(crop_rect(0, 100, &TransformParams::default()), Rect { x: 0, y: 0, w: 0, h: 0 });
1482 }
1483
1484 /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own
1485 /// centre) and resized by `scale`, both about that same centre. Neither
1486 /// case here clips, so the source rect comes back untouched.
1487 #[test]
1488 fn transformed_dst_rect_at_pos_and_scale() {
1489 let dst = Rect { x: 0, y: 0, w: 100, h: 100 };
1490 let src = Rect { x: 0, y: 0, w: 100, h: 100 };
1491 // Moved a quarter of the canvas to the right, untouched vertically.
1492 let moved = TransformParams {
1493 pos_x: 0.25,
1494 ..Default::default()
1495 };
1496 assert_eq!(
1497 transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200),
1498 (Rect { x: 50, y: 0, w: 100, h: 100 }, src),
1499 "25% of a 200-wide canvas is 50 pixels, about the placement's own centre"
1500 );
1501 // Doubled in place, box already centred on the canvas: the centre
1502 // stays, the box fills the canvas, nothing clips.
1503 let centred_dst = Rect { x: 50, y: 50, w: 100, h: 100 };
1504 let grown = TransformParams {
1505 scale: 2.0,
1506 ..Default::default()
1507 };
1508 assert_eq!(
1509 transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200),
1510 (Rect { x: 0, y: 0, w: 200, h: 200 }, src),
1511 "a 100x100 box doubled about its own centre on a 200x200 canvas fills it"
1512 );
1513 }
1514
1515 /// The defect this replaces: a positive offset used to SHRINK the dst
1516 /// rect (squeezing the whole source into what remained) and a negative
1517 /// offset used to render pixel-identical to the identity (the clamp at 0
1518 /// killed it). Real translation keeps the box's size and clips instead:
1519 /// the src rect trims by the same fraction that fell off-canvas, on the
1520 /// side that fell off, and the surviving box size never shrinks below
1521 /// what `scale` alone gives it.
1522 #[test]
1523 fn transformed_dst_rect_clips_instead_of_squeezing() {
1524 let dst = Rect { x: 0, y: 0, w: 100, h: 100 };
1525 let src = Rect { x: 0, y: 0, w: 100, h: 100 };
1526 // +30% of a 100-wide canvas: the box moves 30px right, half of it
1527 // (50px) falls off the right edge -- half the source is trimmed off
1528 // its right, not the whole source squeezed into 70px.
1529 let pos = TransformParams { pos_x: 0.30, ..Default::default() };
1530 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100);
1531 assert_eq!(d, Rect { x: 30, y: 0, w: 70, h: 100 }, "dst size must not shrink below what clipping removes");
1532 assert_eq!(s, Rect { x: 0, y: 0, w: 70, h: 100 }, "src trims off its right, does not squeeze");
1533
1534 // -30%: symmetric on the left, and no longer identical to identity.
1535 let neg = TransformParams { pos_x: -0.30, ..Default::default() };
1536 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100);
1537 assert_eq!(d, Rect { x: 0, y: 0, w: 70, h: 100 });
1538 assert_eq!(s, Rect { x: 30, y: 0, w: 70, h: 100 }, "src trims off its left");
1539 assert_ne!((d, s), (dst, src), "a negative offset must move the picture, not no-op");
1540
1541 // Fully off canvas: both rects empty.
1542 let gone = TransformParams { pos_x: 2.0, ..Default::default() };
1543 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100);
1544 assert!(d.is_empty() && s.is_empty(), "wholly off-canvas has nothing to draw");
1545 }
1546
1547 /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a
1548 /// non-finite value to the identity.
1549 #[test]
1550 fn nearest_90_steps_rounds_and_wraps() {
1551 assert_eq!(nearest_90_steps(0.0), 0);
1552 assert_eq!(nearest_90_steps(89.0), 1);
1553 assert_eq!(nearest_90_steps(91.0), 1);
1554 assert_eq!(nearest_90_steps(180.0), 2);
1555 assert_eq!(nearest_90_steps(-90.0), 3);
1556 assert_eq!(nearest_90_steps(360.0 + 90.0), 1);
1557 assert_eq!(nearest_90_steps(f32::NAN), 0);
1558 }
1559
1560 /// A marked corner pixel lands where a clockwise quarter turn puts it:
1561 /// top-left to top-right at 90 degrees, to bottom-right at 180, to
1562 /// bottom-left at 270 -- and the plane's own shape swaps at 90 and 270
1563 /// and stays put at 180.
1564 #[test]
1565 fn rotate_i420_90s_places_a_marked_pixel() {
1566 let (w, h) = (4usize, 3usize);
1567 let mut y = vec![0u8; w * h];
1568 y[0] = 99; // (x=0, y=0), the top-left corner.
1569 let (u, v) = (vec![128u8; 2 * 2], vec![128u8; 2 * 2]);
1570
1571 let mark_at = |plane: &[u8], w: u32, x: u32, y: u32| plane[(y * w + x) as usize];
1572
1573 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1);
1574 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees");
1575 assert_eq!(mark_at(&ry, rw, rw - 1, 0), 99, "top-left moves to top-right");
1576
1577 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2);
1578 assert_eq!((rw, rh), (w as u32, h as u32), "dims stay put at 180 degrees");
1579 assert_eq!(
1580 mark_at(&ry, rw, rw - 1, rh - 1),
1581 99,
1582 "top-left moves to bottom-right"
1583 );
1584
1585 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 3);
1586 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 270 degrees");
1587 assert_eq!(
1588 mark_at(&ry, rw, 0, rh - 1),
1589 99,
1590 "top-left moves to bottom-left"
1591 );
1592
1593 // Zero steps, and four of them, are both the identity.
1594 let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0);
1595 assert_eq!((ry, ru, rv, rw, rh), (y.clone(), u.clone(), v.clone(), w as u32, h as u32));
1596 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4);
1597 assert_eq!((ry, rw, rh), (y, w as u32, h as u32), "four quarter turns is the identity");
1598 }
1599
1600 /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..64
1601 /// are 40. A vertical edge to track through a horizontal move.
1602 fn vsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1603 let y = (0..64 * 64).map(|i| if i % 64 < 32 { 200u8 } else { 40u8 }).collect();
1604 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1605 }
1606
1607 /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge
1608 /// to track through a vertical move.
1609 fn hsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1610 let y = (0..64 * 64).map(|i| if i / 64 < 32 { 200u8 } else { 40u8 }).collect();
1611 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
1612 }
1613
1614 /// [`Composer::place_transformed`] at compose level, with the exact
1615 /// defect the geometry used to have: a positive `pos_x` squeezed the
1616 /// whole source into a shrunk box (content narrower, not just displaced)
1617 /// and a negative one rendered pixel-identical to the identity. These
1618 /// assert on the DISPLACED CONTENT (where the source's own edge lands),
1619 /// not on any rect field, so a squeeze that happens to leave rect sizes
1620 /// looking plausible cannot pass silently.
1621 #[test]
1622 fn place_transformed_displaces_content_not_just_a_rect() {
1623 let (src_w, src_h) = (64u32, 64u32);
1624 let (y, u, v) = vsplit_64();
1625 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1626
1627 // Identity: the source's own edge stays at column 32, everywhere.
1628 let (iy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default());
1629 for row in 0..64 {
1630 let r = &iy[row * 64..][..64];
1631 assert!(r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40), "row {row}: {r:?}");
1632 }
1633
1634 // +25%: the box moves right by 16 and does NOT shrink -- content
1635 // width stays 64 (the source's own 32/32 split), clipped to what
1636 // still fits. The edge (originally at box-column 32) now sits at
1637 // canvas column 16 + 32 = 48, not squeezed inward.
1638 let plus = TransformParams { pos_x: 0.25, ..Default::default() };
1639 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1640 for row in 0..64 {
1641 let r = &py[row * 64..][..64];
1642 assert!(r[..16].iter().all(|&p| p == BLACK_Y), "row {row} left of box: {r:?}");
1643 assert!(r[16..48].iter().all(|&p| p == 200), "row {row} squeezed inward: {r:?}");
1644 assert!(r[48..].iter().all(|&p| p == 40), "row {row} edge moved: {r:?}");
1645 }
1646
1647 // -25%: mirror image -- this used to be pixel-identical to identity.
1648 let minus = TransformParams { pos_x: -0.25, ..Default::default() };
1649 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1650 assert_ne!(ny, iy, "a negative offset must move the picture, not no-op");
1651 for row in 0..64 {
1652 let r = &ny[row * 64..][..64];
1653 assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}");
1654 assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}");
1655 assert!(r[48..].iter().all(|&p| p == BLACK_Y), "row {row} right of box: {r:?}");
1656 }
1657
1658 // Wholly off-canvas: nothing to draw, all black.
1659 let gone = TransformParams { pos_x: 2.0, ..Default::default() };
1660 let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone);
1661 assert!(gy.iter().all(|&p| p == BLACK_Y), "off-canvas must render background");
1662 }
1663
1664 /// The same defect on the vertical axis: `pos_y` moves content up/down,
1665 /// clipped, never squeezed.
1666 #[test]
1667 fn place_transformed_displaces_content_vertically() {
1668 let (src_w, src_h) = (64u32, 64u32);
1669 let (y, u, v) = hsplit_64();
1670 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1671
1672 let plus = TransformParams { pos_y: 0.25, ..Default::default() };
1673 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
1674 for row in 0..16 {
1675 assert!(py[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} above the box");
1676 }
1677 for row in 16..48 {
1678 assert!(py[row * 64..][..64].iter().all(|&p| p == 200), "row {row} squeezed: {:?}", &py[row * 64..][..4]);
1679 }
1680 for row in 48..64 {
1681 assert!(py[row * 64..][..64].iter().all(|&p| p == 40), "row {row} edge moved");
1682 }
1683
1684 let minus = TransformParams { pos_y: -0.25, ..Default::default() };
1685 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
1686 for row in 0..16 {
1687 assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}");
1688 }
1689 for row in 16..48 {
1690 assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}");
1691 }
1692 for row in 48..64 {
1693 assert!(ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y), "row {row} below the box");
1694 }
1695 }
1696
1697 /// Position and scale together: a halved box moved right must place its
1698 /// (also halved) content at the moved-and-scaled location, not squeeze
1699 /// the full source into whatever survived clamping.
1700 #[test]
1701 fn place_transformed_displaces_content_with_scale() {
1702 let (src_w, src_h) = (64u32, 64u32);
1703 let (y, u, v) = vsplit_64();
1704 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
1705 // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16),
1706 // fully on-canvas. The source's column-32 edge, halved, sits at
1707 // box-local column 16, i.e. canvas column 32 + 16 = 48.
1708 let t = TransformParams { scale: 0.5, pos_x: 0.25, ..Default::default() };
1709 let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t);
1710 for row in 0..64 {
1711 let r = &sy[row * 64..][..64];
1712 let inside = (16..48).contains(&row);
1713 let want_bg = if inside { r[0] } else { BLACK_Y };
1714 assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}");
1715 if inside {
1716 assert!(r[40].abs_diff(200) <= 1, "row {row} col 40 should be the left half: {r:?}");
1717 assert!(r[56].abs_diff(40) <= 1, "row {row} col 56 should be the right half: {r:?}");
1718 }
1719 }
1720 }
1721}