forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5984e27Tahinli3 months ago583 commits

scale.rs1355 lines, 53.0 KiBHistoryRawDownload
1//! I420 rescale and frame placement: the primitive a project resolution needs.
2//!
3//! A timeline has one resolution; the media on it does not. Everything a
4//! mixed-resolution timeline asks for is these three pieces:
5//!
6//! * [`scale_i420`] resamples a planar frame to another size,
7//! * [`fit_rect`] is the pure geometry -- where the scaled picture lands on the
8//! project canvas, and which part of the source it comes from, under one of
9//! four [`FitPolicy`] rules,
10//! * [`compose_i420`] blits the scaled picture onto a canvas, so the pixels a
11//! letterbox leaves over stay whatever the canvas was filled with
12//! ([`black_i420`] is that fill).
13//!
14//! The filter is bilinear in 16.16 fixed point: two taps per axis, column
15//! weights precomputed once per plane, no float and no division in the pixel
16//! loop. That is the honest quality level for v1 -- a downscale by more than 2x
17//! aliases, because two taps cannot carry a wider kernel. The upgrade path is a
18//! separable Lanczos-3 (or a box prefilter before the bilinear pass) behind the
19//! same signature: nothing here exposes the tap count. 1280x720 -> 1920x1080
20//! measures 3.82 ms/frame in release (`perf_720p_to_1080p` below), against the
21//! 4.7 ms the BGRA conversion next door already costs per frame.
22//!
23//! Sample siting: each plane is resampled as its own image with centre-aligned
24//! mapping, `src = (dst + 0.5) * src_len / dst_len - 0.5`. For chroma that
25//! treats I420 as centre-sited where MPEG-2 calls it left-sited, a quarter-
26//! chroma-sample bias that no eye finds and that a siting-aware kernel would fix
27//! in the same place the Lanczos upgrade goes.
28
29use crate::transform::TransformParams;
30
31/// Limited-range black: what an untouched canvas pixel is.
32pub const BLACK_Y: u8 = 16;
33/// Neutral chroma: 128 in both planes.
34pub const NEUTRAL_C: u8 = 128;
35
36/// A rectangle on one plane, in luma samples. Always inside the plane it
37/// describes; `fit_rect` never hands back one that is not.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct Rect {
40 pub x: u32,
41 pub y: u32,
42 pub w: u32,
43 pub h: u32,
44}
45
46impl Rect {
47 pub fn is_empty(&self) -> bool {
48 self.w == 0 || self.h == 0
49 }
50}
51
52/// How a source picture of one shape meets a canvas of another.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum FitPolicy {
55 /// Whole picture, aspect kept, centred -- the leftover canvas is bars.
56 #[default]
57 Fit,
58 /// Whole canvas, aspect kept, centred -- the leftover picture is cropped.
59 Fill,
60 /// Whole picture on the whole canvas; aspect is not kept.
61 Stretch,
62 /// No resampling at all: 1:1 samples, centred, padded or cropped per axis.
63 Center,
64}
65
66/// Placement and crop for one source on one canvas.
67///
68/// Returns `(dst placement rect on the canvas, src crop rect on the source)`.
69/// The caller scales the crop to the placement size and composes it there; a
70/// `Center` result has the two rects the same size, i.e. nothing to scale.
71///
72/// Rounding, and why it is what it is: both rects are aligned to the I420
73/// chroma grid, so that one chroma sample of the scaled picture is one chroma
74/// sample of the canvas and no colour lands half a sample off. `x` and `y` are
75/// floored to even; `w` and `h` are floored to even *unless* the rect ends
76/// exactly at the plane edge, where an odd size is fine because both grids end
77/// together (that is what keeps an equal-size `Fit` a byte-exact pass-through
78/// on an odd-width source). The alignment can therefore cost one sample of
79/// aspect accuracy -- under a tenth of a percent at any real resolution.
80///
81/// A zero-sized canvas or source yields two empty rects. An extreme aspect
82/// never rounds the picture away: the smallest rect is one chroma sample (2x2),
83/// clipped to the plane. A plane one sample wide or high has no grid to align
84/// to and keeps that single sample.
85pub fn fit_rect(src_w: u32, src_h: u32, dst_w: u32, dst_h: u32, policy: FitPolicy) -> (Rect, Rect) {
86 let empty = Rect {
87 x: 0,
88 y: 0,
89 w: 0,
90 h: 0,
91 };
92 if src_w == 0 || src_h == 0 || dst_w == 0 || dst_h == 0 {
93 return (empty, empty);
94 }
95 let full_src = Rect {
96 x: 0,
97 y: 0,
98 w: src_w,
99 h: src_h,
100 };
101 let full_dst = Rect {
102 x: 0,
103 y: 0,
104 w: dst_w,
105 h: dst_h,
106 };
107
108 match policy {
109 FitPolicy::Stretch => (full_dst, full_src),
110 FitPolicy::Fit => {
111 // Widest box with the source aspect that still fits the canvas.
112 let (w, h) =
113 if u64::from(src_w) * u64::from(dst_h) <= u64::from(dst_w) * u64::from(src_h) {
114 (ratio(src_w, dst_h, src_h).min(dst_w), dst_h)
115 } else {
116 (dst_w, ratio(src_h, dst_w, src_w).min(dst_h))
117 };
118 (centred(w, h, dst_w, dst_h), full_src)
119 }
120 FitPolicy::Fill => {
121 // Largest box with the canvas aspect that still fits the source.
122 let (w, h) =
123 if u64::from(src_w) * u64::from(dst_h) >= u64::from(dst_w) * u64::from(src_h) {
124 (ratio(src_h, dst_w, dst_h).min(src_w), src_h)
125 } else {
126 (src_w, ratio(src_w, dst_h, dst_w).min(src_h))
127 };
128 (full_dst, centred(w, h, src_w, src_h))
129 }
130 FitPolicy::Center => {
131 let w = src_w.min(dst_w);
132 let h = src_h.min(dst_h);
133 let dst = centred(w, h, dst_w, dst_h);
134 let src = centred(w, h, src_w, src_h);
135 // Even-alignment may have shrunk one of them; 1:1 means both carry
136 // the same sample count, so take the smaller of the two.
137 let w = dst.w.min(src.w);
138 let h = dst.h.min(src.h);
139 (Rect { w, h, ..dst }, Rect { w, h, ..src })
140 }
141 }
142}
143
144/// `value * num / den`, rounded to nearest, in 64-bit so 8K x 8K cannot wrap.
145fn ratio(value: u32, num: u32, den: u32) -> u32 {
146 let den = u64::from(den).max(1);
147 ((u64::from(value) * u64::from(num) + den / 2) / den) as u32
148}
149
150/// A `w` x `h` box centred in `extent_w` x `extent_h`, chroma-grid aligned.
151fn centred(w: u32, h: u32, extent_w: u32, extent_h: u32) -> Rect {
152 let (x, w) = align(extent_w.saturating_sub(w) / 2, w, extent_w);
153 let (y, h) = align(extent_h.saturating_sub(h) / 2, h, extent_h);
154 Rect { x, y, w, h }
155}
156
157/// Floors the offset to even, clips the size into the plane, and floors the
158/// size to even unless the rect ends at the plane edge.
159fn align(offset: u32, size: u32, extent: u32) -> (u32, u32) {
160 let offset = (offset & !1).min(extent);
161 let mut size = size.min(extent - offset);
162 if offset + size < extent {
163 size &= !1;
164 }
165 if size == 0 {
166 // An extreme aspect (a 1-sample-wide source) would otherwise round its
167 // picture away entirely. One chroma sample is the floor, not zero.
168 size = extent.min(2);
169 }
170 (offset, size)
171}
172
173/// Chroma plane size for a luma dimension: `(w + 1) / 2`, both axes.
174pub fn chroma_dims(w: usize, h: usize) -> (usize, usize) {
175 (w.div_ceil(2), h.div_ceil(2))
176}
177
178/// A `w` x `h` I420 canvas filled with limited-range black.
179pub fn black_i420(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
180 let (cw, ch) = chroma_dims(w, h);
181 (
182 vec![BLACK_Y; w * h],
183 vec![NEUTRAL_C; cw * ch],
184 vec![NEUTRAL_C; cw * ch],
185 )
186}
187
188/// Resamples a tightly packed I420 frame (stride == width) into another one.
189///
190/// Equal dimensions copy byte for byte -- a project at the media's own
191/// resolution is not a resample. Otherwise each plane is bilinear-filtered
192/// independently, chroma at its own `(w + 1) / 2` size, so odd dimensions need
193/// no special case: a 7x5 source has a 4x3 chroma plane and a 13x9 destination
194/// wants a 7x5 one, and that is just another rescale.
195///
196/// Panics if a slice is not exactly its plane's size; a mis-sized buffer is a
197/// caller bug, not a runtime condition, and every alternative silently produces
198/// a sheared picture.
199#[allow(clippy::too_many_arguments)]
200pub fn scale_i420(
201 src_y: &[u8],
202 src_u: &[u8],
203 src_v: &[u8],
204 src_w: usize,
205 src_h: usize,
206 dst_y: &mut [u8],
207 dst_u: &mut [u8],
208 dst_v: &mut [u8],
209 dst_w: usize,
210 dst_h: usize,
211) {
212 let (src_cw, src_ch) = chroma_dims(src_w, src_h);
213 let (dst_cw, dst_ch) = chroma_dims(dst_w, dst_h);
214 assert_eq!(src_y.len(), src_w * src_h, "source luma plane");
215 assert_eq!(src_u.len(), src_cw * src_ch, "source U plane");
216 assert_eq!(src_v.len(), src_cw * src_ch, "source V plane");
217 assert_eq!(dst_y.len(), dst_w * dst_h, "destination luma plane");
218 assert_eq!(dst_u.len(), dst_cw * dst_ch, "destination U plane");
219 assert_eq!(dst_v.len(), dst_cw * dst_ch, "destination V plane");
220
221 if src_w == dst_w && src_h == dst_h {
222 dst_y.copy_from_slice(src_y);
223 dst_u.copy_from_slice(src_u);
224 dst_v.copy_from_slice(src_v);
225 return;
226 }
227 plane(src_y, src_w, src_h, dst_y, dst_w, dst_h);
228 plane(src_u, src_cw, src_ch, dst_u, dst_cw, dst_ch);
229 plane(src_v, src_cw, src_ch, dst_v, dst_cw, dst_ch);
230}
231
232/// 16.16 fixed point: one whole sample step.
233const ONE: u32 = 1 << 16;
234const HALF: u32 = ONE / 2;
235
236/// The two source samples and the weight of the second one, for one output
237/// position: `src = (dst + 0.5) * src_len / dst_len - 0.5`, clamped to the
238/// plane so the edges replicate instead of reading past it.
239fn taps(dst_len: usize, src_len: usize) -> Vec<(u32, u32, u32)> {
240 let step = (src_len as u64) * u64::from(ONE) / dst_len as u64;
241 let last = src_len as u32 - 1;
242 (0..dst_len)
243 .map(|i| {
244 // (i + 0.5) * step - 0.5, kept in u64 until the subtraction so the
245 // clamp at 0 is the only place a negative could have appeared.
246 let centre = (2 * i as u64 + 1) * step / 2;
247 let pos = centre.saturating_sub(u64::from(HALF));
248 let whole = ((pos >> 16) as u32).min(last);
249 let frac = if whole == last {
250 0
251 } else {
252 (pos as u32) & (ONE - 1)
253 };
254 (whole, (whole + 1).min(last), frac)
255 })
256 .collect()
257}
258
259/// Bilinear resample of one tightly packed 8-bit plane.
260fn plane(src: &[u8], src_w: usize, src_h: usize, dst: &mut [u8], dst_w: usize, dst_h: usize) {
261 if dst_w == 0 || dst_h == 0 || src_w == 0 || src_h == 0 {
262 return;
263 }
264 let cols = taps(dst_w, src_w);
265 let rows = taps(dst_h, src_h);
266
267 for (y, &(y0, y1, wy)) in rows.iter().enumerate() {
268 let top = &src[y0 as usize * src_w..][..src_w];
269 let bottom = &src[y1 as usize * src_w..][..src_w];
270 let inv_wy = ONE - wy;
271 let out = &mut dst[y * dst_w..][..dst_w];
272 for (o, &(x0, x1, wx)) in out.iter_mut().zip(cols.iter()) {
273 let inv_wx = ONE - wx;
274 let (x0, x1) = (x0 as usize, x1 as usize);
275 // Each stage stays under 255 * 65536 + 32768, well inside u32.
276 let a = (u32::from(top[x0]) * inv_wx + u32::from(top[x1]) * wx + HALF) >> 16;
277 let b = (u32::from(bottom[x0]) * inv_wx + u32::from(bottom[x1]) * wx + HALF) >> 16;
278 *o = ((a * inv_wy + b * wy + HALF) >> 16) as u8;
279 }
280 }
281}
282
283/// Blits a frame of exactly `rect.w` x `rect.h` onto a canvas at `rect`.
284///
285/// The rect is clipped to the canvas first, so a rect from anywhere (not just
286/// [`fit_rect`]) is safe; a clipped blit copies the part that fits, from the
287/// frame's top-left. Everything outside the rect keeps whatever the canvas
288/// already held -- [`black_i420`] for a letterbox.
289///
290/// Chroma rounding: `rect.x/2` and `rect.y/2` address the canvas chroma plane,
291/// which is exact because [`fit_rect`] hands back even offsets. An odd offset
292/// would put the frame's chroma half a sample off its own grid, so it is
293/// floored to even here rather than silently smeared.
294#[allow(clippy::too_many_arguments)]
295pub fn compose_i420(
296 canvas_y: &mut [u8],
297 canvas_u: &mut [u8],
298 canvas_v: &mut [u8],
299 canvas_w: usize,
300 canvas_h: usize,
301 frame_y: &[u8],
302 frame_u: &[u8],
303 frame_v: &[u8],
304 rect: Rect,
305) {
306 let x = (rect.x & !1) as usize;
307 let y = (rect.y & !1) as usize;
308 if x >= canvas_w || y >= canvas_h {
309 return;
310 }
311 let fw = rect.w as usize;
312 let fh = rect.h as usize;
313 let w = fw.min(canvas_w - x);
314 let h = fh.min(canvas_h - y);
315 if w == 0 || h == 0 {
316 return;
317 }
318 for row in 0..h {
319 canvas_y[(y + row) * canvas_w + x..][..w].copy_from_slice(&frame_y[row * fw..][..w]);
320 }
321
322 let (canvas_cw, _) = chroma_dims(canvas_w, canvas_h);
323 let (fcw, _) = chroma_dims(fw, fh);
324 // Half-resolution copy of the clipped luma region, rounded up so an odd
325 // width still carries its last (half-covered) chroma sample.
326 let (cw, ch) = chroma_dims(w, h);
327 let (cx, cy) = (x / 2, y / 2);
328 for row in 0..ch {
329 let dst = (cy + row) * canvas_cw + cx;
330 canvas_u[dst..][..cw].copy_from_slice(&frame_u[row * fcw..][..cw]);
331 canvas_v[dst..][..cw].copy_from_slice(&frame_v[row * fcw..][..cw]);
332 }
333}
334
335/// The source rect [`TransformParams`]'s crop fractions cut out of a `src_w` x
336/// `src_h` picture, chroma-grid aligned exactly as [`fit_rect`]'s rects are.
337/// Fractions are clamped to `0.0..=0.5` a side, so opposing crops can never
338/// meet or cross -- the smallest surviving rect is one chroma sample, for
339/// [`align`]'s reason.
340pub fn crop_rect(src_w: u32, src_h: u32, t: &TransformParams) -> Rect {
341 if src_w == 0 || src_h == 0 {
342 return Rect { x: 0, y: 0, w: 0, h: 0 };
343 }
344 let (cl, cr) = (t.crop_l.clamp(0.0, 0.5), t.crop_r.clamp(0.0, 0.5));
345 let (ct, cb) = (t.crop_t.clamp(0.0, 0.5), t.crop_b.clamp(0.0, 0.5));
346 let x0 = (f64::from(src_w) * f64::from(cl)).round() as u32;
347 let x1 = (f64::from(src_w) * (1.0 - f64::from(cr))).round() as u32;
348 let y0 = (f64::from(src_h) * f64::from(ct)).round() as u32;
349 let y1 = (f64::from(src_h) * (1.0 - f64::from(cb))).round() as u32;
350 let (x, w) = align(x0.min(src_w), x1.saturating_sub(x0), src_w);
351 let (y, h) = align(y0.min(src_h), y1.saturating_sub(y0), src_h);
352 Rect { x, y, w, h }
353}
354
355/// `dst` -- a placement [`fit_rect`] already worked out -- moved by
356/// [`TransformParams::pos_x`]/`pos_y` (canvas fractions, about `dst`'s own
357/// centre) and resized by `scale` (about that same centre), clamped onto the
358/// canvas and chroma-grid aligned like every other rect here.
359///
360/// corner-cut: a placement pushed partway off the canvas is clipped at the
361/// edge (what [`compose_i420`] already does to any rect), not wrapped or
362/// reflected -- there is no picture to draw once it is entirely off, and
363/// [`compose_i420`] already refuses that case by returning without a write.
364pub fn transformed_dst_rect(dst: Rect, t: &TransformParams, canvas_w: u32, canvas_h: u32) -> Rect {
365 if dst.is_empty() || canvas_w == 0 || canvas_h == 0 {
366 return dst;
367 }
368 let scale = if t.scale.is_finite() && t.scale > 0.0 {
369 f64::from(t.scale)
370 } else {
371 1.0
372 };
373 let new_w = ((f64::from(dst.w) * scale).round() as i64).clamp(1, i64::from(canvas_w));
374 let new_h = ((f64::from(dst.h) * scale).round() as i64).clamp(1, i64::from(canvas_h));
375 let pos_x = if t.pos_x.is_finite() { f64::from(t.pos_x) } else { 0.0 };
376 let pos_y = if t.pos_y.is_finite() { f64::from(t.pos_y) } else { 0.0 };
377 let cx = i64::from(dst.x) + i64::from(dst.w) / 2 + (f64::from(canvas_w) * pos_x).round() as i64;
378 let cy = i64::from(dst.y) + i64::from(dst.h) / 2 + (f64::from(canvas_h) * pos_y).round() as i64;
379 let x = (cx - new_w / 2).clamp(0, i64::from(canvas_w)) as u32;
380 let y = (cy - new_h / 2).clamp(0, i64::from(canvas_h)) as u32;
381 let (x, w) = align(x, new_w as u32, canvas_w);
382 let (y, h) = align(y, new_h as u32, canvas_h);
383 Rect { x, y, w, h }
384}
385
386/// Nearest 90-degree step `degrees` renders at: `0` (0deg), `1` (90deg
387/// clockwise), `2` (180deg) or `3` (270deg). Continuous rotation is not
388/// rendered at all -- see the [`crate::transform`] module docs -- so this is
389/// the one lossy step between what a project *stores* and what a frame
390/// *shows*. Non-finite folds to `0`.
391pub fn nearest_90_steps(degrees: f32) -> u8 {
392 if !degrees.is_finite() {
393 return 0;
394 }
395 let norm = degrees.rem_euclid(360.0);
396 ((norm / 90.0).round() as i64).rem_euclid(4) as u8
397}
398
399/// Rotates a tightly packed I420 frame by `steps` quarter turns clockwise
400/// (`steps % 4`; see [`nearest_90_steps`]). `0` and `2` keep the frame's
401/// shape, `1` and `3` swap it -- the chroma planes rotate the same way at
402/// their own `(w+1)/2` x `(h+1)/2` size, which stays exact because it is
403/// exactly the luma size's, swapped the same way.
404pub fn rotate_i420_90s(
405 y: &[u8],
406 u: &[u8],
407 v: &[u8],
408 w: u32,
409 h: u32,
410 steps: u8,
411) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
412 let steps = steps % 4;
413 if steps == 0 || w == 0 || h == 0 {
414 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
415 }
416 let (cw, ch) = chroma_dims(w as usize, h as usize);
417 let (ry, rw, rh) = rotate_plane(y, w as usize, h as usize, steps);
418 let (ru, ..) = rotate_plane(u, cw, ch, steps);
419 let (rv, ..) = rotate_plane(v, cw, ch, steps);
420 (ry, ru, rv, rw as u32, rh as u32)
421}
422
423/// One tightly packed plane, rotated `steps` (1..=3) quarter turns clockwise.
424fn rotate_plane(src: &[u8], w: usize, h: usize, steps: u8) -> (Vec<u8>, usize, usize) {
425 match steps {
426 1 => {
427 let (nw, nh) = (h, w);
428 let mut out = vec![0u8; nw * nh];
429 for yp in 0..nh {
430 for xp in 0..nw {
431 out[yp * nw + xp] = src[(h - 1 - xp) * w + yp];
432 }
433 }
434 (out, nw, nh)
435 }
436 2 => {
437 let mut out = vec![0u8; w * h];
438 for yp in 0..h {
439 for xp in 0..w {
440 out[yp * w + xp] = src[(h - 1 - yp) * w + (w - 1 - xp)];
441 }
442 }
443 (out, w, h)
444 }
445 3 => {
446 let (nw, nh) = (h, w);
447 let mut out = vec![0u8; nw * nh];
448 for yp in 0..nh {
449 for xp in 0..nw {
450 out[yp * nw + xp] = src[xp * w + (w - 1 - yp)];
451 }
452 }
453 (out, nw, nh)
454 }
455 _ => unreachable!("steps % 4 is 1, 2 or 3 here"),
456 }
457}
458
459/// One clip's pictures placed on the project canvas: the geometry, plus the
460/// buffers it composes into so a frame costs no allocation.
461///
462/// This is the *one* definition of what a mixed-resolution timeline looks like:
463/// playback ([`crate::decode`]) and export ([`crate::export`]) both hand their
464/// decoded planes to [`place`](Composer::place), so what is watched and what is
465/// written cannot drift apart.
466///
467/// **Order against the colour grade: grade first, place second.** A grade
468/// belongs to the clip's own pixels -- it is graded at the resolution it was
469/// shot at, which is also the cheaper end of a downscale -- and, decisively, the
470/// letterbox bars are *not* the clip: a brightness grade that reached them would
471/// lift the black frame around the picture. Callers therefore grade the source
472/// planes and place the result; the bars stay exactly [`black_i420`].
473///
474/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of
475/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a
476/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at
477/// 4096x2160 (the floor), all measured. A worker holds one more than this in its
478/// hand, so a burst off a full queue is `queue_depth + 1`.
479///
480/// The floor of 2 is the bound this engine ran on everywhere before there was
481/// any decode-ahead; the ceiling keeps a small picture from queueing a second of
482/// video the consumer would have to walk through after a seek.
483pub(crate) fn queue_depth(width: u32, height: u32) -> usize {
484 const BUDGET: usize = 96 << 20;
485 let bytes = width as usize * height as usize * 4;
486 if bytes == 0 {
487 return 2;
488 }
489 (BUDGET / bytes).clamp(2, 16)
490}
491
492/// A canvas of the picture's own size is a pass-through: [`place`](Composer::place)
493/// hands the caller's own planes straight back, allocates nothing and touches no
494/// byte, which is what keeps a project at its media's resolution the byte-for-byte
495/// path it was before there was a project resolution at all.
496///
497/// [`place`]: Composer::place
498pub struct Composer {
499 width: u32,
500 height: u32,
501 policy: FitPolicy,
502 /// The `src` rect of [`fit_rect`], gathered tightly packed. Only `Fill` and
503 /// `Center` ever crop, so this stays empty for a letterboxed project.
504 crop: (Vec<u8>, Vec<u8>, Vec<u8>),
505 /// The crop resampled to the placement rect.
506 scaled: (Vec<u8>, Vec<u8>, Vec<u8>),
507 /// The canvas itself, refilled with black every frame -- a memset against a
508 /// decode, and the only way a policy change cannot leave last frame's bars
509 /// showing through.
510 canvas: (Vec<u8>, Vec<u8>, Vec<u8>),
511}
512
513impl Composer {
514 pub fn new(width: u32, height: u32, policy: FitPolicy) -> Self {
515 let empty = || (Vec::new(), Vec::new(), Vec::new());
516 Self {
517 width,
518 height,
519 policy,
520 crop: empty(),
521 scaled: empty(),
522 canvas: empty(),
523 }
524 }
525
526 /// A composer that places nothing: every picture passes through at its own
527 /// size. What the file-level decode API opens with, where there is no
528 /// project and therefore no canvas.
529 pub fn passthrough() -> Self {
530 Self::new(0, 0, FitPolicy::Fit)
531 }
532
533 /// Whether this canvas is the one that places nothing
534 /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand,
535 /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that
536 /// needs it is sizing a queue before anything has been decoded.
537 pub(crate) fn places_nothing(&self) -> bool {
538 self.width == 0 || self.height == 0
539 }
540
541 /// How many decoded pictures a worker over this canvas may keep ahead of
542 /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
543 /// than a 1080p one instead of the same number of far bigger frames.
544 ///
545 /// A **pass-through** canvas has no size of its own -- the pictures come out
546 /// at the source's -- so it cannot answer, and the caller that knows the
547 /// stream asks [`queue_depth`] with those dimensions instead. Answering 2
548 /// here would be the pre-decode-ahead bound, which is exactly the bug this
549 /// pair exists to keep out of the file-open path.
550 pub(crate) fn queue_depth(&self) -> usize {
551 queue_depth(self.width, self.height)
552 }
553
554 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
555 /// composer would hand it back untouched. What lets a caller keep a fused
556 /// fast path (the graded conversion) for the common case.
557 pub fn is_passthrough(&self, src_w: u32, src_h: u32) -> bool {
558 self.width == 0 || self.height == 0 || (src_w, src_h) == (self.width, self.height)
559 }
560
561 /// The picture as the project sees it: `(y, u, v, width, height)`, either the
562 /// caller's own planes (pass-through) or the canvas with the fitted picture
563 /// composed onto it. The dimensions come back because those two differ.
564 ///
565 /// Panics on a plane that is not exactly `src_w` x `src_h` (chroma at
566 /// `(w + 1) / 2`), as [`scale_i420`] does and for its reason.
567 pub fn place<'a>(
568 &'a mut self,
569 y: &'a [u8],
570 u: &'a [u8],
571 v: &'a [u8],
572 src_w: u32,
573 src_h: u32,
574 ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
575 if self.is_passthrough(src_w, src_h) {
576 return (y, u, v, src_w, src_h);
577 }
578 let (dst, src) = fit_rect(src_w, src_h, self.width, self.height, self.policy);
579 let (sw, sh) = (src_w as usize, src_h as usize);
580
581 // Crop first, so the scaler only ever sees a tightly packed plane. Fit
582 // and Stretch never crop, which is the whole cost of the common case.
583 let (src_y, src_u, src_v) = if (src.w, src.h) == (src_w, src_h) {
584 (y, u, v)
585 } else {
586 crop_i420(&mut self.crop, y, u, v, sw, sh, src);
587 (&self.crop.0[..], &self.crop.1[..], &self.crop.2[..])
588 };
589 // ...then resample it to the placement, unless it already is that size
590 // (`Center` never resamples, and neither does an exact-fit upscale).
591 let (cw, ch) = (src.w as usize, src.h as usize);
592 let (dw, dh) = (dst.w as usize, dst.h as usize);
593 let (pic_y, pic_u, pic_v) = if (cw, ch) == (dw, dh) {
594 (src_y, src_u, src_v)
595 } else {
596 let (ccw, cch) = chroma_dims(dw, dh);
597 let (sy, su, sv) = &mut self.scaled;
598 sy.resize(dw * dh, 0);
599 su.resize(ccw * cch, 0);
600 sv.resize(ccw * cch, 0);
601 scale_i420(src_y, src_u, src_v, cw, ch, sy, su, sv, dw, dh);
602 (&sy[..], &su[..], &sv[..])
603 };
604
605 let (w, h) = (self.width as usize, self.height as usize);
606 let (canvas_cw, canvas_ch) = chroma_dims(w, h);
607 let (ky, ku, kv) = &mut self.canvas;
608 fill(ky, w * h, BLACK_Y);
609 fill(ku, canvas_cw * canvas_ch, NEUTRAL_C);
610 fill(kv, canvas_cw * canvas_ch, NEUTRAL_C);
611 compose_i420(ky, ku, kv, w, h, pic_y, pic_u, pic_v, dst);
612 (ky, ku, kv, self.width, self.height)
613 }
614
615 /// [`place`](Self::place) with a per-clip [`TransformParams`] applied on
616 /// top of the fit policy: the source is cropped to [`crop_rect`], rotated
617 /// by [`rotate_i420_90s`] to [`nearest_90_steps`] of `t.rotate`, fit to the
618 /// canvas exactly as an untransformed picture is, and the fitted
619 /// placement is then moved/resized by [`transformed_dst_rect`].
620 /// `t.is_identity()` takes the exact [`place`](Self::place) path.
621 ///
622 /// corner-cut: unlike `place`, this always allocates its crop and rotate
623 /// buffers fresh rather than reusing `self`'s -- the grade path already
624 /// pays the same per-frame cost for a graded clip
625 /// ([`crate::decode::Render::frame`]'s `graded` copy), so a transformed
626 /// clip follows that precedent instead of adding a second steady-state
627 /// buffer budget. Upgrade path if this shows up in a measurement: give
628 /// `Composer` its own crop/rotate scratch fields, sized once like `crop`
629 /// and `scaled` already are.
630 pub fn place_transformed(
631 &mut self,
632 y: &[u8],
633 u: &[u8],
634 v: &[u8],
635 src_w: u32,
636 src_h: u32,
637 t: &TransformParams,
638 ) -> (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32) {
639 if t.is_identity() {
640 let (y, u, v, w, h) = self.place(y, u, v, src_w, src_h);
641 return (y.to_vec(), u.to_vec(), v.to_vec(), w, h);
642 }
643 // A pass-through canvas still has a picture to place a transform on;
644 // treat it as a canvas the exact size of the incoming picture, so a
645 // transformed clip at the project's own resolution still crops,
646 // rotates and moves instead of skipping straight through.
647 let (canvas_w, canvas_h) = if self.width == 0 || self.height == 0 {
648 (src_w, src_h)
649 } else {
650 (self.width, self.height)
651 };
652
653 let crop = crop_rect(src_w, src_h, t);
654 let mut buf = (Vec::new(), Vec::new(), Vec::new());
655 let (cy, cu, cv) = if (crop.w, crop.h) == (src_w, src_h) {
656 (y, u, v)
657 } else {
658 crop_i420(&mut buf, y, u, v, src_w as usize, src_h as usize, crop);
659 (&buf.0[..], &buf.1[..], &buf.2[..])
660 };
661
662 let steps = nearest_90_steps(t.rotate);
663 let (ry, ru, rv, rw, rh) = rotate_i420_90s(cy, cu, cv, crop.w, crop.h, steps);
664
665 let (dst, src) = fit_rect(rw, rh, canvas_w, canvas_h, self.policy);
666 let (rw_u, rh_u) = (rw as usize, rh as usize);
667 let (fy, fu, fv) = if (src.w, src.h) == (rw, rh) {
668 (&ry[..], &ru[..], &rv[..])
669 } else {
670 crop_i420(&mut buf, &ry, &ru, &rv, rw_u, rh_u, src);
671 (&buf.0[..], &buf.1[..], &buf.2[..])
672 };
673
674 let dst = transformed_dst_rect(dst, t, canvas_w, canvas_h);
675 let (sw, sh) = (src.w as usize, src.h as usize);
676 let (dw, dh) = (dst.w as usize, dst.h as usize);
677 let mut scaled = (Vec::new(), Vec::new(), Vec::new());
678 let (py, pu, pv) = if (sw, sh) == (dw, dh) {
679 (fy, fu, fv)
680 } else {
681 let (ccw, cch) = chroma_dims(dw, dh);
682 scaled.0.resize(dw * dh, 0);
683 scaled.1.resize(ccw * cch, 0);
684 scaled.2.resize(ccw * cch, 0);
685 scale_i420(
686 fy, fu, fv, sw, sh, &mut scaled.0, &mut scaled.1, &mut scaled.2, dw, dh,
687 );
688 (&scaled.0[..], &scaled.1[..], &scaled.2[..])
689 };
690
691 let (w, h) = (canvas_w as usize, canvas_h as usize);
692 let mut canvas = black_i420(w, h);
693 compose_i420(
694 &mut canvas.0,
695 &mut canvas.1,
696 &mut canvas.2,
697 w,
698 h,
699 py,
700 pu,
701 pv,
702 dst,
703 );
704 (canvas.0, canvas.1, canvas.2, canvas_w, canvas_h)
705 }
706}
707
708/// Per-byte lerp of two same-sized I420 frames: `out = a + (b - a) * t`, on
709/// every plane. `t` is clamped to `[0, 1]` -- a caller ramping across a
710/// cross-dissolve window hands back an in-range fraction already, this is the
711/// backstop. `a`/`b`'s planes must be the same length pairwise (Y with Y, U
712/// with U, V with V); a mismatched pair panics rather than silently
713/// truncating a picture.
714pub fn blend_i420(a: (&[u8], &[u8], &[u8]), b: (&[u8], &[u8], &[u8]), t: f32) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
715 let t = t.clamp(0.0, 1.0);
716 let plane = |a: &[u8], b: &[u8]| -> Vec<u8> {
717 assert_eq!(a.len(), b.len(), "blend_i420: mismatched plane sizes");
718 a.iter()
719 .zip(b)
720 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
721 .collect()
722 };
723 (plane(a.0, b.0), plane(a.1, b.1), plane(a.2, b.2))
724}
725
726/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
727/// across frames is refilled, not reallocated.
728fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
729 plane.clear();
730 plane.resize(len, value);
731}
732
733/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
734/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
735/// crop is exactly half of it.
736fn crop_i420(
737 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
738 y: &[u8],
739 u: &[u8],
740 v: &[u8],
741 src_w: usize,
742 src_h: usize,
743 rect: Rect,
744) {
745 let (w, h) = (rect.w as usize, rect.h as usize);
746 let (x, cy0) = (rect.x as usize, rect.y as usize);
747 let (src_cw, _) = chroma_dims(src_w, src_h);
748 let (cw, ch) = chroma_dims(w, h);
749 let (oy, ou, ov) = out;
750 oy.clear();
751 ou.clear();
752 ov.clear();
753 for row in 0..h {
754 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
755 }
756 let (cx, cy0) = (x / 2, cy0 / 2);
757 for row in 0..ch {
758 let at = (cy0 + row) * src_cw + cx;
759 ou.extend_from_slice(&u[at..][..cw]);
760 ov.extend_from_slice(&v[at..][..cw]);
761 }
762 debug_assert_eq!(oy.len(), w * h);
763 debug_assert_eq!(ou.len(), cw * ch);
764}
765
766#[cfg(test)]
767mod tests {
768 use super::*;
769
770 /// Allocates the destination planes for a size and runs a scale into them.
771 fn scaled(
772 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
773 src_w: usize,
774 src_h: usize,
775 dst_w: usize,
776 dst_h: usize,
777 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
778 let (cw, ch) = chroma_dims(dst_w, dst_h);
779 let mut dst = (
780 vec![0u8; dst_w * dst_h],
781 vec![0u8; cw * ch],
782 vec![0u8; cw * ch],
783 );
784 scale_i420(
785 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
786 );
787 dst
788 }
789
790 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
791 let (cw, ch) = chroma_dims(w, h);
792 (
793 (0..w * h).map(|i| (i % 256) as u8).collect(),
794 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
795 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
796 )
797 }
798
799 /// The pass-through invariant: a project at the media's own resolution must
800 /// hand the decoder's bytes to the encoder unchanged.
801 #[test]
802 fn identity_scale_is_byte_identical() {
803 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
804 let src = gradient(w, h);
805 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
806 }
807 }
808
809 /// Halving is the one case where bilinear is exactly a 2x2 box average:
810 /// the output centre falls on the shared corner of four input samples.
811 /// 0/254 averages to 127 with no rounding slack at all.
812 #[test]
813 fn downscale_by_two_averages_a_checkerboard() {
814 let (w, h) = (32, 24);
815 let (cw, ch) = chroma_dims(w, h);
816 let checker = |i: usize, stride: usize| {
817 if (i / stride + i % stride).is_multiple_of(2) {
818 0u8
819 } else {
820 254
821 }
822 };
823 let src = (
824 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
825 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
826 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
827 );
828 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
829 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
830 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
831 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
832 }
833
834 /// Nothing may leak in from outside a plane: a flat frame stays flat at
835 /// every edge, upscaled and downscaled, odd sizes included.
836 #[test]
837 fn flat_frame_stays_flat() {
838 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
839 for &(sw, sh) in &sizes {
840 let (cw, ch) = chroma_dims(sw, sh);
841 let src = (
842 vec![80u8; sw * sh],
843 vec![90u8; cw * ch],
844 vec![200u8; cw * ch],
845 );
846 for &(dw, dh) in &sizes {
847 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
848 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
849 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
850 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
851 }
852 }
853 }
854
855 /// Chroma alignment: an edge in the U plane must land at the *same* place
856 /// after a 2x upscale, with a symmetric two-sample blend around it and
857 /// untouched flats either side -- a half-sample bias shows up as an
858 /// asymmetric pair here, which is colour bleeding one way.
859 #[test]
860 fn chroma_edge_keeps_its_position() {
861 let (w, h) = (8, 8);
862 let (cw, ch) = chroma_dims(w, h);
863 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
864 let src = (
865 vec![80u8; w * h],
866 (0..cw * ch)
867 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
868 .collect(),
869 vec![128u8; cw * ch],
870 );
871 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
872 let (dcw, _) = chroma_dims(w * 2, h * 2);
873 assert_eq!(dcw, 8);
874 let row = &u[dcw * 3..][..dcw];
875 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
876 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
877 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
878 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
879 // most 1; anything further means the edge moved.
880 assert!(
881 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
882 "blend is off centre, i.e. chroma bled one way: {row:?}"
883 );
884 }
885
886 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
887 /// `(src, dst, policy) -> (placement, crop)`.
888 #[test]
889 fn fit_rect_table() {
890 let r = |x, y, w, h| Rect { x, y, w, h };
891 let cases = [
892 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
893 (
894 (1920, 1080),
895 (640, 480),
896 FitPolicy::Fit,
897 r(0, 60, 640, 360),
898 r(0, 0, 1920, 1080),
899 ),
900 // ...and the same pair filled: the canvas is whole, the source is
901 // cropped to 4:3 (1440 wide) about its centre.
902 (
903 (1920, 1080),
904 (640, 480),
905 FitPolicy::Fill,
906 r(0, 0, 640, 480),
907 r(240, 0, 1440, 1080),
908 ),
909 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
910 (
911 (640, 480),
912 (1920, 1080),
913 FitPolicy::Fit,
914 r(240, 0, 1440, 1080),
915 r(0, 0, 640, 480),
916 ),
917 (
918 (640, 480),
919 (1920, 1080),
920 FitPolicy::Fill,
921 r(0, 0, 1920, 1080),
922 r(0, 60, 640, 360),
923 ),
924 // Stretch ignores aspect entirely, both ways.
925 (
926 (1920, 1080),
927 (640, 480),
928 FitPolicy::Stretch,
929 r(0, 0, 640, 480),
930 r(0, 0, 1920, 1080),
931 ),
932 // 1:1 with a bigger source: cropped both ways, centred.
933 (
934 (1920, 1080),
935 (640, 480),
936 FitPolicy::Center,
937 r(0, 0, 640, 480),
938 r(640, 300, 640, 480),
939 ),
940 // 1:1 with a smaller source: padded both ways, centred.
941 (
942 (640, 480),
943 (1920, 1080),
944 FitPolicy::Center,
945 r(640, 300, 640, 480),
946 r(0, 0, 640, 480),
947 ),
948 // Odd sizes: offsets even, sizes even unless they reach the edge.
949 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
950 (
951 (7, 5),
952 (13, 9),
953 FitPolicy::Fit,
954 r(0, 0, 13, 9),
955 r(0, 0, 7, 5),
956 ),
957 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
958 // offset without putting chroma half a sample off, so the last one
959 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
960 (
961 (9, 9),
962 (13, 9),
963 FitPolicy::Center,
964 r(2, 0, 8, 9),
965 r(0, 0, 8, 9),
966 ),
967 (
968 (13, 9),
969 (9, 9),
970 FitPolicy::Center,
971 r(0, 0, 8, 9),
972 r(2, 0, 8, 9),
973 ),
974 ];
975 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
976 let got = fit_rect(sw, sh, dw, dh, policy);
977 assert_eq!(
978 got,
979 (want_dst, want_src),
980 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
981 );
982 }
983 // Degenerate input is empty, not a panic.
984 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
985 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
986 }
987
988 /// Every rect a policy hands back must sit inside its plane, start on the
989 /// chroma grid, and end on it or at the plane edge -- the invariant
990 /// `compose_i420` relies on.
991 #[test]
992 fn fit_rect_stays_on_the_chroma_grid() {
993 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
994 for policy in [
995 FitPolicy::Fit,
996 FitPolicy::Fill,
997 FitPolicy::Stretch,
998 FitPolicy::Center,
999 ] {
1000 for &sw in &sizes {
1001 for &dh in &sizes {
1002 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
1003 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
1004 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
1005 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
1006 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
1007 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
1008 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
1009 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
1010 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
1011 // A plane one sample wide or high has no chroma grid to
1012 // be on: `Center` from a 2-high source onto a 1-high
1013 // canvas is one row, and no size satisfies both edges.
1014 // Nothing real is that shape; it must merely not
1015 // escape its plane, which the two asserts above cover.
1016 if grid {
1017 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
1018 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
1019 }
1020 assert!(!rect.is_empty(), "{ctx} empty");
1021 }
1022 }
1023 }
1024 }
1025 }
1026
1027 #[test]
1028 fn compose_fills_the_rect_and_nothing_else() {
1029 let (cw2, ch2) = (640usize, 360usize);
1030 let (canvas_w, canvas_h) = (640usize, 480usize);
1031 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
1032 let (fcw, fch) = chroma_dims(cw2, ch2);
1033 let frame = (
1034 vec![200u8; cw2 * ch2],
1035 vec![70u8; fcw * fch],
1036 vec![30u8; fcw * fch],
1037 );
1038 let rect = Rect {
1039 x: 0,
1040 y: 60,
1041 w: cw2 as u32,
1042 h: ch2 as u32,
1043 };
1044 compose_i420(
1045 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
1046 );
1047
1048 for row in 0..canvas_h {
1049 let inside = (60..420).contains(&row);
1050 let want = if inside { 200 } else { BLACK_Y };
1051 assert!(
1052 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
1053 "luma row {row}"
1054 );
1055 }
1056 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
1057 for row in 0..cch {
1058 let inside = (30..210).contains(&row);
1059 let (wu, wv) = if inside {
1060 (70, 30)
1061 } else {
1062 (NEUTRAL_C, NEUTRAL_C)
1063 };
1064 assert!(
1065 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
1066 "U row {row}"
1067 );
1068 assert!(
1069 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
1070 "V row {row}"
1071 );
1072 }
1073 }
1074
1075 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
1076 /// is public and a caller may compute a rect itself.
1077 #[test]
1078 fn compose_clips_a_rect_that_runs_off_the_canvas() {
1079 let (mut y, mut u, mut v) = black_i420(16, 16);
1080 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
1081 let rect = Rect {
1082 x: 12,
1083 y: 12,
1084 w: 8,
1085 h: 8,
1086 };
1087 compose_i420(
1088 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
1089 );
1090 assert_eq!(y[15 * 16 + 15], 99);
1091 assert_eq!(y[11 * 16 + 15], BLACK_Y);
1092 // Wholly outside: no write at all.
1093 let before = y.clone();
1094 compose_i420(
1095 &mut y,
1096 &mut u,
1097 &mut v,
1098 16,
1099 16,
1100 &frame.0,
1101 &frame.1,
1102 &frame.2,
1103 Rect {
1104 x: 100,
1105 y: 0,
1106 w: 8,
1107 h: 8,
1108 },
1109 );
1110 assert_eq!(y, before);
1111 }
1112
1113 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
1114 /// project canvas, letterbox bars intact.
1115 #[test]
1116 fn fit_scale_compose_letterboxes() {
1117 let (sw, sh) = (640usize, 480usize);
1118 let (dw, dh) = (1920usize, 1080usize);
1119 let src = gradient(sw, sh);
1120 let (dst_rect, src_rect) =
1121 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
1122 assert_eq!(
1123 src_rect,
1124 Rect {
1125 x: 0,
1126 y: 0,
1127 w: 640,
1128 h: 480
1129 }
1130 );
1131 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
1132 let picture = scaled(&src, sw, sh, rw, rh);
1133 let (mut y, mut u, mut v) = black_i420(dw, dh);
1134 compose_i420(
1135 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
1136 );
1137 // Pillarbox columns stay black, the picture area does not.
1138 let mid = (dh / 2) * dw;
1139 assert!(
1140 y[mid..mid + dst_rect.x as usize]
1141 .iter()
1142 .all(|&s| s == BLACK_Y)
1143 );
1144 assert_eq!(
1145 y[mid + dst_rect.x as usize..][..rw],
1146 picture.0[(rh / 2) * rw..][..rw]
1147 );
1148 }
1149
1150 /// The wiring invariant: a project at its media's own resolution hands the
1151 /// decoder's own slices back, not a copy that happens to be equal. Asserted
1152 /// on the pointer, because "identical bytes" is cheap and "no work at all"
1153 /// is what the common case is promised.
1154 #[test]
1155 fn a_canvas_of_the_source_size_is_a_pass_through() {
1156 let (w, h) = (64usize, 48usize);
1157 let src = gradient(w, h);
1158 for mut canvas in [
1159 Composer::new(w as u32, h as u32, FitPolicy::Fit),
1160 Composer::new(w as u32, h as u32, FitPolicy::Fill),
1161 Composer::new(w as u32, h as u32, FitPolicy::Center),
1162 Composer::passthrough(),
1163 ] {
1164 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
1165 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
1166 assert_eq!(u.as_ptr(), src.1.as_ptr());
1167 assert_eq!(v.as_ptr(), src.2.as_ptr());
1168 assert_eq!((cw, ch), (w as u32, h as u32));
1169 }
1170 }
1171
1172 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
1173 /// the pillarbox columns are limited-range black, exactly -- a bar that is
1174 /// merely dark is a bar the grade reached.
1175 #[test]
1176 fn fit_pillarboxes_with_exact_black_bars() {
1177 let (sw, sh) = (640u32, 480u32);
1178 let (dw, dh) = (1920u32, 1080u32);
1179 let src = (
1180 vec![200u8; (sw * sh) as usize],
1181 vec![70u8; (sw * sh / 4) as usize],
1182 vec![30u8; (sw * sh / 4) as usize],
1183 );
1184 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
1185 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1186 assert_eq!((w, h), (dw, dh));
1187 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
1188 assert_eq!(
1189 rect,
1190 Rect {
1191 x: 240,
1192 y: 0,
1193 w: 1440,
1194 h: 1080
1195 },
1196 "geometry moved"
1197 );
1198 let (w, h) = (w as usize, h as usize);
1199 let row = &y[(h / 2) * w..][..w];
1200 let x = rect.x as usize;
1201 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
1202 assert!(
1203 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
1204 "right bar not black"
1205 );
1206 assert!(
1207 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
1208 "picture"
1209 );
1210 // ...and the bars are neutral in chroma too, or they would be a colour.
1211 let (cw, _) = chroma_dims(w, h);
1212 let crow = &u[(h / 4) * cw..][..cw];
1213 assert!(
1214 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
1215 "bar has colour"
1216 );
1217 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
1218 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
1219 }
1220
1221 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
1222 /// the canvas (no bar anywhere), `Center` pads without resampling.
1223 #[test]
1224 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
1225 let (sw, sh) = (640u32, 480u32);
1226 let (dw, dh) = (1920u32, 1080u32);
1227 let src = (
1228 vec![200u8; (sw * sh) as usize],
1229 vec![70u8; (sw * sh / 4) as usize],
1230 vec![30u8; (sw * sh / 4) as usize],
1231 );
1232 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
1233 let mut canvas = Composer::new(dw, dh, policy);
1234 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1235 assert!(
1236 y.iter().all(|&s| s == 200),
1237 "{policy:?} left a bar: the canvas is not covered"
1238 );
1239 }
1240 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1241 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1242 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1243 assert_eq!(rect.w, sw, "Center resampled the picture");
1244 let (w, h) = (w as usize, h as usize);
1245 let row = &y[(h / 2) * w..][..w];
1246 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1247 assert!(
1248 row[rect.x as usize..][..sw as usize]
1249 .iter()
1250 .all(|&s| s == 200)
1251 );
1252 }
1253
1254 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1255 /// picture, chroma with it: a marked band at a known column has to come out
1256 /// at the column the geometry puts it at.
1257 #[test]
1258 fn fill_crops_about_the_centre() {
1259 let (sw, sh) = (32usize, 8usize);
1260 let (dw, dh) = (8u32, 8u32);
1261 // Column 16 (the centre) is bright, everything else is dark.
1262 let y: Vec<u8> = (0..sw * sh)
1263 .map(|i| if i % sw == 16 { 240 } else { 40 })
1264 .collect();
1265 let (cw, ch) = chroma_dims(sw, sh);
1266 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1267 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1268 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1269 assert_eq!((w, h), (dw, dh));
1270 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1271 assert_eq!(
1272 dst,
1273 Rect {
1274 x: 0,
1275 y: 0,
1276 w: 8,
1277 h: 8
1278 },
1279 "Fill must cover"
1280 );
1281 assert_eq!(
1282 crop,
1283 Rect {
1284 x: 12,
1285 y: 0,
1286 w: 8,
1287 h: 8
1288 },
1289 "crop off centre"
1290 );
1291 // The bright column is crop-relative column 4 of 8, untouched by the
1292 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1293 let row = &y[..8];
1294 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1295 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1296 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1297 }
1298
1299 /// Not asserted: only the release number means anything. Run with
1300 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1301 #[test]
1302 fn perf_720p_to_1080p() {
1303 let src = gradient(1280, 720);
1304 let (cw, ch) = chroma_dims(1920, 1080);
1305 let mut dst = (
1306 vec![0u8; 1920 * 1080],
1307 vec![0u8; cw * ch],
1308 vec![0u8; cw * ch],
1309 );
1310 let runs = 30;
1311 let t = std::time::Instant::now();
1312 for _ in 0..runs {
1313 scale_i420(
1314 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1315 );
1316 }
1317 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1318 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1319 }
1320
1321 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1322 /// scale and blit -- which is what the playback budget has to hold. Printed,
1323 /// not asserted, like every other perf test here.
1324 #[test]
1325 fn perf_compose_720p_onto_1080p() {
1326 let src = gradient(1280, 720);
1327 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1328 let runs = 30;
1329 let t = std::time::Instant::now();
1330 for _ in 0..runs {
1331 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1332 }
1333 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1334 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1335 }
1336
1337 /// [`blend_i420`] at the midpoint of two solid-colour frames lands exactly
1338 /// on the 50/50 average, on every plane -- the synthetic stand-in for "the
1339 /// dissolve's midpoint frame looks like the average colour" the export
1340 /// path is built on.
1341 #[test]
1342 fn blend_i420_is_50_50_at_the_midpoint() {
1343 let a = (vec![0u8; 16], vec![10u8; 4], vec![20u8; 4]);
1344 let b = (vec![100u8; 16], vec![50u8; 4], vec![120u8; 4]);
1345 let (y, u, v) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.5);
1346 assert!(y.iter().all(|&p| p == 50), "Y midpoint: {y:?}");
1347 assert!(u.iter().all(|&p| p == 30), "U midpoint: {u:?}");
1348 assert!(v.iter().all(|&p| p == 70), "V midpoint: {v:?}");
1349 // The edges hand back each frame untouched.
1350 let (y0, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 0.0);
1351 assert_eq!(y0, a.0);
1352 let (y1, _, _) = blend_i420((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), 1.0);
1353 assert_eq!(y1, b.0);
1354 }
1355}