forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB86e9455Tahinli3 months ago398 commits

scale.rs1079 lines, 41.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
29/// Limited-range black: what an untouched canvas pixel is.
30pub const BLACK_Y: u8 = 16;
31/// Neutral chroma: 128 in both planes.
32pub const NEUTRAL_C: u8 = 128;
33
34/// A rectangle on one plane, in luma samples. Always inside the plane it
35/// describes; `fit_rect` never hands back one that is not.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct Rect {
38 pub x: u32,
39 pub y: u32,
40 pub w: u32,
41 pub h: u32,
42}
43
44impl Rect {
45 pub fn is_empty(&self) -> bool {
46 self.w == 0 || self.h == 0
47 }
48}
49
50/// How a source picture of one shape meets a canvas of another.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum FitPolicy {
53 /// Whole picture, aspect kept, centred -- the leftover canvas is bars.
54 #[default]
55 Fit,
56 /// Whole canvas, aspect kept, centred -- the leftover picture is cropped.
57 Fill,
58 /// Whole picture on the whole canvas; aspect is not kept.
59 Stretch,
60 /// No resampling at all: 1:1 samples, centred, padded or cropped per axis.
61 Center,
62}
63
64/// Placement and crop for one source on one canvas.
65///
66/// Returns `(dst placement rect on the canvas, src crop rect on the source)`.
67/// The caller scales the crop to the placement size and composes it there; a
68/// `Center` result has the two rects the same size, i.e. nothing to scale.
69///
70/// Rounding, and why it is what it is: both rects are aligned to the I420
71/// chroma grid, so that one chroma sample of the scaled picture is one chroma
72/// sample of the canvas and no colour lands half a sample off. `x` and `y` are
73/// floored to even; `w` and `h` are floored to even *unless* the rect ends
74/// exactly at the plane edge, where an odd size is fine because both grids end
75/// together (that is what keeps an equal-size `Fit` a byte-exact pass-through
76/// on an odd-width source). The alignment can therefore cost one sample of
77/// aspect accuracy -- under a tenth of a percent at any real resolution.
78///
79/// A zero-sized canvas or source yields two empty rects. An extreme aspect
80/// never rounds the picture away: the smallest rect is one chroma sample (2x2),
81/// clipped to the plane. A plane one sample wide or high has no grid to align
82/// to and keeps that single sample.
83pub fn fit_rect(src_w: u32, src_h: u32, dst_w: u32, dst_h: u32, policy: FitPolicy) -> (Rect, Rect) {
84 let empty = Rect {
85 x: 0,
86 y: 0,
87 w: 0,
88 h: 0,
89 };
90 if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 {
91 return (empty, empty);
92 }
93 let full_src = Rect {
94 x: 0,
95 y: 0,
96 w: src_w,
97 h: src_h,
98 };
99 let full_dst = Rect {
100 x: 0,
101 y: 0,
102 w: dst_w,
103 h: dst_h,
104 };
105
106 match policy {
107 FitPolicy::Stretch => (full_dst, full_src),
108 FitPolicy::Fit => {
109 // Widest box with the source aspect that still fits the canvas.
110 let (w, h) =
111 if u64::from(src_w) * u64::from(dst_h) <= u64::from(dst_w) * u64::from(src_h) {
112 (ratio(src_w, dst_h, src_h).min(dst_w), dst_h)
113 } else {
114 (dst_w, ratio(src_h, dst_w, src_w).min(dst_h))
115 };
116 (centred(w, h, dst_w, dst_h), full_src)
117 }
118 FitPolicy::Fill => {
119 // Largest box with the canvas aspect that still fits the source.
120 let (w, h) =
121 if u64::from(src_w) * u64::from(dst_h) >= u64::from(dst_w) * u64::from(src_h) {
122 (ratio(src_h, dst_w, dst_h).min(src_w), src_h)
123 } else {
124 (src_w, ratio(src_w, dst_h, dst_w).min(src_h))
125 };
126 (full_dst, centred(w, h, src_w, src_h))
127 }
128 FitPolicy::Center => {
129 let w = src_w.min(dst_w);
130 let h = src_h.min(dst_h);
131 let dst = centred(w, h, dst_w, dst_h);
132 let src = centred(w, h, src_w, src_h);
133 // Even-alignment may have shrunk one of them; 1:1 means both carry
134 // the same sample count, so take the smaller of the two.
135 let w = dst.w.min(src.w);
136 let h = dst.h.min(src.h);
137 (Rect { w, h, ..dst }, Rect { w, h, ..src })
138 }
139 }
140}
141
142/// `value * num / den`, rounded to nearest, in 64-bit so 8K x 8K cannot wrap.
143fn ratio(value: u32, num: u32, den: u32) -> u32 {
144 let den = u64::from(den).max(1);
145 ((u64::from(value) * u64::from(num) + den / 2) / den) as u32
146}
147
148/// A `w` x `h` box centred in `extent_w` x `extent_h`, chroma-grid aligned.
149fn centred(w: u32, h: u32, extent_w: u32, extent_h: u32) -> Rect {
150 let (x, w) = align(extent_w.saturating_sub(w) / 2, w, extent_w);
151 let (y, h) = align(extent_h.saturating_sub(h) / 2, h, extent_h);
152 Rect { x, y, w, h }
153}
154
155/// Floors the offset to even, clips the size into the plane, and floors the
156/// size to even unless the rect ends at the plane edge.
157fn align(offset: u32, size: u32, extent: u32) -> (u32, u32) {
158 let offset = (offset & !1).min(extent);
159 let mut size = size.min(extent - offset);
160 if offset + size < extent {
161 size &= !1;
162 }
163 if size == 0 {
164 // An extreme aspect (a 1-sample-wide source) would otherwise round its
165 // picture away entirely. One chroma sample is the floor, not zero.
166 size = extent.min(2);
167 }
168 (offset, size)
169}
170
171/// Chroma plane size for a luma dimension: `(w + 1) / 2`, both axes.
172pub fn chroma_dims(w: usize, h: usize) -> (usize, usize) {
173 (w.div_ceil(2), h.div_ceil(2))
174}
175
176/// A `w` x `h` I420 canvas filled with limited-range black.
177pub fn black_i420(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
178 let (cw, ch) = chroma_dims(w, h);
179 (
180 vec![BLACK_Y; w * h],
181 vec![NEUTRAL_C; cw * ch],
182 vec![NEUTRAL_C; cw * ch],
183 )
184}
185
186/// Resamples a tightly packed I420 frame (stride == width) into another one.
187///
188/// Equal dimensions copy byte for byte -- a project at the media's own
189/// resolution is not a resample. Otherwise each plane is bilinear-filtered
190/// independently, chroma at its own `(w + 1) / 2` size, so odd dimensions need
191/// no special case: a 7x5 source has a 4x3 chroma plane and a 13x9 destination
192/// wants a 7x5 one, and that is just another rescale.
193///
194/// Panics if a slice is not exactly its plane's size; a mis-sized buffer is a
195/// caller bug, not a runtime condition, and every alternative silently produces
196/// a sheared picture.
197#[allow(clippy::too_many_arguments)]
198pub fn scale_i420(
199 src_y: &[u8],
200 src_u: &[u8],
201 src_v: &[u8],
202 src_w: usize,
203 src_h: usize,
204 dst_y: &mut [u8],
205 dst_u: &mut [u8],
206 dst_v: &mut [u8],
207 dst_w: usize,
208 dst_h: usize,
209) {
210 let (src_cw, src_ch) = chroma_dims(src_w, src_h);
211 let (dst_cw, dst_ch) = chroma_dims(dst_w, dst_h);
212 assert_eq!(src_y.len(), src_w * src_h, "source luma plane");
213 assert_eq!(src_u.len(), src_cw * src_ch, "source U plane");
214 assert_eq!(src_v.len(), src_cw * src_ch, "source V plane");
215 assert_eq!(dst_y.len(), dst_w * dst_h, "destination luma plane");
216 assert_eq!(dst_u.len(), dst_cw * dst_ch, "destination U plane");
217 assert_eq!(dst_v.len(), dst_cw * dst_ch, "destination V plane");
218
219 if src_w == dst_w && src_h == dst_h {
220 dst_y.copy_from_slice(src_y);
221 dst_u.copy_from_slice(src_u);
222 dst_v.copy_from_slice(src_v);
223 return;
224 }
225 plane(src_y, src_w, src_h, dst_y, dst_w, dst_h);
226 plane(src_u, src_cw, src_ch, dst_u, dst_cw, dst_ch);
227 plane(src_v, src_cw, src_ch, dst_v, dst_cw, dst_ch);
228}
229
230/// 16.16 fixed point: one whole sample step.
231const ONE: u32 = 1 << 16;
232const HALF: u32 = ONE / 2;
233
234/// The two source samples and the weight of the second one, for one output
235/// position: `src = (dst + 0.5) * src_len / dst_len - 0.5`, clamped to the
236/// plane so the edges replicate instead of reading past it.
237fn taps(dst_len: usize, src_len: usize) -> Vec<(u32, u32, u32)> {
238 let step = (src_len as u64) * u64::from(ONE) / dst_len as u64;
239 let last = src_len as u32 - 1;
240 (0..dst_len)
241 .map(|i| {
242 // (i + 0.5) * step - 0.5, kept in u64 until the subtraction so the
243 // clamp at 0 is the only place a negative could have appeared.
244 let centre = (2 * i as u64 + 1) * step / 2;
245 let pos = centre.saturating_sub(u64::from(HALF));
246 let whole = ((pos >> 16) as u32).min(last);
247 let frac = if whole == last {
248 0
249 } else {
250 (pos as u32) & (ONE - 1)
251 };
252 (whole, (whole + 1).min(last), frac)
253 })
254 .collect()
255}
256
257/// Bilinear resample of one tightly packed 8-bit plane.
258fn plane(src: &[u8], src_w: usize, src_h: usize, dst: &mut [u8], dst_w: usize, dst_h: usize) {
259 if dst_w == 0 || dst_h == 0 || src_w == 0 || src_h == 0 {
260 return;
261 }
262 let cols = taps(dst_w, src_w);
263 let rows = taps(dst_h, src_h);
264
265 for (y, &(y0, y1, wy)) in rows.iter().enumerate() {
266 let top = &src[y0 as usize * src_w..][..src_w];
267 let bottom = &src[y1 as usize * src_w..][..src_w];
268 let inv_wy = ONE - wy;
269 let out = &mut dst[y * dst_w..][..dst_w];
270 for (o, &(x0, x1, wx)) in out.iter_mut().zip(cols.iter()) {
271 let inv_wx = ONE - wx;
272 let (x0, x1) = (x0 as usize, x1 as usize);
273 // Each stage stays under 255 * 65536 + 32768, well inside u32.
274 let a = (u32::from(top[x0]) * inv_wx + u32::from(top[x1]) * wx + HALF) >> 16;
275 let b = (u32::from(bottom[x0]) * inv_wx + u32::from(bottom[x1]) * wx + HALF) >> 16;
276 *o = ((a * inv_wy + b * wy + HALF) >> 16) as u8;
277 }
278 }
279}
280
281/// Blits a frame of exactly `rect.w` x `rect.h` onto a canvas at `rect`.
282///
283/// The rect is clipped to the canvas first, so a rect from anywhere (not just
284/// [`fit_rect`]) is safe; a clipped blit copies the part that fits, from the
285/// frame's top-left. Everything outside the rect keeps whatever the canvas
286/// already held -- [`black_i420`] for a letterbox.
287///
288/// Chroma rounding: `rect.x/2` and `rect.y/2` address the canvas chroma plane,
289/// which is exact because [`fit_rect`] hands back even offsets. An odd offset
290/// would put the frame's chroma half a sample off its own grid, so it is
291/// floored to even here rather than silently smeared.
292#[allow(clippy::too_many_arguments)]
293pub fn compose_i420(
294 canvas_y: &mut [u8],
295 canvas_u: &mut [u8],
296 canvas_v: &mut [u8],
297 canvas_w: usize,
298 canvas_h: usize,
299 frame_y: &[u8],
300 frame_u: &[u8],
301 frame_v: &[u8],
302 rect: Rect,
303) {
304 let x = (rect.x & !1) as usize;
305 let y = (rect.y & !1) as usize;
306 if x >= canvas_w || y >= canvas_h {
307 return;
308 }
309 let fw = rect.w as usize;
310 let fh = rect.h as usize;
311 let w = fw.min(canvas_w - x);
312 let h = fh.min(canvas_h - y);
313 if w == 0 || h == 0 {
314 return;
315 }
316 for row in 0..h {
317 canvas_y[(y + row) * canvas_w + x..][..w].copy_from_slice(&frame_y[row * fw..][..w]);
318 }
319
320 let (canvas_cw, _) = chroma_dims(canvas_w, canvas_h);
321 let (fcw, _) = chroma_dims(fw, fh);
322 // Half-resolution copy of the clipped luma region, rounded up so an odd
323 // width still carries its last (half-covered) chroma sample.
324 let (cw, ch) = chroma_dims(w, h);
325 let (cx, cy) = (x / 2, y / 2);
326 for row in 0..ch {
327 let dst = (cy + row) * canvas_cw + cx;
328 canvas_u[dst..][..cw].copy_from_slice(&frame_u[row * fcw..][..cw]);
329 canvas_v[dst..][..cw].copy_from_slice(&frame_v[row * fcw..][..cw]);
330 }
331}
332
333/// One clip's pictures placed on the project canvas: the geometry, plus the
334/// buffers it composes into so a frame costs no allocation.
335///
336/// This is the *one* definition of what a mixed-resolution timeline looks like:
337/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
338/// decoded planes to [`place`](Composer::place), so what is watched and what is
339/// written cannot drift apart.
340///
341/// **Order against the colour grade: grade first, place second.** A grade
342/// belongs to the clip's own pixels -- it is graded at the resolution it was
343/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
344/// letterbox bars are *not* the clip: a brightness grade that reached them would
345/// lift the black frame around the picture. Callers therefore grade the source
346/// planes and place the result; the bars stay exactly [`black_i420`].
347///
348/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
349/// hands the caller's own planes straight back, allocates nothing and touches no
350/// byte, which is what keeps a project at its media's resolution the byte-for-byte
351/// path it was before there was a project resolution at all.
352///
353/// [`place`]: Composer::place
354pub struct Composer {
355 width: u32,
356 height: u32,
357 policy: FitPolicy,
358 /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
359 /// `Center` ever crop, so this stays empty for a letterboxed project.
360 crop: (Vec<u8>, Vec<u8>, Vec<u8>),
361 /// The crop resampled to the placement rect.
362 scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
363 /// The canvas itself, refilled with black every frame -- a memset against a
364 /// decode, and the only way a policy change cannot leave last frame's bars
365 /// showing through.
366 canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
367}
368
369impl Composer {
370 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
371 let empty = || (Vec::new(), Vec::new(), Vec::new());
372 Self {
373 width,
374 height,
375 policy,
376 crop: empty(),
377 scaled: empty(),
378 canvas: empty(),
379 }
380 }
381
382 /// A composer that places nothing: every picture passes through at its own
383 /// size. What the file-level decode API opens with, where there is no
384 /// project and therefore no canvas.
385 pub fn passthrough() -> Self {
386 Self::new(0, 0, FitPolicy::Fit)
387 }
388
389 /// How many decoded pictures a worker over this canvas may keep ahead of
390 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
391 /// than a 1080p one instead of the same number of far bigger frames.
392 ///
393 /// The floor is 2 -- the bound this engine ran on everywhere before there
394 /// was a decode-ahead at all -- and it is also what a pass-through canvas
395 /// gets, since that one does not know what size the pictures will be (they
396 /// are the source's) and its callers pull frame by frame anyway.
397 pub(crate) fn queue_depth(&self) -> usize {
398 /// ~96 MB of BGRA in flight: eleven 1080p pictures, two 4K ones.
399 const BUDGET: usize = 96 << 20;
400 let bytes = self.width as usize * self.height as usize * 4;
401 if bytes == 0 {
402 return 2;
403 }
404 (BUDGET / bytes).clamp(2, 16)
405 }
406
407 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
408 /// composer would hand it back untouched. What lets a caller keep a fused
409 /// fast path (the graded conversion) for the common case.
410 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
411 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
412 }
413
414 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
415 /// caller's own planes (pass-through) or the canvas with the fitted picture
416 /// composed onto it. The dimensions come back because those two differ.
417 ///
418 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
419 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
420 pub fn place<'a>(
421 &'a mut self,
422 y: &'a [u8],
423 u: &'a [u8],
424 v: &'a [u8],
425 src_w: u32,
426 src_h: u32,
427 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
428 if self.is_passthrough(src_w, src_h) {
429 return (y, u, v, src_w, src_h);
430 }
431 let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
432 let (sw, sh) = (src_w as usize, src_h as usize);
433
434 // Crop first, so the scaler only ever sees a tightly packed plane. Fit
435 // and Stretch never crop, which is the whole cost of the common case.
436 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
437 (y, u, v)
438 } else {
439 crop_i420(&mut self.crop, y, u, v, sw, sh, src);
440 (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
441 };
442 // ...then resample it to the placement, unless it already is that size
443 // (`Center` never resamples, and neither does an exact-fit upscale).
444 let (cw, ch) = (src.w as usize, src.h as usize);
445 let (dw, dh) = (dst.w as usize, dst.h as usize);
446 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
447 (src_y, src_u, src_v)
448 } else {
449 let (ccw, cch) = chroma_dims(dw, dh);
450 let (sy, su, sv) = &mut self.scaled;
451 sy.resize(dw * dh, 0);
452 su.resize(ccw * cch, 0);
453 sv.resize(ccw * cch, 0);
454 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
455 (&sy[..], &su[..], &sv[..])
456 };
457
458 let (w, h) = (self.width as usize, self.height as usize);
459 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
460 let (ky, ku, kv) = &mut self.canvas;
461 fill(ky, w * h, BLACK_Y);
462 fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
463 fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
464 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
465 (ky, ku, kv, self.width, self.height)
466 }
467}
468
469/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
470/// across frames is refilled, not reallocated.
471fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
472 plane.clear();
473 plane.resize(len, value);
474}
475
476/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
477/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
478/// crop is exactly half of it.
479fn crop_i420(
480 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
481 y: &[u8],
482 u: &[u8],
483 v: &[u8],
484 src_w: usize,
485 src_h: usize,
486 rect: Rect,
487) {
488 let (w, h) = (rect.w as usize, rect.h as usize);
489 let (x, cy0) = (rect.x as usize, rect.y as usize);
490 let (src_cw, _) = chroma_dims(src_w, src_h);
491 let (cw, ch) = chroma_dims(w, h);
492 let (oy, ou, ov) = out;
493 oy.clear();
494 ou.clear();
495 ov.clear();
496 for row in 0..h {
497 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
498 }
499 let (cx, cy0) = (x / 2, cy0 / 2);
500 for row in 0..ch {
501 let at = (cy0 + row) * src_cw + cx;
502 ou.extend_from_slice(&u[at..][..cw]);
503 ov.extend_from_slice(&v[at..][..cw]);
504 }
505 debug_assert_eq!(oy.len(), w * h);
506 debug_assert_eq!(ou.len(), cw * ch);
507}
508
509#[cfg(test)]
510mod tests {
511 use super::*;
512
513 /// Allocates the destination planes for a size and runs a scale into them.
514 fn scaled(
515 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
516 src_w: usize,
517 src_h: usize,
518 dst_w: usize,
519 dst_h: usize,
520 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
521 let (cw, ch) = chroma_dims(dst_w, dst_h);
522 let mut dst = (
523 vec![0u8; dst_w * dst_h],
524 vec![0u8; cw * ch],
525 vec![0u8; cw * ch],
526 );
527 scale_i420(
528 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
529 );
530 dst
531 }
532
533 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
534 let (cw, ch) = chroma_dims(w, h);
535 (
536 (0..w * h).map(|i| (i % 256) as u8).collect(),
537 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
538 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
539 )
540 }
541
542 /// The pass-through invariant: a project at the media's own resolution must
543 /// hand the decoder's bytes to the encoder unchanged.
544 #[test]
545 fn identity_scale_is_byte_identical() {
546 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
547 let src = gradient(w, h);
548 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
549 }
550 }
551
552 /// Halving is the one case where bilinear is exactly a 2x2 box average:
553 /// the output centre falls on the shared corner of four input samples.
554 /// 0/254 averages to 127 with no rounding slack at all.
555 #[test]
556 fn downscale_by_two_averages_a_checkerboard() {
557 let (w, h) = (32, 24);
558 let (cw, ch) = chroma_dims(w, h);
559 let checker = |i: usize, stride: usize| {
560 if (i / stride + i % stride).is_multiple_of(2) {
561 0u8
562 } else {
563 254
564 }
565 };
566 let src = (
567 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
568 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
569 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
570 );
571 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
572 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
573 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
574 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
575 }
576
577 /// Nothing may leak in from outside a plane: a flat frame stays flat at
578 /// every edge, upscaled and downscaled, odd sizes included.
579 #[test]
580 fn flat_frame_stays_flat() {
581 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
582 for &(sw, sh) in &sizes {
583 let (cw, ch) = chroma_dims(sw, sh);
584 let src = (
585 vec![80u8; sw * sh],
586 vec![90u8; cw * ch],
587 vec![200u8; cw * ch],
588 );
589 for &(dw, dh) in &sizes {
590 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
591 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
592 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
593 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
594 }
595 }
596 }
597
598 /// Chroma alignment: an edge in the U plane must land at the *same* place
599 /// after a 2x upscale, with a symmetric two-sample blend around it and
600 /// untouched flats either side -- a half-sample bias shows up as an
601 /// asymmetric pair here, which is colour bleeding one way.
602 #[test]
603 fn chroma_edge_keeps_its_position() {
604 let (w, h) = (8, 8);
605 let (cw, ch) = chroma_dims(w, h);
606 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
607 let src = (
608 vec![80u8; w * h],
609 (0..cw * ch)
610 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
611 .collect(),
612 vec![128u8; cw * ch],
613 );
614 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
615 let (dcw, _) = chroma_dims(w * 2, h * 2);
616 assert_eq!(dcw, 8);
617 let row = &u[dcw * 3..][..dcw];
618 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
619 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
620 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
621 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
622 // most 1; anything further means the edge moved.
623 assert!(
624 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
625 "blend is off centre, i.e. chroma bled one way: {row:?}"
626 );
627 }
628
629 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
630 /// `(src, dst, policy) -> (placement, crop)`.
631 #[test]
632 fn fit_rect_table() {
633 let r = |x, y, w, h| Rect { x, y, w, h };
634 let cases = [
635 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
636 (
637 (1920, 1080),
638 (640, 480),
639 FitPolicy::Fit,
640 r(0, 60, 640, 360),
641 r(0, 0, 1920, 1080),
642 ),
643 // ...and the same pair filled: the canvas is whole, the source is
644 // cropped to 4:3 (1440 wide) about its centre.
645 (
646 (1920, 1080),
647 (640, 480),
648 FitPolicy::Fill,
649 r(0, 0, 640, 480),
650 r(240, 0, 1440, 1080),
651 ),
652 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
653 (
654 (640, 480),
655 (1920, 1080),
656 FitPolicy::Fit,
657 r(240, 0, 1440, 1080),
658 r(0, 0, 640, 480),
659 ),
660 (
661 (640, 480),
662 (1920, 1080),
663 FitPolicy::Fill,
664 r(0, 0, 1920, 1080),
665 r(0, 60, 640, 360),
666 ),
667 // Stretch ignores aspect entirely, both ways.
668 (
669 (1920, 1080),
670 (640, 480),
671 FitPolicy::Stretch,
672 r(0, 0, 640, 480),
673 r(0, 0, 1920, 1080),
674 ),
675 // 1:1 with a bigger source: cropped both ways, centred.
676 (
677 (1920, 1080),
678 (640, 480),
679 FitPolicy::Center,
680 r(0, 0, 640, 480),
681 r(640, 300, 640, 480),
682 ),
683 // 1:1 with a smaller source: padded both ways, centred.
684 (
685 (640, 480),
686 (1920, 1080),
687 FitPolicy::Center,
688 r(640, 300, 640, 480),
689 r(0, 0, 640, 480),
690 ),
691 // Odd sizes: offsets even, sizes even unless they reach the edge.
692 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
693 (
694 (7, 5),
695 (13, 9),
696 FitPolicy::Fit,
697 r(0, 0, 13, 9),
698 r(0, 0, 7, 5),
699 ),
700 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
701 // offset without putting chroma half a sample off, so the last one
702 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
703 (
704 (9, 9),
705 (13, 9),
706 FitPolicy::Center,
707 r(2, 0, 8, 9),
708 r(0, 0, 8, 9),
709 ),
710 (
711 (13, 9),
712 (9, 9),
713 FitPolicy::Center,
714 r(0, 0, 8, 9),
715 r(2, 0, 8, 9),
716 ),
717 ];
718 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
719 let got = fit_rect(sw, sh, dw, dh, policy);
720 assert_eq!(
721 got,
722 (want_dst, want_src),
723 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
724 );
725 }
726 // Degenerate input is empty, not a panic.
727 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
728 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
729 }
730
731 /// Every rect a policy hands back must sit inside its plane, start on the
732 /// chroma grid, and end on it or at the plane edge -- the invariant
733 /// `compose_i420` relies on.
734 #[test]
735 fn fit_rect_stays_on_the_chroma_grid() {
736 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
737 for policy in [
738 FitPolicy::Fit,
739 FitPolicy::Fill,
740 FitPolicy::Stretch,
741 FitPolicy::Center,
742 ] {
743 for &sw in &sizes {
744 for &dh in &sizes {
745 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
746 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
747 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
748 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
749 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
750 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
751 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
752 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
753 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
754 // A plane one sample wide or high has no chroma grid to
755 // be on: `Center` from a 2-high source onto a 1-high
756 // canvas is one row, and no size satisfies both edges.
757 // Nothing real is that shape; it must merely not
758 // escape its plane, which the two asserts above cover.
759 if grid {
760 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
761 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
762 }
763 assert!(!rect.is_empty(), "{ctx} empty");
764 }
765 }
766 }
767 }
768 }
769
770 #[test]
771 fn compose_fills_the_rect_and_nothing_else() {
772 let (cw2, ch2) = (640usize, 360usize);
773 let (canvas_w, canvas_h) = (640usize, 480usize);
774 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
775 let (fcw, fch) = chroma_dims(cw2, ch2);
776 let frame = (
777 vec![200u8; cw2 * ch2],
778 vec![70u8; fcw * fch],
779 vec![30u8; fcw * fch],
780 );
781 let rect = Rect {
782 x: 0,
783 y: 60,
784 w: cw2 as u32,
785 h: ch2 as u32,
786 };
787 compose_i420(
788 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
789 );
790
791 for row in 0..canvas_h {
792 let inside = (60..420).contains(&row);
793 let want = if inside { 200 } else { BLACK_Y };
794 assert!(
795 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
796 "luma row {row}"
797 );
798 }
799 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
800 for row in 0..cch {
801 let inside = (30..210).contains(&row);
802 let (wu, wv) = if inside {
803 (70, 30)
804 } else {
805 (NEUTRAL_C, NEUTRAL_C)
806 };
807 assert!(
808 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
809 "U row {row}"
810 );
811 assert!(
812 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
813 "V row {row}"
814 );
815 }
816 }
817
818 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
819 /// is public and a caller may compute a rect itself.
820 #[test]
821 fn compose_clips_a_rect_that_runs_off_the_canvas() {
822 let (mut y, mut u, mut v) = black_i420(16, 16);
823 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
824 let rect = Rect {
825 x: 12,
826 y: 12,
827 w: 8,
828 h: 8,
829 };
830 compose_i420(
831 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
832 );
833 assert_eq!(y[15 * 16 + 15], 99);
834 assert_eq!(y[11 * 16 + 15], BLACK_Y);
835 // Wholly outside: no write at all.
836 let before = y.clone();
837 compose_i420(
838 &mut y,
839 &mut u,
840 &mut v,
841 16,
842 16,
843 &frame.0,
844 &frame.1,
845 &frame.2,
846 Rect {
847 x: 100,
848 y: 0,
849 w: 8,
850 h: 8,
851 },
852 );
853 assert_eq!(y, before);
854 }
855
856 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
857 /// project canvas, letterbox bars intact.
858 #[test]
859 fn fit_scale_compose_letterboxes() {
860 let (sw, sh) = (640usize, 480usize);
861 let (dw, dh) = (1920usize, 1080usize);
862 let src = gradient(sw, sh);
863 let (dst_rect, src_rect) =
864 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
865 assert_eq!(
866 src_rect,
867 Rect {
868 x: 0,
869 y: 0,
870 w: 640,
871 h: 480
872 }
873 );
874 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
875 let picture = scaled(&src, sw, sh, rw, rh);
876 let (mut y, mut u, mut v) = black_i420(dw, dh);
877 compose_i420(
878 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
879 );
880 // Pillarbox columns stay black, the picture area does not.
881 let mid = (dh / 2) * dw;
882 assert!(
883 y[mid..mid + dst_rect.x as usize]
884 .iter()
885 .all(|&s| s == BLACK_Y)
886 );
887 assert_eq!(
888 y[mid + dst_rect.x as usize..][..rw],
889 picture.0[(rh / 2) * rw..][..rw]
890 );
891 }
892
893 /// The wiring invariant: a project at its media's own resolution hands the
894 /// decoder's own slices back, not a copy that happens to be equal. Asserted
895 /// on the pointer, because "identical bytes" is cheap and "no work at all"
896 /// is what the common case is promised.
897 #[test]
898 fn a_canvas_of_the_source_size_is_a_pass_through() {
899 let (w, h) = (64usize, 48usize);
900 let src = gradient(w, h);
901 for mut canvas in [
902 Composer::new(w as u32, h as u32, FitPolicy::Fit),
903 Composer::new(w as u32, h as u32, FitPolicy::Fill),
904 Composer::new(w as u32, h as u32, FitPolicy::Center),
905 Composer::passthrough(),
906 ] {
907 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
908 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
909 assert_eq!(u.as_ptr(), src.1.as_ptr());
910 assert_eq!(v.as_ptr(), src.2.as_ptr());
911 assert_eq!((cw, ch), (w as u32, h as u32));
912 }
913 }
914
915 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
916 /// the pillarbox columns are limited-range black, exactly -- a bar that is
917 /// merely dark is a bar the grade reached.
918 #[test]
919 fn fit_pillarboxes_with_exact_black_bars() {
920 let (sw, sh) = (640u32, 480u32);
921 let (dw, dh) = (1920u32, 1080u32);
922 let src = (
923 vec![200u8; (sw * sh) as usize],
924 vec![70u8; (sw * sh / 4) as usize],
925 vec![30u8; (sw * sh / 4) as usize],
926 );
927 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
928 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
929 assert_eq!((w, h), (dw, dh));
930 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
931 assert_eq!(
932 rect,
933 Rect {
934 x: 240,
935 y: 0,
936 w: 1440,
937 h: 1080
938 },
939 "geometry moved"
940 );
941 let (w, h) = (w as usize, h as usize);
942 let row = &y[(h / 2) * w..][..w];
943 let x = rect.x as usize;
944 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
945 assert!(
946 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
947 "right bar not black"
948 );
949 assert!(
950 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
951 "picture"
952 );
953 // ...and the bars are neutral in chroma too, or they would be a colour.
954 let (cw, _) = chroma_dims(w, h);
955 let crow = &u[(h / 4) * cw..][..cw];
956 assert!(
957 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
958 "bar has colour"
959 );
960 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
961 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
962 }
963
964 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
965 /// the canvas (no bar anywhere), `Center` pads without resampling.
966 #[test]
967 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
968 let (sw, sh) = (640u32, 480u32);
969 let (dw, dh) = (1920u32, 1080u32);
970 let src = (
971 vec![200u8; (sw * sh) as usize],
972 vec![70u8; (sw * sh / 4) as usize],
973 vec![30u8; (sw * sh / 4) as usize],
974 );
975 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
976 let mut canvas = Composer::new(dw, dh, policy);
977 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
978 assert!(
979 y.iter().all(|&s| s == 200),
980 "{policy:?} left a bar: the canvas is not covered"
981 );
982 }
983 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
984 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
985 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
986 assert_eq!(rect.w, sw, "Center resampled the picture");
987 let (w, h) = (w as usize, h as usize);
988 let row = &y[(h / 2) * w..][..w];
989 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
990 assert!(
991 row[rect.x as usize..][..sw as usize]
992 .iter()
993 .all(|&s| s == 200)
994 );
995 }
996
997 /// A crop (`Fill` on a wider source) must gather the *middle* of the
998 /// picture, chroma with it: a marked band at a known column has to come out
999 /// at the column the geometry puts it at.
1000 #[test]
1001 fn fill_crops_about_the_centre() {
1002 let (sw, sh) = (32usize, 8usize);
1003 let (dw, dh) = (8u32, 8u32);
1004 // Column 16 (the centre) is bright, everything else is dark.
1005 let y: Vec<u8> = (0..sw * sh)
1006 .map(|i| if i % sw == 16 { 240 } else { 40 })
1007 .collect();
1008 let (cw, ch) = chroma_dims(sw, sh);
1009 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1010 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1011 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1012 assert_eq!((w, h), (dw, dh));
1013 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1014 assert_eq!(
1015 dst,
1016 Rect {
1017 x: 0,
1018 y: 0,
1019 w: 8,
1020 h: 8
1021 },
1022 "Fill must cover"
1023 );
1024 assert_eq!(
1025 crop,
1026 Rect {
1027 x: 12,
1028 y: 0,
1029 w: 8,
1030 h: 8
1031 },
1032 "crop off centre"
1033 );
1034 // The bright column is crop-relative column 4 of 8, untouched by the
1035 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1036 let row = &y[..8];
1037 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1038 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1039 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1040 }
1041
1042 /// Not asserted: only the release number means anything. Run with
1043 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1044 #[test]
1045 fn perf_720p_to_1080p() {
1046 let src = gradient(1280, 720);
1047 let (cw, ch) = chroma_dims(1920, 1080);
1048 let mut dst = (
1049 vec![0u8; 1920 * 1080],
1050 vec![0u8; cw * ch],
1051 vec![0u8; cw * ch],
1052 );
1053 let runs = 30;
1054 let t = std::time::Instant::now();
1055 for _ in 0..runs {
1056 scale_i420(
1057 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1058 );
1059 }
1060 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1061 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1062 }
1063
1064 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1065 /// scale and blit -- which is what the playback budget has to hold. Printed,
1066 /// not asserted, like every other perf test here.
1067 #[test]
1068 fn perf_compose_720p_onto_1080p() {
1069 let src = gradient(1280, 720);
1070 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1071 let runs = 30;
1072 let t = std::time::Instant::now();
1073 for _ in 0..runs {
1074 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1075 }
1076 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1077 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1078 }
1079}