forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

scale.rs2287 lines, 85.4 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 separable in 16.16 fixed point, weights precomputed once per
15//! plane per axis, no float and no division in the pixel loop. An axis that
16//! shrinks by no more than 2x is bilinear, two taps. An axis that shrinks by more
17//! than 2x is an area (box) filter: each output sample is the coverage-weighted
18//! average of the source samples its footprint overlaps, so a wide downscale does
19//! not alias. The upgrade path is a wider kernel (Lanczos-3) behind the same
20//! signature: nothing here exposes the tap count. 1280x720 -> 1920x1080
21//! measures 4.6 ms/frame in release (`perf_720p_to_1080p` below), against the
22//! 4.7 ms the BGRA conversion next door already costs per frame.
23//!
24//! Sample siting: each plane is resampled as its own image with centre-aligned
25//! mapping, `src = (dst + 0.5) * src_len / dst_len - 0.5`. For chroma that
26//! treats I420 as centre-sited where MPEG-2 calls it left-sited, a quarter-
27//! chroma-sample bias that no eye finds and that a siting-aware kernel would fix
28//! in the same place the Lanczos upgrade goes.
29
30use crate::transform::TransformParams;
31
32/// Limited-range black: what an untouched canvas pixel is.
33pub const BLACK_Y: u8 = 16;
34/// Neutral chroma: 128 in both planes.
35pub const NEUTRAL_C: u8 = 128;
36
37/// A sample of a planar picture: 8 bits for every picture the engine's own paths
38/// compose, or 10 bits in a `u16` for a 10-bit export. The arithmetic is the same
39/// at either depth, so it is written once: only the black, the neutral chroma and
40/// the largest code change between the two.
41pub trait Sample: Copy + Default + Send + Sync + 'static {
42 /// Limited-range black, luma.
43 const BLACK: Self;
44 /// Neutral chroma.
45 const NEUTRAL: Self;
46 /// The largest code: 255, or 1023 for a 10-bit `u16`.
47 const MAX: u32;
48 /// The sample's code, widened to `u32`.
49 fn code(self) -> u32;
50 /// A code already in range, as a sample (truncating, as `as` does).
51 fn from_code(code: u32) -> Self;
52 /// A float rounded to the nearest code and clamped to the sample's range.
53 fn from_f32(v: f32) -> Self;
54}
55
56impl Sample for u8 {
57 const BLACK: Self = BLACK_Y;
58 const NEUTRAL: Self = NEUTRAL_C;
59 const MAX: u32 = 255;
60 fn code(self) -> u32 {
61 u32::from(self)
62 }
63 fn from_code(code: u32) -> Self {
64 code as u8
65 }
66 fn from_f32(v: f32) -> Self {
67 v.round().clamp(0.0, 255.0) as u8
68 }
69}
70
71/// The 10-bit sample: the same limited-range codes at four times the depth.
72impl Sample for u16 {
73 const BLACK: Self = 64;
74 const NEUTRAL: Self = 512;
75 const MAX: u32 = 1023;
76 fn code(self) -> u32 {
77 u32::from(self)
78 }
79 fn from_code(code: u32) -> Self {
80 code as u16
81 }
82 fn from_f32(v: f32) -> Self {
83 v.round().clamp(0.0, 1023.0) as u16
84 }
85}
86
87/// A rectangle on one plane, in luma samples. Always inside the plane it
88/// describes; `fit_rect` never hands back one that is not.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct Rect {
91 pub x: u32,
92 pub y: u32,
93 pub w: u32,
94 pub h: u32,
95}
96
97impl Rect {
98 pub fn is_empty(&self) -> bool {
99 self.w == 0 || self.h == 0
100 }
101}
102
103/// How a source picture of one shape meets a canvas of another.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
105pub enum FitPolicy {
106 /// Whole picture, aspect kept, centred -- the leftover canvas is bars.
107 #[default]
108 Fit,
109 /// Whole canvas, aspect kept, centred -- the leftover picture is cropped.
110 Fill,
111 /// Whole picture on the whole canvas; aspect is not kept.
112 Stretch,
113 /// No resampling at all: 1:1 samples, centred, padded or cropped per axis.
114 Center,
115}
116
117/// Placement and crop for one source on one canvas.
118///
119/// Returns `(dst placement rect on the canvas, src crop rect on the source)`.
120/// The caller scales the crop to the placement size and composes it there; a
121/// `Center` result has the two rects the same size, i.e. nothing to scale.
122///
123/// Rounding, and why it is what it is: both rects are aligned to the I420
124/// chroma grid, so that one chroma sample of the scaled picture is one chroma
125/// sample of the canvas and no colour lands half a sample off. `x` and `y` are
126/// floored to even; `w` and `h` are floored to even *unless* the rect ends
127/// exactly at the plane edge, where an odd size is fine because both grids end
128/// together (that is what keeps an equal-size `Fit` a byte-exact pass-through
129/// on an odd-width source). The alignment can therefore cost one sample of
130/// aspect accuracy -- under a tenth of a percent at any real resolution.
131///
132/// A zero-sized canvas or source yields two empty rects. An extreme aspect
133/// never rounds the picture away: the smallest rect is one chroma sample (2x2),
134/// clipped to the plane. A plane one sample wide or high has no grid to align
135/// to and keeps that single sample.
136pub fn fit_rect(src_w: u32, src_h: u32, dst_w: u32, dst_h: u32, policy: FitPolicy) -> (Rect, Rect) {
137 let empty = Rect {
138 x: 0,
139 y: 0,
140 w: 0,
141 h: 0,
142 };
143 if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 {
144 return (empty, empty);
145 }
146 let full_src = Rect {
147 x: 0,
148 y: 0,
149 w: src_w,
150 h: src_h,
151 };
152 let full_dst = Rect {
153 x: 0,
154 y: 0,
155 w: dst_w,
156 h: dst_h,
157 };
158
159 match policy {
160 FitPolicy::Stretch => (full_dst, full_src),
161 FitPolicy::Fit => {
162 // Widest box with the source aspect that still fits the canvas.
163 let (w, h) =
164 if u64::from(src_w) * u64::from(dst_h) <= u64::from(dst_w) * u64::from(src_h) {
165 (ratio(src_w, dst_h, src_h).min(dst_w), dst_h)
166 } else {
167 (dst_w, ratio(src_h, dst_w, src_w).min(dst_h))
168 };
169 (centred(w, h, dst_w, dst_h), full_src)
170 }
171 FitPolicy::Fill => {
172 // Largest box with the canvas aspect that still fits the source.
173 let (w, h) =
174 if u64::from(src_w) * u64::from(dst_h) >= u64::from(dst_w) * u64::from(src_h) {
175 (ratio(src_h, dst_w, dst_h).min(src_w), src_h)
176 } else {
177 (src_w, ratio(src_w, dst_h, dst_w).min(src_h))
178 };
179 (full_dst, centred(w, h, src_w, src_h))
180 }
181 FitPolicy::Center => {
182 let w = src_w.min(dst_w);
183 let h = src_h.min(dst_h);
184 let dst = centred(w, h, dst_w, dst_h);
185 let src = centred(w, h, src_w, src_h);
186 // Even-alignment may have shrunk one of them; 1:1 means both carry
187 // the same sample count, so take the smaller of the two.
188 let w = dst.w.min(src.w);
189 let h = dst.h.min(src.h);
190 (Rect { w, h, ..dst }, Rect { w, h, ..src })
191 }
192 }
193}
194
195/// `value * num / den`, rounded to nearest, in 64-bit so 8K x 8K cannot wrap.
196fn ratio(value: u32, num: u32, den: u32) -> u32 {
197 let den = u64::from(den).max(1);
198 ((u64::from(value) * u64::from(num) + den / 2) / den) as u32
199}
200
201/// A `w` x `h` box centred in `extent_w` x `extent_h`, chroma-grid aligned.
202fn centred(w: u32, h: u32, extent_w: u32, extent_h: u32) -> Rect {
203 let (x, w) = align(extent_w.saturating_sub(w) / 2, w, extent_w);
204 let (y, h) = align(extent_h.saturating_sub(h) / 2, h, extent_h);
205 Rect { x, y, w, h }
206}
207
208/// Floors the offset to even, clips the size into the plane, and floors the
209/// size to even unless the rect ends at the plane edge.
210fn align(offset: u32, size: u32, extent: u32) -> (u32, u32) {
211 let offset = (offset & !1).min(extent);
212 let mut size = size.min(extent - offset);
213 if offset + size < extent {
214 size &= !1;
215 }
216 if size == 0 {
217 // An extreme aspect (a 1-sample-wide source) would otherwise round its
218 // picture away entirely. One chroma sample is the floor, not zero.
219 size = extent.min(2);
220 }
221 (offset, size)
222}
223
224/// Chroma plane size for a luma dimension: `(w + 1) / 2`, both axes.
225pub fn chroma_dims(w: usize, h: usize) -> (usize, usize) {
226 (w.div_ceil(2), h.div_ceil(2))
227}
228
229/// A `w` x `h` I420 canvas filled with limited-range black.
230pub fn black_i420(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
231 black_planes(w, h)
232}
233
234/// [`black_i420`] at 10 bits: luma 64, chroma 512.
235pub fn black_i420_wide(w: usize, h: usize) -> (Vec<u16>, Vec<u16>, Vec<u16>) {
236 black_planes(w, h)
237}
238
239/// [`black_i420`] at either sample type: a 10-bit canvas is black at 64 and 512.
240fn black_planes<T: Sample>(w: usize, h: usize) -> (Vec<T>, Vec<T>, Vec<T>) {
241 let (cw, ch) = chroma_dims(w, h);
242 (
243 vec![T::BLACK; w * h],
244 vec![T::NEUTRAL; cw * ch],
245 vec![T::NEUTRAL; cw * ch],
246 )
247}
248
249/// Resamples a tightly packed I420 frame (stride == width) into another one.
250///
251/// Equal dimensions copy byte for byte -- a project at the media's own
252/// resolution is not a resample. Otherwise each plane is resampled independently
253/// (bilinear, or box on an axis that shrinks by more than 2x), chroma at its own
254/// `(w + 1) / 2` size, so odd dimensions need no special case: a 7x5 source has
255/// a 4x3 chroma plane and a 13x9 destination wants a 7x5 one, and that is just
256/// another rescale.
257///
258/// Panics if a slice is not exactly its plane's size; a mis-sized buffer is a
259/// caller bug, not a runtime condition, and every alternative silently produces
260/// a sheared picture.
261#[allow(clippy::too_many_arguments)]
262pub fn scale_i420<T: Sample>(
263 src_y: &[T],
264 src_u: &[T],
265 src_v: &[T],
266 src_w: usize,
267 src_h: usize,
268 dst_y: &mut [T],
269 dst_u: &mut [T],
270 dst_v: &mut [T],
271 dst_w: usize,
272 dst_h: usize,
273) {
274 let (src_cw, src_ch) = chroma_dims(src_w, src_h);
275 let (dst_cw, dst_ch) = chroma_dims(dst_w, dst_h);
276 assert_eq!(src_y.len(), src_w * src_h, "source luma plane");
277 assert_eq!(src_u.len(), src_cw * src_ch, "source U plane");
278 assert_eq!(src_v.len(), src_cw * src_ch, "source V plane");
279 assert_eq!(dst_y.len(), dst_w * dst_h, "destination luma plane");
280 assert_eq!(dst_u.len(), dst_cw * dst_ch, "destination U plane");
281 assert_eq!(dst_v.len(), dst_cw * dst_ch, "destination V plane");
282
283 if src_w == dst_w && src_h == dst_h {
284 dst_y.copy_from_slice(src_y);
285 dst_u.copy_from_slice(src_u);
286 dst_v.copy_from_slice(src_v);
287 return;
288 }
289 plane(src_y, src_w, src_h, dst_y, dst_w, dst_h);
290 plane(src_u, src_cw, src_ch, dst_u, dst_cw, dst_ch);
291 plane(src_v, src_cw, src_ch, dst_v, dst_cw, dst_ch);
292}
293
294/// 16.16 fixed point: one whole sample step.
295const ONE: u32 = 1 << 16;
296const HALF: u32 = ONE / 2;
297
298/// The source samples one output sample reads, and their 16.16 weights summing to [`ONE`].
299type Tap = Vec<(usize, u32)>;
300
301fn axis(dst_len: usize, src_len: usize) -> Vec<Tap> {
302 if src_len > 2 * dst_len {
303 box_taps(dst_len, src_len)
304 } else {
305 bilinear_taps(dst_len, src_len)
306 }
307}
308
309/// The two source samples and the weight of the second one, for one output
310/// position: `src = (dst + 0.5) * src_len / dst_len - 0.5`, clamped to the
311/// plane so the edges replicate instead of reading past it.
312fn bilinear_taps(dst_len: usize, src_len: usize) -> Vec<Tap> {
313 let step = (src_len as u64) * u64::from(ONE) / dst_len as u64;
314 let last = src_len as u32 - 1;
315 (0..dst_len)
316 .map(|i| {
317 // (i + 0.5) * step - 0.5, kept in u64 until the subtraction so the
318 // clamp at 0 is the only place a negative could have appeared.
319 let centre = (2 * i as u64 + 1) * step / 2;
320 let pos = centre.saturating_sub(u64::from(HALF));
321 let whole = ((pos >> 16) as u32).min(last);
322 let frac = if whole == last {
323 0
324 } else {
325 (pos as u32) & (ONE - 1)
326 };
327 let next = (whole + 1).min(last);
328 vec![(whole as usize, ONE - frac), (next as usize, frac)]
329 })
330 .collect()
331}
332
333fn box_taps(dst_len: usize, src_len: usize) -> Vec<Tap> {
334 let (d, s) = (dst_len as u64, src_len as u64);
335 (0..d)
336 .map(|i| {
337 let (a, b) = (i * s, (i + 1) * s);
338 let mut tap: Tap = (a / d..=(b - 1) / d)
339 .map(|j| {
340 let overlap = ((j + 1) * d).min(b) - (j * d).max(a);
341 (j as usize, ((overlap * u64::from(ONE) + s / 2) / s) as u32)
342 })
343 .collect();
344 let sum: i64 = tap.iter().map(|&(_, w)| i64::from(w)).sum();
345 if let Some(big) = tap.iter_mut().max_by_key(|t| t.1) {
346 big.1 = (i64::from(big.1) + i64::from(ONE) - sum) as u32;
347 }
348 tap
349 })
350 .collect()
351}
352
353fn bilinear_plane<T: Sample>(src: &[T], src_w: usize, src_h: usize, dst: &mut [T], dst_w: usize, dst_h: usize) {
354 let cols = bilinear_taps(dst_w, src_w);
355 let rows = bilinear_taps(dst_h, src_h);
356 for (y, ry) in rows.iter().enumerate() {
357 let ((y0, inv_wy), (y1, wy)) = (ry[0], ry[1]);
358 let top = &src[y0 * src_w..][..src_w];
359 let bottom = &src[y1 * src_w..][..src_w];
360 let out = &mut dst[y * dst_w..][..dst_w];
361 for (o, cx) in out.iter_mut().zip(cols.iter()) {
362 let ((x0, inv_wx), (x1, wx)) = (cx[0], cx[1]);
363 let a = (top[x0].code() * inv_wx + top[x1].code() * wx + HALF) >> 16;
364 let b = (bottom[x0].code() * inv_wx + bottom[x1].code() * wx + HALF) >> 16;
365 *o = T::from_code((a * inv_wy + b * wy + HALF) >> 16);
366 }
367 }
368}
369
370fn round16(acc: u64) -> u32 {
371 ((acc + u64::from(HALF)) >> 16) as u32
372}
373
374/// Resample of one tightly packed plane: horizontal into codes at the source's
375/// precision, then vertical.
376fn plane<T: Sample>(src: &[T], src_w: usize, src_h: usize, dst: &mut [T], dst_w: usize, dst_h: usize) {
377 if dst_w == 0 || dst_h == 0 || src_w == 0 || src_h == 0 {
378 return;
379 }
380 if src_w <= 2 * dst_w && src_h <= 2 * dst_h {
381 return bilinear_plane(src, src_w, src_h, dst, dst_w, dst_h);
382 }
383 let cols = axis(dst_w, src_w);
384 let rows = axis(dst_h, src_h);
385
386 let mut mid = vec![0u32; dst_w * src_h];
387 for (line, out) in src.chunks_exact(src_w).zip(mid.chunks_exact_mut(dst_w)) {
388 for (o, tap) in out.iter_mut().zip(&cols) {
389 let acc: u64 = tap
390 .iter()
391 .map(|&(x, w)| u64::from(line[x].code()) * u64::from(w))
392 .sum();
393 *o = round16(acc);
394 }
395 }
396 for (y, tap) in rows.iter().enumerate() {
397 let out = &mut dst[y * dst_w..][..dst_w];
398 for (x, o) in out.iter_mut().enumerate() {
399 let acc: u64 = tap
400 .iter()
401 .map(|&(r, w)| u64::from(mid[r * dst_w + x]) * u64::from(w))
402 .sum();
403 *o = T::from_code(round16(acc));
404 }
405 }
406}
407
408/// Blits a frame of exactly `rect.w` x `rect.h` onto a canvas at `rect`.
409///
410/// The rect is clipped to the canvas first, so a rect from anywhere (not just
411/// [`fit_rect`]) is safe; a clipped blit copies the part that fits, from the
412/// frame's top-left. Everything outside the rect keeps whatever the canvas
413/// already held -- [`black_i420`] for a letterbox.
414///
415/// Chroma rounding: `rect.x/2` and `rect.y/2` address the canvas chroma plane,
416/// which is exact because [`fit_rect`] hands back even offsets. An odd offset
417/// would put the frame's chroma half a sample off its own grid, so it is
418/// floored to even here rather than silently smeared.
419#[allow(clippy::too_many_arguments)]
420pub fn compose_i420<T: Sample>(
421 canvas_y: &mut [T],
422 canvas_u: &mut [T],
423 canvas_v: &mut [T],
424 canvas_w: usize,
425 canvas_h: usize,
426 frame_y: &[T],
427 frame_u: &[T],
428 frame_v: &[T],
429 rect: Rect,
430) {
431 let x = (rect.x & !1) as usize;
432 let y = (rect.y & !1) as usize;
433 if x >= canvas_w || y >= canvas_h {
434 return;
435 }
436 let fw = rect.w as usize;
437 let fh = rect.h as usize;
438 let w = fw.min(canvas_w - x);
439 let h = fh.min(canvas_h - y);
440 if w == 0 || h == 0 {
441 return;
442 }
443 for row in 0..h {
444 canvas_y[(y + row) * canvas_w + x..][..w].copy_from_slice(&frame_y[row * fw..][..w]);
445 }
446
447 let (canvas_cw, _) = chroma_dims(canvas_w, canvas_h);
448 let (fcw, _) = chroma_dims(fw, fh);
449 // Half-resolution copy of the clipped luma region, rounded up so an odd
450 // width still carries its last (half-covered) chroma sample.
451 let (cw, ch) = chroma_dims(w, h);
452 let (cx, cy) = (x / 2, y / 2);
453 for row in 0..ch {
454 let dst = (cy + row) * canvas_cw + cx;
455 canvas_u[dst..][..cw].copy_from_slice(&frame_u[row * fcw..][..cw]);
456 canvas_v[dst..][..cw].copy_from_slice(&frame_v[row * fcw..][..cw]);
457 }
458}
459
460/// The source rect [`TransformParams`]'s crop fractions cut out of a `src_w` x
461/// `src_h` picture, chroma-grid aligned exactly as [`fit_rect`]'s rects are.
462/// Fractions are clamped to `0.0..=0.5` a side, so opposing crops can never
463/// meet or cross -- the smallest surviving rect is one chroma sample, for
464/// [`align`]'s reason.
465pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect {
466 if src_w == 0 || src_h == 0 {
467 return Rect {
468 x: 0,
469 y: 0,
470 w: 0,
471 h: 0,
472 };
473 }
474 let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5));
475 let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5));
476 let x0 = (f64::from(src_w) * f64::from(cl)).round() as u32;
477 let x1 = (f64::from(src_w) * (1.0 - f64::from(cr))).round() as u32;
478 let y0 = (f64::from(src_h) * f64::from(ct)).round() as u32;
479 let y1 = (f64::from(src_h) * (1.0 - f64::from(cb))).round() as u32;
480 let (x, w) = align(x0.min(src_w), x1.saturating_sub(x0), src_w);
481 let (y, h) = align(y0.min(src_h), y1.saturating_sub(y0), src_h);
482 Rect { x, y, w, h }
483}
484
485/// `dst` -- a placement [`fit_rect`] already worked out, paired with the `src`
486/// rect (inside a `src_w` x `src_h` picture) it is sourced from -- moved by
487/// [`TransformParams::pos_x`]/`pos_y` (canvas fractions, about `dst`'s own
488/// centre) and resized by `scale` (about that same centre).
489///
490/// Translation and scale never distort the picture: the placed box keeps the
491/// aspect its size and `scale` give it, full stop. What moving it off-canvas
492/// does is clip -- the part of the box that falls outside `0..canvas_w` /
493/// `0..canvas_h` is dropped, and the matching fraction of `src` is trimmed
494/// off the same sides, so what remains on screen is an unscaled slice of the
495/// source, not the whole source squeezed into whatever box survived
496/// clamping. Both rects come back chroma-grid aligned like every other rect
497/// here; a placement pushed entirely off the canvas comes back as two empty
498/// rects, which is what [`compose_i420`] already treats as nothing to draw.
499pub fn transformed_dst_rect(
500 dst: Rect,
501 src: Rect,
502 src_w: u32,
503 src_h: u32,
504 t: &TransformParams,
505 canvas_w: u32,
506 canvas_h: u32,
507) -> (Rect, Rect) {
508 let empty = Rect {
509 x: 0,
510 y: 0,
511 w: 0,
512 h: 0,
513 };
514 if dst.is_empty() || src.is_empty() || canvas_w == 0 || canvas_h == 0 {
515 return (dst, src);
516 }
517 let scale = if t.scale.is_finite() && t.scale > 0.0 {
518 f64::from(t.scale)
519 } else {
520 1.0
521 };
522 // Bounded well above any real canvas so the src-trim ratios below cannot
523 // overflow i64, however extreme a stored scale value is.
524 let cap_w = i64::from(canvas_w.max(1)) * 1024;
525 let cap_h = i64::from(canvas_h.max(1)) * 1024;
526 let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, cap_w);
527 let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, cap_h);
528 // ...and the position, to the same ceiling, for the same reason. A
529 // `transform` line takes any finite `f32` for `pos_x`/`pos_y` (there is
530 // no per-field clamp at the parse, unlike `scale`'s use of the value), and
531 // `f64 as i64` *saturates* -- so a hostile 3e38 arrived here as `i64::MAX`
532 // and the additions below, not the cast, are what overflowed: a panic on
533 // the compositing thread in a debug build and a silently wrapped position
534 // in a release one. A cap in canvas fractions is the same 1024 the scale
535 // gets, and a box pushed that far off the canvas is long gone either way:
536 // it comes back as the two empty rects the function already answers with.
537 let pos_x = if t.pos_x.is_finite() {
538 f64::from(t.pos_x)
539 } else {
540 0.0
541 };
542 let pos_y = if t.pos_y.is_finite() {
543 f64::from(t.pos_y)
544 } else {
545 0.0
546 };
547 let cx = (i64::from(dst.x) + i64::from(dst.w) / 2)
548 .saturating_add((f64::from(canvas_w) * pos_x.clamp(-1024.0, 1024.0)).round() as i64);
549 let cy = (i64::from(dst.y) + i64::from(dst.h) / 2)
550 .saturating_add((f64::from(canvas_h) * pos_y.clamp(-1024.0, 1024.0)).round() as i64);
551 // The full box the transform describes, unclamped -- it may start
552 // negative or run past either edge, which is exactly what "moved off the
553 // canvas" means.
554 let bx = cx - new_w / 2;
555 let by = cy - new_h / 2;
556
557 // How much of that box, in the box's own pixels, falls outside the
558 // canvas on each side.
559 let left = (-bx).clamp(0, new_w);
560 let top = (-by).clamp(0, new_h);
561 let right = (bx + new_w - i64::from(canvas_w)).clamp(0, new_w);
562 let bottom = (by + new_h - i64::from(canvas_h)).clamp(0, new_h);
563 if left + right >= new_w || top + bottom >= new_h {
564 return (empty, empty);
565 }
566
567 let dst_x = (bx + left).clamp(0, i64::from(canvas_w)) as u32;
568 let dst_y = (by + top).clamp(0, i64::from(canvas_h)) as u32;
569 let (dst_x, dst_w) = align(dst_x, (new_w - left - right) as u32, canvas_w);
570 let (dst_y, dst_h) = align(dst_y, (new_h - top - bottom) as u32, canvas_h);
571
572 // The same fraction trimmed off `src`, on the matching side: uniform
573 // scale means the ratio of trimmed-box-pixels to source-pixels is the
574 // same on both axes as the ratio of the box's own size to `src`'s.
575 let src_left = i64::from(src.w) * left / new_w;
576 let src_right = i64::from(src.w) * right / new_w;
577 let src_top = i64::from(src.h) * top / new_h;
578 let src_bottom = i64::from(src.h) * bottom / new_h;
579 let src_x = src.x + src_left as u32;
580 let src_y = src.y + src_top as u32;
581 let (src_x, src_w_) = align(
582 src_x,
583 src.w.saturating_sub((src_left + src_right) as u32),
584 src_w,
585 );
586 let (src_y, src_h_) = align(
587 src_y,
588 src.h.saturating_sub((src_top + src_bottom) as u32),
589 src_h,
590 );
591
592 (
593 Rect {
594 x: dst_x,
595 y: dst_y,
596 w: dst_w,
597 h: dst_h,
598 },
599 Rect {
600 x: src_x,
601 y: src_y,
602 w: src_w_,
603 h: src_h_,
604 },
605 )
606}
607
608/// Nearest 90-degree step `degrees` renders at: `0` (0deg), `1` (90deg
609/// clockwise), `2` (180deg) or `3` (270deg). Continuous rotation is not
610/// rendered at all -- see the [`crate::transform`] module docs -- so this is
611/// the one lossy step between what a project *stores* and what a frame
612/// *shows*. Non-finite folds to `0`.
613pub fn nearest_90_steps(degrees: f32) -> u8 {
614 if !degrees.is_finite() {
615 return 0;
616 }
617 let norm = degrees.rem_euclid(360.0);
618 ((norm / 90.0).round() as i64).rem_euclid(4) as u8
619}
620
621/// Rotates a tightly packed I420 frame by `steps` quarter turns clockwise
622/// (`steps % 4`; see [`nearest_90_steps`]). `0` and `2` keep the frame's
623/// shape, `1` and `3` swap it -- the chroma planes rotate the same way at
624/// their own `(w+1)/2` x `(h+1)/2` size, which stays exact because it is
625/// exactly the luma size's, swapped the same way.
626pub fn rotate_i420_90s<T: Sample>(
627 y: &[T],
628 u: &[T],
629 v: &[T],
630 w: u32,
631 h: u32,
632 steps: u8,
633) -> (Vec<T>, Vec<T>, Vec<T>, u32, u32) {
634 let mut out = (Vec::new(), Vec::new(), Vec::new());
635 let (rw, rh) = rotate_i420_90s_into(y, u, v, w, h, steps, &mut out);
636 (out.0, out.1, out.2, rw, rh)
637}
638
639/// [`rotate_i420_90s`] into a caller's own buffers: the top-left of a phone
640/// file's display matrix has to be made on **every decoded frame**, so the
641/// three plane allocations are a steady-state cost to pay once rather than a
642/// per-frame one. The output is exactly what the allocating form returns; the
643/// scratch tuple is resized and refilled, never appended to.
644pub fn rotate_i420_90s_into<T: Sample>(
645 y: &[T],
646 u: &[T],
647 v: &[T],
648 w: u32,
649 h: u32,
650 steps: u8,
651 out: &mut (Vec<T>, Vec<T>, Vec<T>),
652) -> (u32, u32) {
653 let steps = steps % 4;
654 if steps == 0 || w == 0 || h == 0 {
655 out.0.clear();
656 out.0.extend_from_slice(y);
657 out.1.clear();
658 out.1.extend_from_slice(u);
659 out.2.clear();
660 out.2.extend_from_slice(v);
661 return (w, h);
662 }
663 let (cw, ch) = chroma_dims(w as usize, h as usize);
664 rotate_plane_into(y, w as usize, h as usize, steps, &mut out.0);
665 rotate_plane_into(u, cw, ch, steps, &mut out.1);
666 rotate_plane_into(v, cw, ch, steps, &mut out.2);
667 if steps == 2 { (w, h) } else { (h, w) }
668}
669
670/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise,
671/// written into `out` -- resized to the turned size, which is the source's
672/// swapped at 90 and 270 and its own at 180.
673fn rotate_plane_into<T: Sample>(src: &[T], w: usize, h: usize, steps: u8, out: &mut Vec<T>) {
674 match steps {
675 1 => {
676 out.resize(h * w, T::default());
677 for yp in 0..w {
678 for xp in 0..h {
679 out[yp * h + xp] = src[(h - 1 - xp) * w + yp];
680 }
681 }
682 }
683 2 => {
684 out.resize(w * h, T::default());
685 for yp in 0..h {
686 for xp in 0..w {
687 out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)];
688 }
689 }
690 }
691 3 => {
692 out.resize(h * w, T::default());
693 for yp in 0..w {
694 for xp in 0..h {
695 out[yp * h + xp] = src[xp * w + (w - 1 - yp)];
696 }
697 }
698 }
699 _ => unreachable!("steps % 4 is 1, 2 or 3 here"),
700 }
701}
702
703/// One clip's pictures placed on the project canvas: the geometry, plus the
704/// buffers it composes into so a frame costs no allocation.
705///
706/// This is the *one* definition of what a mixed-resolution timeline looks like:
707/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
708/// decoded planes to [`place`](Composer::place), so what is watched and what is
709/// written cannot drift apart.
710///
711/// **Order against the colour grade: grade first, place second.** A grade
712/// belongs to the clip's own pixels -- it is graded at the resolution it was
713/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
714/// letterbox bars are *not* the clip: a brightness grade that reached them would
715/// lift the black frame around the picture. Callers therefore grade the source
716/// planes and place the result; the bars stay exactly [`black_i420`].
717///
718/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of
719/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a
720/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at
721/// 4096x2160 (the floor), all measured. A worker holds one more than this in its
722/// hand, so a burst off a full queue is `queue_depth + 1`.
723///
724/// The floor of 2 is the bound this engine ran on everywhere before there was
725/// any decode-ahead; the ceiling keeps a small picture from queueing a second of
726/// video the consumer would have to walk through after a seek.
727pub(crate) fn queue_depth(width: u32, height: u32) -> usize {
728 const BUDGET: usize = 96 << 20;
729 let bytes = width as usize * height as usize * 4;
730 if bytes == 0 {
731 return 2;
732 }
733 (BUDGET / bytes).clamp(2, 16)
734}
735
736/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
737/// hands the caller's own planes straight back, allocates nothing and touches no
738/// byte, which is what keeps a project at its media's resolution the byte-for-byte
739/// path it was before there was a project resolution at all.
740///
741/// [`place`]: Composer::place
742pub struct Composer {
743 width: u32,
744 height: u32,
745 policy: FitPolicy,
746 /// The 8-bit buffers that [`place`](Composer::place) works in.
747 narrow: Scratch<u8>,
748 /// The 10-bit buffers of [`place_wide`](Composer::place_wide).
749 wide: Scratch<u16>,
750}
751
752/// The three planes of an I420 picture at one sample type.
753type Triple<T> = (Vec<T>, Vec<T>, Vec<T>);
754
755/// One sample type's buffers for a [`Composer`]: the `src` rect of [`fit_rect`],
756/// gathered tightly packed (only `Fill` and `Center` ever crop, so it stays empty
757/// for a letterboxed project); the crop resampled to the placement rect; and the
758/// canvas itself, refilled with black every frame.
759#[derive(Default)]
760struct Scratch<T> {
761 crop: Triple<T>,
762 scaled: Triple<T>,
763 canvas: Triple<T>,
764}
765
766impl Composer {
767 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
768 Self {
769 width,
770 height,
771 policy,
772 narrow: Scratch::default(),
773 wide: Scratch::default(),
774 }
775 }
776
777 /// A composer with the same canvas and fit as this one and none of its scratch:
778 /// what a second decode of the same clip is placed with.
779 pub(crate) fn fresh(&self) -> Self {
780 Self::new(self.width, self.height, self.policy)
781 }
782
783 /// A composer that places nothing: every picture passes through at its own
784 /// size. What the file-level decode API opens with, where there is no
785 /// project and therefore no canvas.
786 pub fn passthrough() -> Self {
787 Self::new(0, 0, FitPolicy::Fit)
788 }
789
790 /// Whether this canvas is the one that places nothing
791 /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand,
792 /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that
793 /// needs it is sizing a queue before anything has been decoded.
794 pub(crate) fn places_nothing(&self) -> bool {
795 self.width == 0 || self.height == 0
796 }
797
798 /// The canvas this composer places onto, for the painter that fills it
799 /// directly at this size -- a picture authored at the canvas's own
800 /// dimensions takes the pass-through path [`is_passthrough`](Self::is_passthrough)
801 /// answers for, and it needs the numbers before there is a picture.
802 pub(crate) fn dims(&self) -> (u32, u32) {
803 (self.width, self.height)
804 }
805
806 /// How many decoded pictures a worker over this canvas may keep ahead of
807 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
808 /// than a 1080p one instead of the same number of far bigger frames.
809 ///
810 /// A **pass-through** canvas has no size of its own -- the pictures come out
811 /// at the source's -- so it cannot answer, and the caller that knows the
812 /// stream asks [`queue_depth`] with those dimensions instead. Answering 2
813 /// here would be the pre-decode-ahead bound, which is exactly the bug this
814 /// pair exists to keep out of the file-open path.
815 pub(crate) fn queue_depth(&self) -> usize {
816 queue_depth(self.width, self.height)
817 }
818
819 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
820 /// composer would hand it back untouched. What lets a caller keep a fused
821 /// fast path (the graded conversion) for the common case.
822 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
823 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
824 }
825
826 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
827 /// caller's own planes (pass-through) or the canvas with the fitted picture
828 /// composed onto it. The dimensions come back because those two differ.
829 ///
830 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
831 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
832 pub fn place<'a>(
833 &'a mut self,
834 y: &'a [u8],
835 u: &'a [u8],
836 v: &'a [u8],
837 src_w: u32,
838 src_h: u32,
839 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
840 if self.is_passthrough(src_w, src_h) {
841 return (y, u, v, src_w, src_h);
842 }
843 place_in(self.width, self.height, self.policy, &mut self.narrow, y, u, v, src_w, src_h)
844 }
845
846 /// [`place`](Self::place) for a picture at 10 bits a sample: the same fit, the
847 /// same canvas, black at 64 and 512, composed at 10 bits.
848 pub fn place_wide<'a>(
849 &'a mut self,
850 y: &'a [u16],
851 u: &'a [u16],
852 v: &'a [u16],
853 src_w: u32,
854 src_h: u32,
855 ) -> (&'a [u16], &'a [u16], &'a [u16], u32, u32) {
856 if self.is_passthrough(src_w, src_h) {
857 return (y, u, v, src_w, src_h);
858 }
859 place_in(self.width, self.height, self.policy, &mut self.wide, y, u, v, src_w, src_h)
860 }
861
862 /// [`place`](Self::place) with a per-clip [`TransformParams`] applied on
863 /// top of the fit policy: the source is cropped to [`crop_rect`], rotated
864 /// by [`rotate_i420_90s`] to [`nearest_90_steps`] of `t.rotate`, fit to the
865 /// canvas exactly as an untransformed picture is, and the fitted
866 /// placement is then moved/resized/clipped by [`transformed_dst_rect`],
867 /// which also trims the matching slice off the source rect so an
868 /// off-canvas move clips instead of squeezing.
869 /// `t.is_identity()` takes the exact [`place`](Self::place) path.
870 ///
871 /// corner-cut: unlike `place`, this always allocates its crop and rotate
872 /// buffers fresh rather than reusing `self`'s -- the grade path already
873 /// pays the same per-frame cost for a graded clip
874 /// ([`crate::decode::Render::frame`]'s `graded` copy), so a transformed
875 /// clip follows that precedent instead of adding a second steady-state
876 /// buffer budget. Upgrade path if this shows up in a measurement: give
877 /// `Composer` its own crop/rotate scratch fields, sized once like `crop`
878 /// and `scaled` already are.
879 pub fn place_transformed(
880 &mut self,
881 y: &[u8],
882 u: &[u8],
883 v: &[u8],
884 src_w: u32,
885 src_h: u32,
886 t: &TransformParams,
887 ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
888 if t.is_identity() {
889 let (y, u, v, w, h) = self.place(y, u, v, src_w, src_h);
890 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
891 }
892 transform_in(self.width, self.height, self.policy, y, u, v, src_w, src_h, t)
893 }
894
895 /// [`place_transformed`](Self::place_transformed) for a 10-bit picture.
896 pub fn place_transformed_wide(
897 &mut self,
898 y: &[u16],
899 u: &[u16],
900 v: &[u16],
901 src_w: u32,
902 src_h: u32,
903 t: &TransformParams,
904 ) -> (Vec<u16>, Vec<u16>, Vec<u16>, u32, u32) {
905 if t.is_identity() {
906 let (y, u, v, w, h) = self.place_wide(y, u, v, src_w, src_h);
907 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
908 }
909 transform_in(self.width, self.height, self.policy, y, u, v, src_w, src_h, t)
910 }
911}
912
913/// [`Composer::place`] at one sample type: the picture fitted onto a `width` x
914/// `height` canvas under `policy`, the canvas and its scratch in `s`.
915#[allow(clippy::too_many_arguments)]
916fn place_in<'a, T: Sample>(
917 width: u32,
918 height: u32,
919 policy: FitPolicy,
920 s: &'a mut Scratch<T>,
921 y: &'a [T],
922 u: &'a [T],
923 v: &'a [T],
924 src_w: u32,
925 src_h: u32,
926) -> (&'a [T], &'a [T], &'a [T], u32, u32) {
927 let (dst, src) = fit_rect(src_w, src_h, width, height, policy);
928 let (sw, sh) = (src_w as usize, src_h as usize);
929
930 // Crop first, so the scaler only ever sees a tightly packed plane. Fit and
931 // Stretch never crop, which is the whole cost of the common case.
932 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
933 (y, u, v)
934 } else {
935 crop_i420(&mut s.crop, y, u, v, sw, sh, src);
936 (&s.crop.0[..], &s.crop.1[..], &s.crop.2[..])
937 };
938 // ...then resample it to the placement, unless it already is that size.
939 let (cw, ch) = (src.w as usize, src.h as usize);
940 let (dw, dh) = (dst.w as usize, dst.h as usize);
941 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
942 (src_y, src_u, src_v)
943 } else {
944 let (ccw, cch) = chroma_dims(dw, dh);
945 let (sy, su, sv) = &mut s.scaled;
946 sy.resize(dw * dh, T::default());
947 su.resize(ccw * cch, T::default());
948 sv.resize(ccw * cch, T::default());
949 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
950 (&sy[..], &su[..], &sv[..])
951 };
952
953 let (w, h) = (width as usize, height as usize);
954 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
955 let (ky, ku, kv) = &mut s.canvas;
956 fill(ky, w * h, T::BLACK);
957 fill(ku, canvas_cw * canvas_ch, T::NEUTRAL);
958 fill(kv, canvas_cw * canvas_ch, T::NEUTRAL);
959 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
960 (ky, ku, kv, width, height)
961}
962
963/// [`Composer::place_transformed`] at one sample type, for a picture that is not
964/// the identity transform. The canvas is the picture's own size on a pass-through
965/// composer.
966#[allow(clippy::too_many_arguments)]
967fn transform_in<T: Sample>(
968 width: u32,
969 height: u32,
970 policy: FitPolicy,
971 y: &[T],
972 u: &[T],
973 v: &[T],
974 src_w: u32,
975 src_h: u32,
976 t: &TransformParams,
977) -> (Vec<T>, Vec<T>, Vec<T>, u32, u32) {
978 // A pass-through canvas still has a picture to place a transform on; treat it
979 // as a canvas the exact size of the incoming picture.
980 let (canvas_w, canvas_h) = if width == 0 || height == 0 {
981 (src_w, src_h)
982 } else {
983 (width, height)
984 };
985
986 let crop = crop_rect(src_w, src_h, t);
987 let mut buf1 = (Vec::new(), Vec::new(), Vec::new());
988 let (cy, cu, cv) = if (crop.w, crop.h) == (src_w, src_h) {
989 (y, u, v)
990 } else {
991 crop_i420(&mut buf1, y, u, v, src_w as usize, src_h as usize, crop);
992 (&buf1.0[..], &buf1.1[..], &buf1.2[..])
993 };
994
995 // No rotation is the overwhelmingly common case (a move or a scale, never a
996 // quarter turn): `rotate_i420_90s` always copies its picture, so that copy is
997 // skipped when there is nothing to turn.
998 let steps = nearest_90_steps(t.rotate);
999 let rot_buf;
1000 let (ry, ru, rv, rw, rh) = if steps == 0 {
1001 (cy, cu, cv, crop.w, crop.h)
1002 } else {
1003 rot_buf = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);
1004 (&rot_buf.0[..], &rot_buf.1[..], &rot_buf.2[..], rot_buf.3, rot_buf.4)
1005 };
1006
1007 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, policy);
1008 let (dst, src) = transformed_dst_rect(dst, src, rw, rh, t, canvas_w, canvas_h);
1009 let (rw_u, rh_u) = (rw as usize, rh as usize);
1010 let mut buf2 = (Vec::new(), Vec::new(), Vec::new());
1011 let (fy, fu, fv) = if (src.w, src.h) == (rw, rh) {
1012 (ry, ru, rv)
1013 } else {
1014 crop_i420(&mut buf2, ry, ru, rv, rw_u, rh_u, src);
1015 (&buf2.0[..], &buf2.1[..], &buf2.2[..])
1016 };
1017
1018 let (sw, sh) = (src.w as usize, src.h as usize);
1019 let (dw, dh) = (dst.w as usize, dst.h as usize);
1020 let mut scaled = (Vec::new(), Vec::new(), Vec::new());
1021 let (py, pu, pv) = if (sw, sh) == (dw, dh) {
1022 (fy, fu, fv)
1023 } else {
1024 let (ccw, cch) = chroma_dims(dw, dh);
1025 scaled.0.resize(dw * dh, T::default());
1026 scaled.1.resize(ccw * cch, T::default());
1027 scaled.2.resize(ccw * cch, T::default());
1028 scale_i420(fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh);
1029 (&scaled.0[..], &scaled.1[..], &scaled.2[..])
1030 };
1031
1032 let (w, h) = (canvas_w as usize, canvas_h as usize);
1033 let mut canvas = black_planes::<T>(w, h);
1034 compose_i420(&mut canvas.0, &mut canvas.1, &mut canvas.2, w, h, py, pu, pv, dst);
1035 // A single clip's opacity is its fade toward the black canvas it sits on.
1036 // Layers above a picture take it as their coverage instead (see
1037 // `export::LayerStack`), so they are placed with opacity 1 there.
1038 if t.opacity < 1.0 {
1039 fade_canvas_to_black(&mut canvas, t.opacity.max(0.0));
1040 }
1041 (canvas.0, canvas.1, canvas.2, canvas_w, canvas_h)
1042}
1043
1044/// Fades an I420 picture drawn on a black canvas toward that black by `k`
1045/// (`0.0` is all black, `1.0` leaves it), per code value: luma toward black,
1046/// chroma toward neutral, rounded to the nearest code.
1047pub fn fade_canvas_to_black<T: Sample>(planes: &mut (Vec<T>, Vec<T>, Vec<T>), k: f32) {
1048 let k = k.clamp(0.0, 1.0);
1049 let toward = |plane: &mut [T], black: T| {
1050 for p in plane {
1051 let v = black.code() as f32 + (p.code() as f32 - black.code() as f32) * k;
1052 *p = T::from_f32(v);
1053 }
1054 };
1055 toward(&mut planes.0, T::BLACK);
1056 toward(&mut planes.1, T::NEUTRAL);
1057 toward(&mut planes.2, T::NEUTRAL);
1058}
1059
1060/// Per-code lerp of two same-sized I420 frames: `out = a + (b - a) * t`, on
1061/// every plane. `t` is clamped to `[0, 1]`. A mismatched pair panics rather than
1062/// silently truncating a picture.
1063pub fn blend_i420<T: Sample>(
1064 a: (&[T], &[T], &[T]),
1065 b: (&[T], &[T], &[T]),
1066 t: f32,
1067) -> (Vec<T>, Vec<T>, Vec<T>) {
1068 let t = t.clamp(0.0, 1.0);
1069 let plane = |a: &[T], b: &[T]| -> Vec<T> {
1070 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");
1071 a.iter()
1072 .zip(b)
1073 .map(|(&av, &bv)| {
1074 let (av, bv) = (av.code() as f32, bv.code() as f32);
1075 T::from_f32(av + (bv - av) * t)
1076 })
1077 .collect()
1078 };
1079 (plane(a.0, b.0), plane(a.1, b.1), plane(a.2, b.2))
1080}
1081
1082/// Resizes `plane` to `len` and sets every code to `value` -- a canvas reused
1083/// across frames is refilled, not reallocated.
1084fn fill<T: Sample>(plane: &mut Vec<T>, len: usize, value: T) {
1085 plane.clear();
1086 plane.resize(len, value);
1087}
1088
1089/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
1090/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
1091/// crop is exactly half of it.
1092fn crop_i420<T: Sample>(
1093 out: &mut (Vec<T>, Vec<T>, Vec<T>),
1094 y: &[T],
1095 u: &[T],
1096 v: &[T],
1097 src_w: usize,
1098 src_h: usize,
1099 rect: Rect,
1100) {
1101 let (w, h) = (rect.w as usize, rect.h as usize);
1102 let (x, cy0) = (rect.x as usize, rect.y as usize);
1103 let (src_cw, _) = chroma_dims(src_w, src_h);
1104 let (cw, ch) = chroma_dims(w, h);
1105 let (oy, ou, ov) = out;
1106 oy.clear();
1107 ou.clear();
1108 ov.clear();
1109 for row in 0..h {
1110 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
1111 }
1112 let (cx, cy0) = (x / 2, cy0 / 2);
1113 for row in 0..ch {
1114 let at = (cy0 + row) * src_cw + cx;
1115 ou.extend_from_slice(&u[at..][..cw]);
1116 ov.extend_from_slice(&v[at..][..cw]);
1117 }
1118 debug_assert_eq!(oy.len(), w * h);
1119 debug_assert_eq!(ou.len(), cw * ch);
1120}
1121
1122/// Where a clip's picture lands on the canvas, worked out once from the same
1123/// helpers [`transform_in`] composes with: the crop, the quarter turn, the fit and
1124/// the placement's own move, scale and fit-crop.
1125struct Placed {
1126 crop: Rect,
1127 steps: u8,
1128 dst: Rect,
1129 src: Rect,
1130}
1131
1132fn placed(src: (u32, u32), t: &TransformParams, canvas: (u32, u32), fit: FitPolicy) -> Placed {
1133 let crop = crop_rect(src.0, src.1, t);
1134 let steps = nearest_90_steps(t.rotate) % 4;
1135 let (rw, rh) = if steps % 2 == 1 { (crop.h, crop.w) } else { (crop.w, crop.h) };
1136 let (dst, srcr) = fit_rect(rw, rh, canvas.0.max(1), canvas.1.max(1), fit);
1137 let (dst, srcr) = transformed_dst_rect(dst, srcr, rw, rh, t, canvas.0.max(1), canvas.1.max(1));
1138 Placed { crop, steps, dst, src: srcr }
1139}
1140
1141/// A point of the clip's source picture, in picture fractions (`0..=1` each), mapped
1142/// to where it shows on the canvas, in canvas fractions, under the placement `t`:
1143/// the inverse of [`canvas_to_picture`]. `src` is the picture's own size. A placement
1144/// that shows nothing returns the point unchanged.
1145pub fn picture_to_canvas(
1146 src: (u32, u32),
1147 t: &TransformParams,
1148 canvas: (u32, u32),
1149 fit: FitPolicy,
1150 p: (f32, f32),
1151) -> (f32, f32) {
1152 let pl = placed(src, t, canvas, fit);
1153 if pl.dst.is_empty() || pl.src.is_empty() || src.0 == 0 || src.1 == 0 {
1154 return p;
1155 }
1156 let (cw, ch) = (f64::from(pl.crop.w), f64::from(pl.crop.h));
1157 let x = f64::from(p.0) * f64::from(src.0) - f64::from(pl.crop.x);
1158 let y = f64::from(p.1) * f64::from(src.1) - f64::from(pl.crop.y);
1159 let (qx, qy) = match pl.steps {
1160 0 => (x, y),
1161 1 => (ch - y, x),
1162 2 => (cw - x, ch - y),
1163 _ => (y, cw - x),
1164 };
1165 let sx = f64::from(pl.dst.w) / f64::from(pl.src.w);
1166 let sy = f64::from(pl.dst.h) / f64::from(pl.src.h);
1167 let cx = f64::from(pl.dst.x) + (qx - f64::from(pl.src.x)) * sx;
1168 let cy = f64::from(pl.dst.y) + (qy - f64::from(pl.src.y)) * sy;
1169 ((cx / f64::from(canvas.0.max(1))) as f32, (cy / f64::from(canvas.1.max(1))) as f32)
1170}
1171
1172/// A canvas point (canvas fractions) mapped back to the clip's source picture, in
1173/// picture fractions: the inverse of [`picture_to_canvas`]. A point off the placed
1174/// picture comes back outside `0..=1`.
1175pub fn canvas_to_picture(
1176 src: (u32, u32),
1177 t: &TransformParams,
1178 canvas: (u32, u32),
1179 fit: FitPolicy,
1180 c: (f32, f32),
1181) -> (f32, f32) {
1182 let pl = placed(src, t, canvas, fit);
1183 if pl.dst.is_empty() || pl.src.is_empty() || src.0 == 0 || src.1 == 0 {
1184 return c;
1185 }
1186 let (cw, ch) = (f64::from(pl.crop.w), f64::from(pl.crop.h));
1187 let sx = f64::from(pl.dst.w) / f64::from(pl.src.w);
1188 let sy = f64::from(pl.dst.h) / f64::from(pl.src.h);
1189 let qx = f64::from(pl.src.x) + (f64::from(c.0) * f64::from(canvas.0.max(1)) - f64::from(pl.dst.x)) / sx;
1190 let qy = f64::from(pl.src.y) + (f64::from(c.1) * f64::from(canvas.1.max(1)) - f64::from(pl.dst.y)) / sy;
1191 let (x, y) = match pl.steps {
1192 0 => (qx, qy),
1193 1 => (qy, ch - qx),
1194 2 => (cw - qx, ch - qy),
1195 _ => (cw - qy, qx),
1196 };
1197 (((x + f64::from(pl.crop.x)) / f64::from(src.0)) as f32, ((y + f64::from(pl.crop.y)) / f64::from(src.1)) as f32)
1198}
1199
1200#[cfg(test)]
1201mod tests {
1202 use super::*;
1203
1204 /// Allocates the destination planes for a size and runs a scale into them.
1205 fn scaled(
1206 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
1207 src_w: usize,
1208 src_h: usize,
1209 dst_w: usize,
1210 dst_h: usize,
1211 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1212 let (cw, ch) = chroma_dims(dst_w, dst_h);
1213 let mut dst = (
1214 vec![0u8; dst_w * dst_h],
1215 vec![0u8; cw * ch],
1216 vec![0u8; cw * ch],
1217 );
1218 scale_i420(
1219 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
1220 );
1221 dst
1222 }
1223
1224 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1225 let (cw, ch) = chroma_dims(w, h);
1226 (
1227 (0..w * h).map(|i| (i % 256) as u8).collect(),
1228 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
1229 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
1230 )
1231 }
1232
1233 /// The pass-through invariant: a project at the media's own resolution must
1234 /// hand the decoder's bytes to the encoder unchanged.
1235 #[test]
1236 fn identity_scale_is_byte_identical() {
1237 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
1238 let src = gradient(w, h);
1239 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
1240 }
1241 }
1242
1243 /// Halving is the one case where bilinear is exactly a 2x2 box average:
1244 /// the output centre falls on the shared corner of four input samples.
1245 /// 0/254 averages to 127 with no rounding slack at all.
1246 #[test]
1247 fn downscale_by_two_averages_a_checkerboard() {
1248 let (w, h) = (32, 24);
1249 let (cw, ch) = chroma_dims(w, h);
1250 let checker = |i: usize, stride: usize| {
1251 if (i / stride + i % stride).is_multiple_of(2) {
1252 0u8
1253 } else {
1254 254
1255 }
1256 };
1257 let src = (
1258 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
1259 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
1260 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
1261 );
1262 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
1263 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
1264 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
1265 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
1266 }
1267
1268 /// Nothing may leak in from outside a plane: a flat frame stays flat at
1269 /// every edge, upscaled and downscaled, odd sizes included.
1270 #[test]
1271 fn flat_frame_stays_flat() {
1272 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
1273 for &(sw, sh) in &sizes {
1274 let (cw, ch) = chroma_dims(sw, sh);
1275 let src = (
1276 vec![80u8; sw * sh],
1277 vec![90u8; cw * ch],
1278 vec![200u8; cw * ch],
1279 );
1280 for &(dw, dh) in &sizes {
1281 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
1282 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
1283 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
1284 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
1285 }
1286 }
1287 }
1288
1289 /// Chroma alignment: an edge in the U plane must land at the *same* place
1290 /// after a 2x upscale, with a symmetric two-sample blend around it and
1291 /// untouched flats either side -- a half-sample bias shows up as an
1292 /// asymmetric pair here, which is colour bleeding one way.
1293 #[test]
1294 fn chroma_edge_keeps_its_position() {
1295 let (w, h) = (8, 8);
1296 let (cw, ch) = chroma_dims(w, h);
1297 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
1298 let src = (
1299 vec![80u8; w * h],
1300 (0..cw * ch)
1301 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
1302 .collect(),
1303 vec![128u8; cw * ch],
1304 );
1305 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
1306 let (dcw, _) = chroma_dims(w * 2, h * 2);
1307 assert_eq!(dcw, 8);
1308 let row = &u[dcw * 3..][..dcw];
1309 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
1310 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
1311 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
1312 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
1313 // most 1; anything further means the edge moved.
1314 assert!(
1315 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
1316 "blend is off centre, i.e. chroma bled one way: {row:?}"
1317 );
1318 }
1319
1320 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
1321 /// `(src, dst, policy) -> (placement, crop)`.
1322 #[test]
1323 fn fit_rect_table() {
1324 let r = |x, y, w, h| Rect { x, y, w, h };
1325 let cases = [
1326 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
1327 (
1328 (1920, 1080),
1329 (640, 480),
1330 FitPolicy::Fit,
1331 r(0, 60, 640, 360),
1332 r(0, 0, 1920, 1080),
1333 ),
1334 // ...and the same pair filled: the canvas is whole, the source is
1335 // cropped to 4:3 (1440 wide) about its centre.
1336 (
1337 (1920, 1080),
1338 (640, 480),
1339 FitPolicy::Fill,
1340 r(0, 0, 640, 480),
1341 r(240, 0, 1440, 1080),
1342 ),
1343 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
1344 (
1345 (640, 480),
1346 (1920, 1080),
1347 FitPolicy::Fit,
1348 r(240, 0, 1440, 1080),
1349 r(0, 0, 640, 480),
1350 ),
1351 (
1352 (640, 480),
1353 (1920, 1080),
1354 FitPolicy::Fill,
1355 r(0, 0, 1920, 1080),
1356 r(0, 60, 640, 360),
1357 ),
1358 // Stretch ignores aspect entirely, both ways.
1359 (
1360 (1920, 1080),
1361 (640, 480),
1362 FitPolicy::Stretch,
1363 r(0, 0, 640, 480),
1364 r(0, 0, 1920, 1080),
1365 ),
1366 // 1:1 with a bigger source: cropped both ways, centred.
1367 (
1368 (1920, 1080),
1369 (640, 480),
1370 FitPolicy::Center,
1371 r(0, 0, 640, 480),
1372 r(640, 300, 640, 480),
1373 ),
1374 // 1:1 with a smaller source: padded both ways, centred.
1375 (
1376 (640, 480),
1377 (1920, 1080),
1378 FitPolicy::Center,
1379 r(640, 300, 640, 480),
1380 r(0, 0, 640, 480),
1381 ),
1382 // Odd sizes: offsets even, sizes even unless they reach the edge.
1383 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
1384 (
1385 (7, 5),
1386 (13, 9),
1387 FitPolicy::Fit,
1388 r(0, 0, 13, 9),
1389 r(0, 0, 7, 5),
1390 ),
1391 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
1392 // offset without putting chroma half a sample off, so the last one
1393 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
1394 (
1395 (9, 9),
1396 (13, 9),
1397 FitPolicy::Center,
1398 r(2, 0, 8, 9),
1399 r(0, 0, 8, 9),
1400 ),
1401 (
1402 (13, 9),
1403 (9, 9),
1404 FitPolicy::Center,
1405 r(0, 0, 8, 9),
1406 r(2, 0, 8, 9),
1407 ),
1408 ];
1409 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
1410 let got = fit_rect(sw, sh, dw, dh, policy);
1411 assert_eq!(
1412 got,
1413 (want_dst, want_src),
1414 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
1415 );
1416 }
1417 // Degenerate input is empty, not a panic.
1418 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
1419 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
1420 }
1421
1422 /// Every rect a policy hands back must sit inside its plane, start on the
1423 /// chroma grid, and end on it or at the plane edge -- the invariant
1424 /// `compose_i420` relies on.
1425 #[test]
1426 fn fit_rect_stays_on_the_chroma_grid() {
1427 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
1428 for policy in [
1429 FitPolicy::Fit,
1430 FitPolicy::Fill,
1431 FitPolicy::Stretch,
1432 FitPolicy::Center,
1433 ] {
1434 for &sw in &sizes {
1435 for &dh in &sizes {
1436 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
1437 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
1438 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
1439 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
1440 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
1441 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
1442 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
1443 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
1444 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
1445 // A plane one sample wide or high has no chroma grid to
1446 // be on: `Center` from a 2-high source onto a 1-high
1447 // canvas is one row, and no size satisfies both edges.
1448 // Nothing real is that shape; it must merely not
1449 // escape its plane, which the two asserts above cover.
1450 if grid {
1451 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
1452 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
1453 }
1454 assert!(!rect.is_empty(), "{ctx} empty");
1455 }
1456 }
1457 }
1458 }
1459 }
1460
1461 #[test]
1462 fn compose_fills_the_rect_and_nothing_else() {
1463 let (cw2, ch2) = (640usize, 360usize);
1464 let (canvas_w, canvas_h) = (640usize, 480usize);
1465 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
1466 let (fcw, fch) = chroma_dims(cw2, ch2);
1467 let frame = (
1468 vec![200u8; cw2 * ch2],
1469 vec![70u8; fcw * fch],
1470 vec![30u8; fcw * fch],
1471 );
1472 let rect = Rect {
1473 x: 0,
1474 y: 60,
1475 w: cw2 as u32,
1476 h: ch2 as u32,
1477 };
1478 compose_i420(
1479 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
1480 );
1481
1482 for row in 0..canvas_h {
1483 let inside = (60..420).contains(&row);
1484 let want = if inside { 200 } else { BLACK_Y };
1485 assert!(
1486 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
1487 "luma row {row}"
1488 );
1489 }
1490 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
1491 for row in 0..cch {
1492 let inside = (30..210).contains(&row);
1493 let (wu, wv) = if inside {
1494 (70, 30)
1495 } else {
1496 (NEUTRAL_C, NEUTRAL_C)
1497 };
1498 assert!(
1499 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
1500 "U row {row}"
1501 );
1502 assert!(
1503 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
1504 "V row {row}"
1505 );
1506 }
1507 }
1508
1509 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
1510 /// is public and a caller may compute a rect itself.
1511 #[test]
1512 fn compose_clips_a_rect_that_runs_off_the_canvas() {
1513 let (mut y, mut u, mut v) = black_i420(16, 16);
1514 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
1515 let rect = Rect {
1516 x: 12,
1517 y: 12,
1518 w: 8,
1519 h: 8,
1520 };
1521 compose_i420(
1522 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
1523 );
1524 assert_eq!(y[15 * 16 + 15], 99);
1525 assert_eq!(y[11 * 16 + 15], BLACK_Y);
1526 // Wholly outside: no write at all.
1527 let before = y.clone();
1528 compose_i420(
1529 &mut y,
1530 &mut u,
1531 &mut v,
1532 16,
1533 16,
1534 &frame.0,
1535 &frame.1,
1536 &frame.2,
1537 Rect {
1538 x: 100,
1539 y: 0,
1540 w: 8,
1541 h: 8,
1542 },
1543 );
1544 assert_eq!(y, before);
1545 }
1546
1547 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
1548 /// project canvas, letterbox bars intact.
1549 #[test]
1550 fn fit_scale_compose_letterboxes() {
1551 let (sw, sh) = (640usize, 480usize);
1552 let (dw, dh) = (1920usize, 1080usize);
1553 let src = gradient(sw, sh);
1554 let (dst_rect, src_rect) =
1555 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
1556 assert_eq!(
1557 src_rect,
1558 Rect {
1559 x: 0,
1560 y: 0,
1561 w: 640,
1562 h: 480
1563 }
1564 );
1565 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
1566 let picture = scaled(&src, sw, sh, rw, rh);
1567 let (mut y, mut u, mut v) = black_i420(dw, dh);
1568 compose_i420(
1569 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
1570 );
1571 // Pillarbox columns stay black, the picture area does not.
1572 let mid = (dh / 2) * dw;
1573 assert!(
1574 y[mid..mid + dst_rect.x as usize]
1575 .iter()
1576 .all(|&s| s == BLACK_Y)
1577 );
1578 assert_eq!(
1579 y[mid + dst_rect.x as usize..][..rw],
1580 picture.0[(rh / 2) * rw..][..rw]
1581 );
1582 }
1583
1584 /// The wiring invariant: a project at its media's own resolution hands the
1585 /// decoder's own slices back, not a copy that happens to be equal. Asserted
1586 /// on the pointer, because "identical bytes" is cheap and "no work at all"
1587 /// is what the common case is promised.
1588 #[test]
1589 fn a_canvas_of_the_source_size_is_a_pass_through() {
1590 let (w, h) = (64usize, 48usize);
1591 let src = gradient(w, h);
1592 for mut canvas in [
1593 Composer::new(w as u32, h as u32, FitPolicy::Fit),
1594 Composer::new(w as u32, h as u32, FitPolicy::Fill),
1595 Composer::new(w as u32, h as u32, FitPolicy::Center),
1596 Composer::passthrough(),
1597 ] {
1598 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
1599 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
1600 assert_eq!(u.as_ptr(), src.1.as_ptr());
1601 assert_eq!(v.as_ptr(), src.2.as_ptr());
1602 assert_eq!((cw, ch), (w as u32, h as u32));
1603 }
1604 }
1605
1606 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
1607 /// the pillarbox columns are limited-range black, exactly -- a bar that is
1608 /// merely dark is a bar the grade reached.
1609 #[test]
1610 fn fit_pillarboxes_with_exact_black_bars() {
1611 let (sw, sh) = (640u32, 480u32);
1612 let (dw, dh) = (1920u32, 1080u32);
1613 let src = (
1614 vec![200u8; (sw * sh) as usize],
1615 vec![70u8; (sw * sh / 4) as usize],
1616 vec![30u8; (sw * sh / 4) as usize],
1617 );
1618 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
1619 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1620 assert_eq!((w, h), (dw, dh));
1621 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
1622 assert_eq!(
1623 rect,
1624 Rect {
1625 x: 240,
1626 y: 0,
1627 w: 1440,
1628 h: 1080
1629 },
1630 "geometry moved"
1631 );
1632 let (w, h) = (w as usize, h as usize);
1633 let row = &y[(h / 2) * w..][..w];
1634 let x = rect.x as usize;
1635 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
1636 assert!(
1637 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
1638 "right bar not black"
1639 );
1640 assert!(
1641 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
1642 "picture"
1643 );
1644 // ...and the bars are neutral in chroma too, or they would be a colour.
1645 let (cw, _) = chroma_dims(w, h);
1646 let crow = &u[(h / 4) * cw..][..cw];
1647 assert!(
1648 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
1649 "bar has colour"
1650 );
1651 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
1652 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
1653 }
1654
1655 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
1656 /// the canvas (no bar anywhere), `Center` pads without resampling.
1657 #[test]
1658 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
1659 let (sw, sh) = (640u32, 480u32);
1660 let (dw, dh) = (1920u32, 1080u32);
1661 let src = (
1662 vec![200u8; (sw * sh) as usize],
1663 vec![70u8; (sw * sh / 4) as usize],
1664 vec![30u8; (sw * sh / 4) as usize],
1665 );
1666 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
1667 let mut canvas = Composer::new(dw, dh, policy);
1668 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1669 assert!(
1670 y.iter().all(|&s| s == 200),
1671 "{policy:?} left a bar: the canvas is not covered"
1672 );
1673 }
1674 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1675 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1676 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1677 assert_eq!(rect.w, sw, "Center resampled the picture");
1678 let (w, h) = (w as usize, h as usize);
1679 let row = &y[(h / 2) * w..][..w];
1680 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1681 assert!(
1682 row[rect.x as usize..][..sw as usize]
1683 .iter()
1684 .all(|&s| s == 200)
1685 );
1686 }
1687
1688 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1689 /// picture, chroma with it: a marked band at a known column has to come out
1690 /// at the column the geometry puts it at.
1691 #[test]
1692 fn fill_crops_about_the_centre() {
1693 let (sw, sh) = (32usize, 8usize);
1694 let (dw, dh) = (8u32, 8u32);
1695 // Column 16 (the centre) is bright, everything else is dark.
1696 let y: Vec<u8> = (0..sw * sh)
1697 .map(|i| if i % sw == 16 { 240 } else { 40 })
1698 .collect();
1699 let (cw, ch) = chroma_dims(sw, sh);
1700 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1701 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1702 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1703 assert_eq!((w, h), (dw, dh));
1704 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1705 assert_eq!(
1706 dst,
1707 Rect {
1708 x: 0,
1709 y: 0,
1710 w: 8,
1711 h: 8
1712 },
1713 "Fill must cover"
1714 );
1715 assert_eq!(
1716 crop,
1717 Rect {
1718 x: 12,
1719 y: 0,
1720 w: 8,
1721 h: 8
1722 },
1723 "crop off centre"
1724 );
1725 // The bright column is crop-relative column 4 of 8, untouched by the
1726 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1727 let row = &y[..8];
1728 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1729 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1730 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1731 }
1732
1733 /// Not asserted: only the release number means anything. Run with
1734 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1735 #[test]
1736 #[ignore = "perf: run with --ignored"]
1737 fn perf_720p_to_1080p() {
1738 let src = gradient(1280, 720);
1739 let (cw, ch) = chroma_dims(1920, 1080);
1740 let mut dst = (
1741 vec![0u8; 1920 * 1080],
1742 vec![0u8; cw * ch],
1743 vec![0u8; cw * ch],
1744 );
1745 let runs = 30;
1746 let t = std::time::Instant::now();
1747 for _ in 0..runs {
1748 scale_i420(
1749 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1750 );
1751 }
1752 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1753 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1754 }
1755
1756 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1757 /// scale and blit -- which is what the playback budget has to hold. Printed,
1758 /// not asserted, like every other perf test here.
1759 #[test]
1760 #[ignore = "perf: run with --ignored"]
1761 fn perf_compose_720p_onto_1080p() {
1762 let src = gradient(1280, 720);
1763 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1764 let runs = 30;
1765 let t = std::time::Instant::now();
1766 for _ in 0..runs {
1767 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1768 }
1769 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1770 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1771 }
1772
1773 /// [`blend_i420`] at the midpoint of two solid-colour frames lands exactly
1774 /// on the 50/50 average, on every plane -- the synthetic stand-in for "the
1775 /// dissolve's midpoint frame looks like the average colour" the export
1776 /// path is built on.
1777 #[test]
1778 fn blend_i420_is_50_50_at_the_midpoint() {
1779 let a = (vec![0u8; 16], vec![10u8; 4], vec![20u8; 4]);
1780 let b = (vec![100u8; 16], vec![50u8; 4], vec![120u8; 4]);
1781 let (y, u, v) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.5);
1782 assert!(y.iter().all(|&p| p == 50), "Y midpoint: {y:?}");
1783 assert!(u.iter().all(|&p| p == 30), "U midpoint: {u:?}");
1784 assert!(v.iter().all(|&p| p == 70), "V midpoint: {v:?}");
1785 // The edges hand back each frame untouched.
1786 let (y0, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.0);
1787 assert_eq!(y0, a.0);
1788 let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0);
1789 assert_eq!(y1, b.0);
1790 }
1791
1792 /// The crop fractions cut a rect out of a 100x100 source at the very
1793 /// pixels the maths says, chroma-grid aligned like every other rect here.
1794 #[test]
1795 fn crop_rect_math() {
1796 let t = TransformParams {
1797 crop_l: 0.1,
1798 crop_r: 0.2,
1799 crop_t: 0.0,
1800 crop_b: 0.0,
1801 ..Default::default()
1802 };
1803 assert_eq!(
1804 crop_rect(100, 100, &t),
1805 Rect {
1806 x: 10,
1807 y: 0,
1808 w: 70,
1809 h: 100
1810 },
1811 "10% off the left, 20% off the right, nothing off top or bottom"
1812 );
1813 // Opposing crops clamp to 0.5 a side rather than meeting or crossing.
1814 let extreme = TransformParams {
1815 crop_l: 0.9,
1816 crop_r: 0.9,
1817 ..Default::default()
1818 };
1819 let r = crop_rect(100, 100, &extreme);
1820 assert!(r.w >= 2, "the smallest surviving rect is one chroma sample");
1821 // A zero-sized source has nothing to crop.
1822 assert_eq!(
1823 crop_rect(0, 100, &TransformParams::default()),
1824 Rect {
1825 x: 0,
1826 y: 0,
1827 w: 0,
1828 h: 0
1829 }
1830 );
1831 }
1832
1833 /// A placement moved by `pos_x`/`pos_y` (canvas fractions about its own
1834 /// centre) and resized by `scale`, both about that same centre. Neither
1835 /// case here clips, so the source rect comes back untouched.
1836 #[test]
1837 fn transformed_dst_rect_at_pos_and_scale() {
1838 let dst = Rect {
1839 x: 0,
1840 y: 0,
1841 w: 100,
1842 h: 100,
1843 };
1844 let src = Rect {
1845 x: 0,
1846 y: 0,
1847 w: 100,
1848 h: 100,
1849 };
1850 // Moved a quarter of the canvas to the right, untouched vertically.
1851 let moved = TransformParams {
1852 pos_x: 0.25,
1853 ..Default::default()
1854 };
1855 assert_eq!(
1856 transformed_dst_rect(dst, src, 100, 100, &moved, 200, 200),
1857 (
1858 Rect {
1859 x: 50,
1860 y: 0,
1861 w: 100,
1862 h: 100
1863 },
1864 src
1865 ),
1866 "25% of a 200-wide canvas is 50 pixels, about the placement's own centre"
1867 );
1868 // Doubled in place, box already centred on the canvas: the centre
1869 // stays, the box fills the canvas, nothing clips.
1870 let centred_dst = Rect {
1871 x: 50,
1872 y: 50,
1873 w: 100,
1874 h: 100,
1875 };
1876 let grown = TransformParams {
1877 scale: 2.0,
1878 ..Default::default()
1879 };
1880 assert_eq!(
1881 transformed_dst_rect(centred_dst, src, 100, 100, &grown, 200, 200),
1882 (
1883 Rect {
1884 x: 0,
1885 y: 0,
1886 w: 200,
1887 h: 200
1888 },
1889 src
1890 ),
1891 "a 100x100 box doubled about its own centre on a 200x200 canvas fills it"
1892 );
1893 }
1894
1895 /// The defect this replaces: a positive offset used to SHRINK the dst
1896 /// rect (squeezing the whole source into what remained) and a negative
1897 /// offset used to render pixel-identical to the identity (the clamp at 0
1898 /// killed it). Real translation keeps the box's size and clips instead:
1899 /// the src rect trims by the same fraction that fell off-canvas, on the
1900 /// side that fell off, and the surviving box size never shrinks below
1901 /// what `scale` alone gives it.
1902 #[test]
1903 fn transformed_dst_rect_clips_instead_of_squeezing() {
1904 let dst = Rect {
1905 x: 0,
1906 y: 0,
1907 w: 100,
1908 h: 100,
1909 };
1910 let src = Rect {
1911 x: 0,
1912 y: 0,
1913 w: 100,
1914 h: 100,
1915 };
1916 // +30% of a 100-wide canvas: the box moves 30px right, half of it
1917 // (50px) falls off the right edge -- half the source is trimmed off
1918 // its right, not the whole source squeezed into 70px.
1919 let pos = TransformParams {
1920 pos_x: 0.30,
1921 ..Default::default()
1922 };
1923 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &pos, 100, 100);
1924 assert_eq!(
1925 d,
1926 Rect {
1927 x: 30,
1928 y: 0,
1929 w: 70,
1930 h: 100
1931 },
1932 "dst size must not shrink below what clipping removes"
1933 );
1934 assert_eq!(
1935 s,
1936 Rect {
1937 x: 0,
1938 y: 0,
1939 w: 70,
1940 h: 100
1941 },
1942 "src trims off its right, does not squeeze"
1943 );
1944
1945 // -30%: symmetric on the left, and no longer identical to identity.
1946 let neg = TransformParams {
1947 pos_x: -0.30,
1948 ..Default::default()
1949 };
1950 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &neg, 100, 100);
1951 assert_eq!(
1952 d,
1953 Rect {
1954 x: 0,
1955 y: 0,
1956 w: 70,
1957 h: 100
1958 }
1959 );
1960 assert_eq!(
1961 s,
1962 Rect {
1963 x: 30,
1964 y: 0,
1965 w: 70,
1966 h: 100
1967 },
1968 "src trims off its left"
1969 );
1970 assert_ne!(
1971 (d, s),
1972 (dst, src),
1973 "a negative offset must move the picture, not no-op"
1974 );
1975
1976 // Fully off canvas: both rects empty.
1977 let gone = TransformParams {
1978 pos_x: 2.0,
1979 ..Default::default()
1980 };
1981 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &gone, 100, 100);
1982 assert!(
1983 d.is_empty() && s.is_empty(),
1984 "wholly off-canvas has nothing to draw"
1985 );
1986 }
1987
1988 /// `pos_x`/`pos_y` are canvas fractions and a `transform` line takes any
1989 /// finite `f32`, so they are the one transform field with no bound on the
1990 /// way in -- `float()` (edith.rs) refuses only inf/NaN, and unlike
1991 /// `scale`, which this function caps at a thousand canvas widths precisely
1992 /// so its own arithmetic cannot overflow, the position was multiplied by
1993 /// the canvas and added to `dst.x` unchecked. Rust's `as i64` saturates, so
1994 /// a hostile 3e38 became `i64::MAX` and the *add* is what overflowed:
1995 /// a panic on the compositing thread in a debug build, a silently wrapped
1996 /// position in a release one. A placement pushed off the canvas is already
1997 /// a legal answer (the two empty rects above); a position past the point
1998 /// where the picture is long gone must give that same answer.
1999 #[test]
2000 fn a_transform_position_a_file_can_name_does_not_overflow_the_centre() {
2001 let dst = Rect {
2002 x: 10,
2003 y: 20,
2004 w: 100,
2005 h: 100,
2006 };
2007 let src = Rect {
2008 x: 0,
2009 y: 0,
2010 w: 100,
2011 h: 100,
2012 };
2013 for (pos_x, pos_y) in [
2014 (3.0e38f32, 0.0),
2015 (-3.0e38, 0.0),
2016 (0.0, 3.0e38),
2017 (0.0, -3.0e38),
2018 (3.0e38, 3.0e38),
2019 (f32::MAX, f32::MIN),
2020 ] {
2021 let t = TransformParams {
2022 pos_x,
2023 pos_y,
2024 ..Default::default()
2025 };
2026 let (d, s) = transformed_dst_rect(dst, src, 100, 100, &t, 200, 200);
2027 // The answer is "nothing to draw" -- the box is a thousand canvas
2028 // widths off screen -- not an overflow and not a wrapped position
2029 // that lands back on the canvas.
2030 assert!(
2031 d.is_empty() && s.is_empty(),
2032 "pos ({pos_x}, {pos_y}) gave {d:?} / {s:?} rather than an empty rect pair"
2033 );
2034 }
2035 }
2036
2037 /// [`nearest_90_steps`] rounds to the closest quarter turn and folds a
2038 /// non-finite value to the identity.
2039 #[test]
2040 fn nearest_90_steps_rounds_and_wraps() {
2041 assert_eq!(nearest_90_steps(0.0), 0);
2042 assert_eq!(nearest_90_steps(89.0), 1);
2043 assert_eq!(nearest_90_steps(91.0), 1);
2044 assert_eq!(nearest_90_steps(180.0), 2);
2045 assert_eq!(nearest_90_steps(-90.0), 3);
2046 assert_eq!(nearest_90_steps(360.0 + 90.0), 1);
2047 assert_eq!(nearest_90_steps(f32::NAN), 0);
2048 }
2049
2050 /// A marked corner pixel lands where a clockwise quarter turn puts it:
2051 /// top-left to top-right at 90 degrees, to bottom-right at 180, to
2052 /// bottom-left at 270 -- and the plane's own shape swaps at 90 and 270
2053 /// and stays put at 180.
2054 #[test]
2055 fn rotate_i420_90s_places_a_marked_pixel() {
2056 let (w, h) = (4usize, 3usize);
2057 let mut y = vec![0u8; w * h];
2058 y[0] = 99; // (x=0, y=0), the top-left corner.
2059 let (u, v) = (vec![128u8; 2 * 2], vec![128u8; 2 * 2]);
2060
2061 let mark_at = |plane: &[u8], w: u32, x: u32, y: u32| plane[(y * w + x) as usize];
2062
2063 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 1);
2064 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 90 degrees");
2065 assert_eq!(
2066 mark_at(&ry, rw, rw - 1, 0),
2067 99,
2068 "top-left moves to top-right"
2069 );
2070
2071 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 2);
2072 assert_eq!(
2073 (rw, rh),
2074 (w as u32, h as u32),
2075 "dims stay put at 180 degrees"
2076 );
2077 assert_eq!(
2078 mark_at(&ry, rw, rw - 1, rh - 1),
2079 99,
2080 "top-left moves to bottom-right"
2081 );
2082
2083 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 3);
2084 assert_eq!((rw, rh), (h as u32, w as u32), "dims swap at 270 degrees");
2085 assert_eq!(
2086 mark_at(&ry, rw, 0, rh - 1),
2087 99,
2088 "top-left moves to bottom-left"
2089 );
2090
2091 // Zero steps, and four of them, are both the identity.
2092 let (ry, ru, rv, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 0);
2093 assert_eq!(
2094 (ry, ru, rv, rw, rh),
2095 (y.clone(), u.clone(), v.clone(), w as u32, h as u32)
2096 );
2097 let (ry, _, _, rw, rh) = rotate_i420_90s(&y, &u, &v, w as u32, h as u32, 4);
2098 assert_eq!(
2099 (ry, rw, rh),
2100 (y, w as u32, h as u32),
2101 "four quarter turns is the identity"
2102 );
2103 }
2104
2105 /// A 64x64 Y plane split down the middle: columns 0..32 are 200, 32..64
2106 /// are 40. A vertical edge to track through a horizontal move.
2107 fn vsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2108 let y = (0..64 * 64)
2109 .map(|i| if i % 64 < 32 { 200u8 } else { 40u8 })
2110 .collect();
2111 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
2112 }
2113
2114 /// Same split, but across rows: 0..32 are 200, 32..64 are 40 -- an edge
2115 /// to track through a vertical move.
2116 fn hsplit_64() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2117 let y = (0..64 * 64)
2118 .map(|i| if i / 64 < 32 { 200u8 } else { 40u8 })
2119 .collect();
2120 (y, vec![NEUTRAL_C; 32 * 32], vec![NEUTRAL_C; 32 * 32])
2121 }
2122
2123 /// [`Composer::place_transformed`] at compose level, with the exact
2124 /// defect the geometry used to have: a positive `pos_x` squeezed the
2125 /// whole source into a shrunk box (content narrower, not just displaced)
2126 /// and a negative one rendered pixel-identical to the identity. These
2127 /// assert on the DISPLACED CONTENT (where the source's own edge lands),
2128 /// not on any rect field, so a squeeze that happens to leave rect sizes
2129 /// looking plausible cannot pass silently.
2130 #[test]
2131 fn place_transformed_displaces_content_not_just_a_rect() {
2132 let (src_w, src_h) = (64u32, 64u32);
2133 let (y, u, v) = vsplit_64();
2134 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
2135
2136 // Identity: the source's own edge stays at column 32, everywhere.
2137 let (iy, ..) =
2138 canvas.place_transformed(&y, &u, &v, src_w, src_h, &TransformParams::default());
2139 for row in 0..64 {
2140 let r = &iy[row * 64..][..64];
2141 assert!(
2142 r[..32].iter().all(|&p| p == 200) && r[32..].iter().all(|&p| p == 40),
2143 "row {row}: {r:?}"
2144 );
2145 }
2146
2147 // +25%: the box moves right by 16 and does NOT shrink -- content
2148 // width stays 64 (the source's own 32/32 split), clipped to what
2149 // still fits. The edge (originally at box-column 32) now sits at
2150 // canvas column 16 + 32 = 48, not squeezed inward.
2151 let plus = TransformParams {
2152 pos_x: 0.25,
2153 ..Default::default()
2154 };
2155 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
2156 for row in 0..64 {
2157 let r = &py[row * 64..][..64];
2158 assert!(
2159 r[..16].iter().all(|&p| p == BLACK_Y),
2160 "row {row} left of box: {r:?}"
2161 );
2162 assert!(
2163 r[16..48].iter().all(|&p| p == 200),
2164 "row {row} squeezed inward: {r:?}"
2165 );
2166 assert!(
2167 r[48..].iter().all(|&p| p == 40),
2168 "row {row} edge moved: {r:?}"
2169 );
2170 }
2171
2172 // -25%: mirror image -- this used to be pixel-identical to identity.
2173 let minus = TransformParams {
2174 pos_x: -0.25,
2175 ..Default::default()
2176 };
2177 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
2178 assert_ne!(ny, iy, "a negative offset must move the picture, not no-op");
2179 for row in 0..64 {
2180 let r = &ny[row * 64..][..64];
2181 assert!(r[..16].iter().all(|&p| p == 200), "row {row}: {r:?}");
2182 assert!(r[16..48].iter().all(|&p| p == 40), "row {row}: {r:?}");
2183 assert!(
2184 r[48..].iter().all(|&p| p == BLACK_Y),
2185 "row {row} right of box: {r:?}"
2186 );
2187 }
2188
2189 // Wholly off-canvas: nothing to draw, all black.
2190 let gone = TransformParams {
2191 pos_x: 2.0,
2192 ..Default::default()
2193 };
2194 let (gy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &gone);
2195 assert!(
2196 gy.iter().all(|&p| p == BLACK_Y),
2197 "off-canvas must render background"
2198 );
2199 }
2200
2201 /// The same defect on the vertical axis: `pos_y` moves content up/down,
2202 /// clipped, never squeezed.
2203 #[test]
2204 fn place_transformed_displaces_content_vertically() {
2205 let (src_w, src_h) = (64u32, 64u32);
2206 let (y, u, v) = hsplit_64();
2207 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
2208
2209 let plus = TransformParams {
2210 pos_y: 0.25,
2211 ..Default::default()
2212 };
2213 let (py, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &plus);
2214 for row in 0..16 {
2215 assert!(
2216 py[row * 64..][..64].iter().all(|&p| p == BLACK_Y),
2217 "row {row} above the box"
2218 );
2219 }
2220 for row in 16..48 {
2221 assert!(
2222 py[row * 64..][..64].iter().all(|&p| p == 200),
2223 "row {row} squeezed: {:?}",
2224 &py[row * 64..][..4]
2225 );
2226 }
2227 for row in 48..64 {
2228 assert!(
2229 py[row * 64..][..64].iter().all(|&p| p == 40),
2230 "row {row} edge moved"
2231 );
2232 }
2233
2234 let minus = TransformParams {
2235 pos_y: -0.25,
2236 ..Default::default()
2237 };
2238 let (ny, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &minus);
2239 for row in 0..16 {
2240 assert!(ny[row * 64..][..64].iter().all(|&p| p == 200), "row {row}");
2241 }
2242 for row in 16..48 {
2243 assert!(ny[row * 64..][..64].iter().all(|&p| p == 40), "row {row}");
2244 }
2245 for row in 48..64 {
2246 assert!(
2247 ny[row * 64..][..64].iter().all(|&p| p == BLACK_Y),
2248 "row {row} below the box"
2249 );
2250 }
2251 }
2252
2253 /// Position and scale together: a halved box moved right must place its
2254 /// (also halved) content at the moved-and-scaled location, not squeeze
2255 /// the full source into whatever survived clamping.
2256 #[test]
2257 fn place_transformed_displaces_content_with_scale() {
2258 let (src_w, src_h) = (64u32, 64u32);
2259 let (y, u, v) = vsplit_64();
2260 let mut canvas = Composer::new(src_w, src_h, FitPolicy::Fit);
2261 // scale 0.5, pos_x +0.25: box becomes 32x32 at canvas (32, 16),
2262 // fully on-canvas. The source's column-32 edge, halved, sits at
2263 // box-local column 16, i.e. canvas column 32 + 16 = 48.
2264 let t = TransformParams {
2265 scale: 0.5,
2266 pos_x: 0.25,
2267 ..Default::default()
2268 };
2269 let (sy, ..) = canvas.place_transformed(&y, &u, &v, src_w, src_h, &t);
2270 for row in 0..64 {
2271 let r = &sy[row * 64..][..64];
2272 let inside = (16..48).contains(&row);
2273 let want_bg = if inside { r[0] } else { BLACK_Y };
2274 assert_eq!(want_bg, BLACK_Y, "row {row} col 0 outside the box: {r:?}");
2275 if inside {
2276 assert!(
2277 r[40].abs_diff(200) <= 1,
2278 "row {row} col 40 should be the left half: {r:?}"
2279 );
2280 assert!(
2281 r[56].abs_diff(40) <= 1,
2282 "row {row} col 56 should be the right half: {r:?}"
2283 );
2284 }
2285 }
2286 }
2287}