forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

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