forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB99d87d4Tahinli3 months ago508 commits

scale.rs1100 lines, 42.2 KiBHistoryRawDownload
1//! I420 rescale and frame placement: the primitive a project resolution needs.
2//!
3//! A timeline has one resolution; the media on it does not. Everything a
4//! mixed-resolution timeline asks for is these three pieces:
5//!
6//! * [`scale_i420`] resamples a planar frame to another size,
7//! * [`fit_rect`] is the pure geometry -- where the scaled picture lands on the
8//! project canvas, and which part of the source it comes from, under one of
9//! four [`FitPolicy`] rules,
10//! * [`compose_i420`] blits the scaled picture onto a canvas, so the pixels a
11//! letterbox leaves over stay whatever the canvas was filled with
12//! ([`black_i420`] is that fill).
13//!
14//! The filter is bilinear in 16.16 fixed point: two taps per axis, column
15//! weights precomputed once per plane, no float and no division in the pixel
16//! loop. That is the honest quality level for v1 -- a downscale by more than 2x
17//! aliases, because two taps cannot carry a wider kernel. The upgrade path is a
18//! separable Lanczos-3 (or a box prefilter before the bilinear pass) behind the
19//! same signature: nothing here exposes the tap count. 1280x720 -> 1920x1080
20//! measures 3.82 ms/frame in release (`perf_720p_to_1080p` below), against the
21//! 4.7 ms the BGRA conversion next door already costs per frame.
22//!
23//! Sample siting: each plane is resampled as its own image with centre-aligned
24//! mapping, `src = (dst + 0.5) * src_len / dst_len - 0.5`. For chroma that
25//! treats I420 as centre-sited where MPEG-2 calls it left-sited, a quarter-
26//! chroma-sample bias that no eye finds and that a siting-aware kernel would fix
27//! in the same place the Lanczos upgrade goes.
28
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/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of
349/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a
350/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at
351/// 4096x2160 (the floor), all measured. A worker holds one more than this in its
352/// hand, so a burst off a full queue is `queue_depth + 1`.
353///
354/// The floor of 2 is the bound this engine ran on everywhere before there was
355/// any decode-ahead; the ceiling keeps a small picture from queueing a second of
356/// video the consumer would have to walk through after a seek.
357pub(crate) fn queue_depth(width: u32, height: u32) -> usize {
358 const BUDGET: usize = 96 << 20;
359 let bytes = width as usize * height as usize * 4;
360 if bytes == 0 {
361 return 2;
362 }
363 (BUDGET / bytes).clamp(2, 16)
364}
365
366/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
367/// hands the caller's own planes straight back, allocates nothing and touches no
368/// byte, which is what keeps a project at its media's resolution the byte-for-byte
369/// path it was before there was a project resolution at all.
370///
371/// [`place`]: Composer::place
372pub struct Composer {
373 width: u32,
374 height: u32,
375 policy: FitPolicy,
376 /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
377 /// `Center` ever crop, so this stays empty for a letterboxed project.
378 crop: (Vec<u8>, Vec<u8>, Vec<u8>),
379 /// The crop resampled to the placement rect.
380 scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
381 /// The canvas itself, refilled with black every frame -- a memset against a
382 /// decode, and the only way a policy change cannot leave last frame's bars
383 /// showing through.
384 canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
385}
386
387impl Composer {
388 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
389 let empty = || (Vec::new(), Vec::new(), Vec::new());
390 Self {
391 width,
392 height,
393 policy,
394 crop: empty(),
395 scaled: empty(),
396 canvas: empty(),
397 }
398 }
399
400 /// A composer that places nothing: every picture passes through at its own
401 /// size. What the file-level decode API opens with, where there is no
402 /// project and therefore no canvas.
403 pub fn passthrough() -> Self {
404 Self::new(0, 0, FitPolicy::Fit)
405 }
406
407 /// Whether this canvas is the one that places nothing
408 /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand,
409 /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that
410 /// needs it is sizing a queue before anything has been decoded.
411 pub(crate) fn places_nothing(&self) -> bool {
412 self.width == 0 || self.height == 0
413 }
414
415 /// How many decoded pictures a worker over this canvas may keep ahead of
416 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
417 /// than a 1080p one instead of the same number of far bigger frames.
418 ///
419 /// A **pass-through** canvas has no size of its own -- the pictures come out
420 /// at the source's -- so it cannot answer, and the caller that knows the
421 /// stream asks [`queue_depth`] with those dimensions instead. Answering 2
422 /// here would be the pre-decode-ahead bound, which is exactly the bug this
423 /// pair exists to keep out of the file-open path.
424 pub(crate) fn queue_depth(&self) -> usize {
425 queue_depth(self.width, self.height)
426 }
427
428 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
429 /// composer would hand it back untouched. What lets a caller keep a fused
430 /// fast path (the graded conversion) for the common case.
431 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
432 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
433 }
434
435 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
436 /// caller's own planes (pass-through) or the canvas with the fitted picture
437 /// composed onto it. The dimensions come back because those two differ.
438 ///
439 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
440 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
441 pub fn place<'a>(
442 &'a mut self,
443 y: &'a [u8],
444 u: &'a [u8],
445 v: &'a [u8],
446 src_w: u32,
447 src_h: u32,
448 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
449 if self.is_passthrough(src_w, src_h) {
450 return (y, u, v, src_w, src_h);
451 }
452 let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
453 let (sw, sh) = (src_w as usize, src_h as usize);
454
455 // Crop first, so the scaler only ever sees a tightly packed plane. Fit
456 // and Stretch never crop, which is the whole cost of the common case.
457 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
458 (y, u, v)
459 } else {
460 crop_i420(&mut self.crop, y, u, v, sw, sh, src);
461 (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
462 };
463 // ...then resample it to the placement, unless it already is that size
464 // (`Center` never resamples, and neither does an exact-fit upscale).
465 let (cw, ch) = (src.w as usize, src.h as usize);
466 let (dw, dh) = (dst.w as usize, dst.h as usize);
467 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
468 (src_y, src_u, src_v)
469 } else {
470 let (ccw, cch) = chroma_dims(dw, dh);
471 let (sy, su, sv) = &mut self.scaled;
472 sy.resize(dw * dh, 0);
473 su.resize(ccw * cch, 0);
474 sv.resize(ccw * cch, 0);
475 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
476 (&sy[..], &su[..], &sv[..])
477 };
478
479 let (w, h) = (self.width as usize, self.height as usize);
480 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
481 let (ky, ku, kv) = &mut self.canvas;
482 fill(ky, w * h, BLACK_Y);
483 fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
484 fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
485 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
486 (ky, ku, kv, self.width, self.height)
487 }
488}
489
490/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
491/// across frames is refilled, not reallocated.
492fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
493 plane.clear();
494 plane.resize(len, value);
495}
496
497/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
498/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
499/// crop is exactly half of it.
500fn crop_i420(
501 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
502 y: &[u8],
503 u: &[u8],
504 v: &[u8],
505 src_w: usize,
506 src_h: usize,
507 rect: Rect,
508) {
509 let (w, h) = (rect.w as usize, rect.h as usize);
510 let (x, cy0) = (rect.x as usize, rect.y as usize);
511 let (src_cw, _) = chroma_dims(src_w, src_h);
512 let (cw, ch) = chroma_dims(w, h);
513 let (oy, ou, ov) = out;
514 oy.clear();
515 ou.clear();
516 ov.clear();
517 for row in 0..h {
518 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
519 }
520 let (cx, cy0) = (x / 2, cy0 / 2);
521 for row in 0..ch {
522 let at = (cy0 + row) * src_cw + cx;
523 ou.extend_from_slice(&u[at..][..cw]);
524 ov.extend_from_slice(&v[at..][..cw]);
525 }
526 debug_assert_eq!(oy.len(), w * h);
527 debug_assert_eq!(ou.len(), cw * ch);
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533
534 /// Allocates the destination planes for a size and runs a scale into them.
535 fn scaled(
536 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
537 src_w: usize,
538 src_h: usize,
539 dst_w: usize,
540 dst_h: usize,
541 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
542 let (cw, ch) = chroma_dims(dst_w, dst_h);
543 let mut dst = (
544 vec![0u8; dst_w * dst_h],
545 vec![0u8; cw * ch],
546 vec![0u8; cw * ch],
547 );
548 scale_i420(
549 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
550 );
551 dst
552 }
553
554 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
555 let (cw, ch) = chroma_dims(w, h);
556 (
557 (0..w * h).map(|i| (i % 256) as u8).collect(),
558 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
559 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
560 )
561 }
562
563 /// The pass-through invariant: a project at the media's own resolution must
564 /// hand the decoder's bytes to the encoder unchanged.
565 #[test]
566 fn identity_scale_is_byte_identical() {
567 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
568 let src = gradient(w, h);
569 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
570 }
571 }
572
573 /// Halving is the one case where bilinear is exactly a 2x2 box average:
574 /// the output centre falls on the shared corner of four input samples.
575 /// 0/254 averages to 127 with no rounding slack at all.
576 #[test]
577 fn downscale_by_two_averages_a_checkerboard() {
578 let (w, h) = (32, 24);
579 let (cw, ch) = chroma_dims(w, h);
580 let checker = |i: usize, stride: usize| {
581 if (i / stride + i % stride).is_multiple_of(2) {
582 0u8
583 } else {
584 254
585 }
586 };
587 let src = (
588 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
589 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
590 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
591 );
592 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
593 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
594 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
595 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
596 }
597
598 /// Nothing may leak in from outside a plane: a flat frame stays flat at
599 /// every edge, upscaled and downscaled, odd sizes included.
600 #[test]
601 fn flat_frame_stays_flat() {
602 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
603 for &(sw, sh) in &sizes {
604 let (cw, ch) = chroma_dims(sw, sh);
605 let src = (
606 vec![80u8; sw * sh],
607 vec![90u8; cw * ch],
608 vec![200u8; cw * ch],
609 );
610 for &(dw, dh) in &sizes {
611 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
612 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
613 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
614 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
615 }
616 }
617 }
618
619 /// Chroma alignment: an edge in the U plane must land at the *same* place
620 /// after a 2x upscale, with a symmetric two-sample blend around it and
621 /// untouched flats either side -- a half-sample bias shows up as an
622 /// asymmetric pair here, which is colour bleeding one way.
623 #[test]
624 fn chroma_edge_keeps_its_position() {
625 let (w, h) = (8, 8);
626 let (cw, ch) = chroma_dims(w, h);
627 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
628 let src = (
629 vec![80u8; w * h],
630 (0..cw * ch)
631 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
632 .collect(),
633 vec![128u8; cw * ch],
634 );
635 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
636 let (dcw, _) = chroma_dims(w * 2, h * 2);
637 assert_eq!(dcw, 8);
638 let row = &u[dcw * 3..][..dcw];
639 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
640 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
641 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
642 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
643 // most 1; anything further means the edge moved.
644 assert!(
645 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
646 "blend is off centre, i.e. chroma bled one way: {row:?}"
647 );
648 }
649
650 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
651 /// `(src, dst, policy) -> (placement, crop)`.
652 #[test]
653 fn fit_rect_table() {
654 let r = |x, y, w, h| Rect { x, y, w, h };
655 let cases = [
656 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
657 (
658 (1920, 1080),
659 (640, 480),
660 FitPolicy::Fit,
661 r(0, 60, 640, 360),
662 r(0, 0, 1920, 1080),
663 ),
664 // ...and the same pair filled: the canvas is whole, the source is
665 // cropped to 4:3 (1440 wide) about its centre.
666 (
667 (1920, 1080),
668 (640, 480),
669 FitPolicy::Fill,
670 r(0, 0, 640, 480),
671 r(240, 0, 1440, 1080),
672 ),
673 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
674 (
675 (640, 480),
676 (1920, 1080),
677 FitPolicy::Fit,
678 r(240, 0, 1440, 1080),
679 r(0, 0, 640, 480),
680 ),
681 (
682 (640, 480),
683 (1920, 1080),
684 FitPolicy::Fill,
685 r(0, 0, 1920, 1080),
686 r(0, 60, 640, 360),
687 ),
688 // Stretch ignores aspect entirely, both ways.
689 (
690 (1920, 1080),
691 (640, 480),
692 FitPolicy::Stretch,
693 r(0, 0, 640, 480),
694 r(0, 0, 1920, 1080),
695 ),
696 // 1:1 with a bigger source: cropped both ways, centred.
697 (
698 (1920, 1080),
699 (640, 480),
700 FitPolicy::Center,
701 r(0, 0, 640, 480),
702 r(640, 300, 640, 480),
703 ),
704 // 1:1 with a smaller source: padded both ways, centred.
705 (
706 (640, 480),
707 (1920, 1080),
708 FitPolicy::Center,
709 r(640, 300, 640, 480),
710 r(0, 0, 640, 480),
711 ),
712 // Odd sizes: offsets even, sizes even unless they reach the edge.
713 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
714 (
715 (7, 5),
716 (13, 9),
717 FitPolicy::Fit,
718 r(0, 0, 13, 9),
719 r(0, 0, 7, 5),
720 ),
721 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
722 // offset without putting chroma half a sample off, so the last one
723 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
724 (
725 (9, 9),
726 (13, 9),
727 FitPolicy::Center,
728 r(2, 0, 8, 9),
729 r(0, 0, 8, 9),
730 ),
731 (
732 (13, 9),
733 (9, 9),
734 FitPolicy::Center,
735 r(0, 0, 8, 9),
736 r(2, 0, 8, 9),
737 ),
738 ];
739 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
740 let got = fit_rect(sw, sh, dw, dh, policy);
741 assert_eq!(
742 got,
743 (want_dst, want_src),
744 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
745 );
746 }
747 // Degenerate input is empty, not a panic.
748 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
749 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
750 }
751
752 /// Every rect a policy hands back must sit inside its plane, start on the
753 /// chroma grid, and end on it or at the plane edge -- the invariant
754 /// `compose_i420` relies on.
755 #[test]
756 fn fit_rect_stays_on_the_chroma_grid() {
757 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
758 for policy in [
759 FitPolicy::Fit,
760 FitPolicy::Fill,
761 FitPolicy::Stretch,
762 FitPolicy::Center,
763 ] {
764 for &sw in &sizes {
765 for &dh in &sizes {
766 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
767 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
768 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
769 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
770 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
771 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
772 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
773 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
774 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
775 // A plane one sample wide or high has no chroma grid to
776 // be on: `Center` from a 2-high source onto a 1-high
777 // canvas is one row, and no size satisfies both edges.
778 // Nothing real is that shape; it must merely not
779 // escape its plane, which the two asserts above cover.
780 if grid {
781 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
782 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
783 }
784 assert!(!rect.is_empty(), "{ctx} empty");
785 }
786 }
787 }
788 }
789 }
790
791 #[test]
792 fn compose_fills_the_rect_and_nothing_else() {
793 let (cw2, ch2) = (640usize, 360usize);
794 let (canvas_w, canvas_h) = (640usize, 480usize);
795 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
796 let (fcw, fch) = chroma_dims(cw2, ch2);
797 let frame = (
798 vec![200u8; cw2 * ch2],
799 vec![70u8; fcw * fch],
800 vec![30u8; fcw * fch],
801 );
802 let rect = Rect {
803 x: 0,
804 y: 60,
805 w: cw2 as u32,
806 h: ch2 as u32,
807 };
808 compose_i420(
809 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
810 );
811
812 for row in 0..canvas_h {
813 let inside = (60..420).contains(&row);
814 let want = if inside { 200 } else { BLACK_Y };
815 assert!(
816 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
817 "luma row {row}"
818 );
819 }
820 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
821 for row in 0..cch {
822 let inside = (30..210).contains(&row);
823 let (wu, wv) = if inside {
824 (70, 30)
825 } else {
826 (NEUTRAL_C, NEUTRAL_C)
827 };
828 assert!(
829 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
830 "U row {row}"
831 );
832 assert!(
833 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
834 "V row {row}"
835 );
836 }
837 }
838
839 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
840 /// is public and a caller may compute a rect itself.
841 #[test]
842 fn compose_clips_a_rect_that_runs_off_the_canvas() {
843 let (mut y, mut u, mut v) = black_i420(16, 16);
844 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
845 let rect = Rect {
846 x: 12,
847 y: 12,
848 w: 8,
849 h: 8,
850 };
851 compose_i420(
852 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
853 );
854 assert_eq!(y[15 * 16 + 15], 99);
855 assert_eq!(y[11 * 16 + 15], BLACK_Y);
856 // Wholly outside: no write at all.
857 let before = y.clone();
858 compose_i420(
859 &mut y,
860 &mut u,
861 &mut v,
862 16,
863 16,
864 &frame.0,
865 &frame.1,
866 &frame.2,
867 Rect {
868 x: 100,
869 y: 0,
870 w: 8,
871 h: 8,
872 },
873 );
874 assert_eq!(y, before);
875 }
876
877 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
878 /// project canvas, letterbox bars intact.
879 #[test]
880 fn fit_scale_compose_letterboxes() {
881 let (sw, sh) = (640usize, 480usize);
882 let (dw, dh) = (1920usize, 1080usize);
883 let src = gradient(sw, sh);
884 let (dst_rect, src_rect) =
885 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
886 assert_eq!(
887 src_rect,
888 Rect {
889 x: 0,
890 y: 0,
891 w: 640,
892 h: 480
893 }
894 );
895 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
896 let picture = scaled(&src, sw, sh, rw, rh);
897 let (mut y, mut u, mut v) = black_i420(dw, dh);
898 compose_i420(
899 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
900 );
901 // Pillarbox columns stay black, the picture area does not.
902 let mid = (dh / 2) * dw;
903 assert!(
904 y[mid..mid + dst_rect.x as usize]
905 .iter()
906 .all(|&s| s == BLACK_Y)
907 );
908 assert_eq!(
909 y[mid + dst_rect.x as usize..][..rw],
910 picture.0[(rh / 2) * rw..][..rw]
911 );
912 }
913
914 /// The wiring invariant: a project at its media's own resolution hands the
915 /// decoder's own slices back, not a copy that happens to be equal. Asserted
916 /// on the pointer, because "identical bytes" is cheap and "no work at all"
917 /// is what the common case is promised.
918 #[test]
919 fn a_canvas_of_the_source_size_is_a_pass_through() {
920 let (w, h) = (64usize, 48usize);
921 let src = gradient(w, h);
922 for mut canvas in [
923 Composer::new(w as u32, h as u32, FitPolicy::Fit),
924 Composer::new(w as u32, h as u32, FitPolicy::Fill),
925 Composer::new(w as u32, h as u32, FitPolicy::Center),
926 Composer::passthrough(),
927 ] {
928 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
929 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
930 assert_eq!(u.as_ptr(), src.1.as_ptr());
931 assert_eq!(v.as_ptr(), src.2.as_ptr());
932 assert_eq!((cw, ch), (w as u32, h as u32));
933 }
934 }
935
936 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
937 /// the pillarbox columns are limited-range black, exactly -- a bar that is
938 /// merely dark is a bar the grade reached.
939 #[test]
940 fn fit_pillarboxes_with_exact_black_bars() {
941 let (sw, sh) = (640u32, 480u32);
942 let (dw, dh) = (1920u32, 1080u32);
943 let src = (
944 vec![200u8; (sw * sh) as usize],
945 vec![70u8; (sw * sh / 4) as usize],
946 vec![30u8; (sw * sh / 4) as usize],
947 );
948 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
949 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
950 assert_eq!((w, h), (dw, dh));
951 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
952 assert_eq!(
953 rect,
954 Rect {
955 x: 240,
956 y: 0,
957 w: 1440,
958 h: 1080
959 },
960 "geometry moved"
961 );
962 let (w, h) = (w as usize, h as usize);
963 let row = &y[(h / 2) * w..][..w];
964 let x = rect.x as usize;
965 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
966 assert!(
967 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
968 "right bar not black"
969 );
970 assert!(
971 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
972 "picture"
973 );
974 // ...and the bars are neutral in chroma too, or they would be a colour.
975 let (cw, _) = chroma_dims(w, h);
976 let crow = &u[(h / 4) * cw..][..cw];
977 assert!(
978 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
979 "bar has colour"
980 );
981 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
982 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
983 }
984
985 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
986 /// the canvas (no bar anywhere), `Center` pads without resampling.
987 #[test]
988 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
989 let (sw, sh) = (640u32, 480u32);
990 let (dw, dh) = (1920u32, 1080u32);
991 let src = (
992 vec![200u8; (sw * sh) as usize],
993 vec![70u8; (sw * sh / 4) as usize],
994 vec![30u8; (sw * sh / 4) as usize],
995 );
996 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
997 let mut canvas = Composer::new(dw, dh, policy);
998 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
999 assert!(
1000 y.iter().all(|&s| s == 200),
1001 "{policy:?} left a bar: the canvas is not covered"
1002 );
1003 }
1004 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1005 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1006 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1007 assert_eq!(rect.w, sw, "Center resampled the picture");
1008 let (w, h) = (w as usize, h as usize);
1009 let row = &y[(h / 2) * w..][..w];
1010 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1011 assert!(
1012 row[rect.x as usize..][..sw as usize]
1013 .iter()
1014 .all(|&s| s == 200)
1015 );
1016 }
1017
1018 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1019 /// picture, chroma with it: a marked band at a known column has to come out
1020 /// at the column the geometry puts it at.
1021 #[test]
1022 fn fill_crops_about_the_centre() {
1023 let (sw, sh) = (32usize, 8usize);
1024 let (dw, dh) = (8u32, 8u32);
1025 // Column 16 (the centre) is bright, everything else is dark.
1026 let y: Vec<u8> = (0..sw * sh)
1027 .map(|i| if i % sw == 16 { 240 } else { 40 })
1028 .collect();
1029 let (cw, ch) = chroma_dims(sw, sh);
1030 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1031 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1032 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1033 assert_eq!((w, h), (dw, dh));
1034 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1035 assert_eq!(
1036 dst,
1037 Rect {
1038 x: 0,
1039 y: 0,
1040 w: 8,
1041 h: 8
1042 },
1043 "Fill must cover"
1044 );
1045 assert_eq!(
1046 crop,
1047 Rect {
1048 x: 12,
1049 y: 0,
1050 w: 8,
1051 h: 8
1052 },
1053 "crop off centre"
1054 );
1055 // The bright column is crop-relative column 4 of 8, untouched by the
1056 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1057 let row = &y[..8];
1058 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1059 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1060 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1061 }
1062
1063 /// Not asserted: only the release number means anything. Run with
1064 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1065 #[test]
1066 fn perf_720p_to_1080p() {
1067 let src = gradient(1280, 720);
1068 let (cw, ch) = chroma_dims(1920, 1080);
1069 let mut dst = (
1070 vec![0u8; 1920 * 1080],
1071 vec![0u8; cw * ch],
1072 vec![0u8; cw * ch],
1073 );
1074 let runs = 30;
1075 let t = std::time::Instant::now();
1076 for _ in 0..runs {
1077 scale_i420(
1078 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1079 );
1080 }
1081 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1082 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1083 }
1084
1085 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1086 /// scale and blit -- which is what the playback budget has to hold. Printed,
1087 /// not asserted, like every other perf test here.
1088 #[test]
1089 fn perf_compose_720p_onto_1080p() {
1090 let src = gradient(1280, 720);
1091 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1092 let runs = 30;
1093 let t = std::time::Instant::now();
1094 for _ in 0..runs {
1095 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1096 }
1097 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1098 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1099 }
1100}