forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB3050ac9Tahinli3 months ago553 commits

scale.rs1318 lines, 51.1 KiBHistoryRawDownload
1//! I420 rescale and frame placement: the primitive a project resolution needs.
2//!
3//! A timeline has one resolution; the media on it does not. Everything a
4//! mixed-resolution timeline asks for is these three pieces:
5//!
6//! * [`scale_i420`] resamples a planar frame to another size,
7//! * [`fit_rect`] is the pure geometry -- where the scaled picture lands on the
8//! project canvas, and which part of the source it comes from, under one of
9//! four [`FitPolicy`] rules,
10//! * [`compose_i420`] blits the scaled picture onto a canvas, so the pixels a
11//! letterbox leaves over stay whatever the canvas was filled with
12//! ([`black_i420`] is that fill).
13//!
14//! The filter is bilinear in 16.16 fixed point: two taps per axis, column
15//! weights precomputed once per plane, no float and no division in the pixel
16//! loop. That is the honest quality level for v1 -- a downscale by more than 2x
17//! aliases, because two taps cannot carry a wider kernel. The upgrade path is a
18//! separable Lanczos-3 (or a box prefilter before the bilinear pass) behind the
19//! same signature: nothing here exposes the tap count. 1280x720 -> 1920x1080
20//! measures 3.82 ms/frame in release (`perf_720p_to_1080p` below), against the
21//! 4.7 ms the BGRA conversion next door already costs per frame.
22//!
23//! Sample siting: each plane is resampled as its own image with centre-aligned
24//! mapping, `src = (dst + 0.5) * src_len / dst_len - 0.5`. For chroma that
25//! treats I420 as centre-sited where MPEG-2 calls it left-sited, a quarter-
26//! chroma-sample bias that no eye finds and that a siting-aware kernel would fix
27//! in the same place the Lanczos upgrade goes.
28
29use crate::transform::TransformParams;
30
31/// Limited-range black: what an untouched canvas pixel is.
32pub const BLACK_Y: u8 = 16;
33/// Neutral chroma: 128 in both planes.
34pub const NEUTRAL_C: u8 = 128;
35
36/// A 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/// Resizes `plane` to `len` and sets every byte to `value` -- a canvas reused
709/// across frames is refilled, not reallocated.
710fn fill(plane: &mut Vec<u8>, len: usize, value: u8) {
711 plane.clear();
712 plane.resize(len, value);
713}
714
715/// Gathers `rect` out of a tightly packed I420 frame into another tightly packed
716/// one. `rect` comes from [`fit_rect`], so its offsets are even and the chroma
717/// crop is exactly half of it.
718fn crop_i420(
719 out: &mut (Vec<u8>, Vec<u8>, Vec<u8>),
720 y: &[u8],
721 u: &[u8],
722 v: &[u8],
723 src_w: usize,
724 src_h: usize,
725 rect: Rect,
726) {
727 let (w, h) = (rect.w as usize, rect.h as usize);
728 let (x, cy0) = (rect.x as usize, rect.y as usize);
729 let (src_cw, _) = chroma_dims(src_w, src_h);
730 let (cw, ch) = chroma_dims(w, h);
731 let (oy, ou, ov) = out;
732 oy.clear();
733 ou.clear();
734 ov.clear();
735 for row in 0..h {
736 oy.extend_from_slice(&y[(cy0 + row) * src_w + x..][..w]);
737 }
738 let (cx, cy0) = (x / 2, cy0 / 2);
739 for row in 0..ch {
740 let at = (cy0 + row) * src_cw + cx;
741 ou.extend_from_slice(&u[at..][..cw]);
742 ov.extend_from_slice(&v[at..][..cw]);
743 }
744 debug_assert_eq!(oy.len(), w * h);
745 debug_assert_eq!(ou.len(), cw * ch);
746}
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751
752 /// Allocates the destination planes for a size and runs a scale into them.
753 fn scaled(
754 src: &(Vec<u8>, Vec<u8>, Vec<u8>),
755 src_w: usize,
756 src_h: usize,
757 dst_w: usize,
758 dst_h: usize,
759 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
760 let (cw, ch) = chroma_dims(dst_w, dst_h);
761 let mut dst = (
762 vec![0u8; dst_w * dst_h],
763 vec![0u8; cw * ch],
764 vec![0u8; cw * ch],
765 );
766 scale_i420(
767 &src.0, &src.1, &src.2, src_w, src_h, &mut dst.0, &mut dst.1, &mut dst.2, dst_w, dst_h,
768 );
769 dst
770 }
771
772 fn gradient(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
773 let (cw, ch) = chroma_dims(w, h);
774 (
775 (0..w * h).map(|i| (i % 256) as u8).collect(),
776 (0..cw * ch).map(|i| (i % 251) as u8).collect(),
777 (0..cw * ch).map(|i| (255 - i % 256) as u8).collect(),
778 )
779 }
780
781 /// The pass-through invariant: a project at the media's own resolution must
782 /// hand the decoder's bytes to the encoder unchanged.
783 #[test]
784 fn identity_scale_is_byte_identical() {
785 for (w, h) in [(64, 48), (7, 5), (1, 1)] {
786 let src = gradient(w, h);
787 assert_eq!(scaled(&src, w, h, w, h), src, "{w}x{h}");
788 }
789 }
790
791 /// Halving is the one case where bilinear is exactly a 2x2 box average:
792 /// the output centre falls on the shared corner of four input samples.
793 /// 0/254 averages to 127 with no rounding slack at all.
794 #[test]
795 fn downscale_by_two_averages_a_checkerboard() {
796 let (w, h) = (32, 24);
797 let (cw, ch) = chroma_dims(w, h);
798 let checker = |i: usize, stride: usize| {
799 if (i / stride + i % stride).is_multiple_of(2) {
800 0u8
801 } else {
802 254
803 }
804 };
805 let src = (
806 (0..w * h).map(|i| checker(i, w)).collect::<Vec<_>>(),
807 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
808 (0..cw * ch).map(|i| checker(i, cw)).collect::<Vec<_>>(),
809 );
810 let (y, u, v) = scaled(&src, w, h, w / 2, h / 2);
811 assert!(y.iter().all(|&s| s == 127), "luma: {:?}", &y[..8]);
812 assert!(u.iter().all(|&s| s == 127), "U: {:?}", &u[..4]);
813 assert!(v.iter().all(|&s| s == 127), "V: {:?}", &v[..4]);
814 }
815
816 /// Nothing may leak in from outside a plane: a flat frame stays flat at
817 /// every edge, upscaled and downscaled, odd sizes included.
818 #[test]
819 fn flat_frame_stays_flat() {
820 let sizes = [(7, 5), (16, 16), (13, 9), (1, 4)];
821 for &(sw, sh) in &sizes {
822 let (cw, ch) = chroma_dims(sw, sh);
823 let src = (
824 vec![80u8; sw * sh],
825 vec![90u8; cw * ch],
826 vec![200u8; cw * ch],
827 );
828 for &(dw, dh) in &sizes {
829 let (y, u, v) = scaled(&src, sw, sh, dw, dh);
830 assert!(y.iter().all(|&s| s == 80), "Y {sw}x{sh}->{dw}x{dh}");
831 assert!(u.iter().all(|&s| s == 90), "U {sw}x{sh}->{dw}x{dh}");
832 assert!(v.iter().all(|&s| s == 200), "V {sw}x{sh}->{dw}x{dh}");
833 }
834 }
835 }
836
837 /// Chroma alignment: an edge in the U plane must land at the *same* place
838 /// after a 2x upscale, with a symmetric two-sample blend around it and
839 /// untouched flats either side -- a half-sample bias shows up as an
840 /// asymmetric pair here, which is colour bleeding one way.
841 #[test]
842 fn chroma_edge_keeps_its_position() {
843 let (w, h) = (8, 8);
844 let (cw, ch) = chroma_dims(w, h);
845 // Chroma columns 0,1 = 90 and 2,3 = 200: the edge sits at the middle.
846 let src = (
847 vec![80u8; w * h],
848 (0..cw * ch)
849 .map(|i| if i % cw < cw / 2 { 90 } else { 200 })
850 .collect(),
851 vec![128u8; cw * ch],
852 );
853 let (_, u, _) = scaled(&src, w, h, w * 2, h * 2);
854 let (dcw, _) = chroma_dims(w * 2, h * 2);
855 assert_eq!(dcw, 8);
856 let row = &u[dcw * 3..][..dcw];
857 assert_eq!(&row[..3], &[90, 90, 90], "flat side moved: {row:?}");
858 assert_eq!(&row[5..], &[200, 200, 200], "flat side moved: {row:?}");
859 // The two blend samples are 117.5 and 172.5 before rounding: symmetric
860 // about the 145 midpoint, so they sum to 290. Round-half-up costs at
861 // most 1; anything further means the edge moved.
862 assert!(
863 (i32::from(row[3]) + i32::from(row[4]) - 290).abs() <= 1,
864 "blend is off centre, i.e. chroma bled one way: {row:?}"
865 );
866 }
867
868 /// Geometry, table-driven: 16:9 into 4:3 and back, plus odd sizes.
869 /// `(src, dst, policy) -> (placement, crop)`.
870 #[test]
871 fn fit_rect_table() {
872 let r = |x, y, w, h| Rect { x, y, w, h };
873 let cases = [
874 // 16:9 source on a 4:3 canvas: 640x360 letterboxed inside 640x480.
875 (
876 (1920, 1080),
877 (640, 480),
878 FitPolicy::Fit,
879 r(0, 60, 640, 360),
880 r(0, 0, 1920, 1080),
881 ),
882 // ...and the same pair filled: the canvas is whole, the source is
883 // cropped to 4:3 (1440 wide) about its centre.
884 (
885 (1920, 1080),
886 (640, 480),
887 FitPolicy::Fill,
888 r(0, 0, 640, 480),
889 r(240, 0, 1440, 1080),
890 ),
891 // 4:3 source on a 16:9 canvas: pillarboxed 1440 wide.
892 (
893 (640, 480),
894 (1920, 1080),
895 FitPolicy::Fit,
896 r(240, 0, 1440, 1080),
897 r(0, 0, 640, 480),
898 ),
899 (
900 (640, 480),
901 (1920, 1080),
902 FitPolicy::Fill,
903 r(0, 0, 1920, 1080),
904 r(0, 60, 640, 360),
905 ),
906 // Stretch ignores aspect entirely, both ways.
907 (
908 (1920, 1080),
909 (640, 480),
910 FitPolicy::Stretch,
911 r(0, 0, 640, 480),
912 r(0, 0, 1920, 1080),
913 ),
914 // 1:1 with a bigger source: cropped both ways, centred.
915 (
916 (1920, 1080),
917 (640, 480),
918 FitPolicy::Center,
919 r(0, 0, 640, 480),
920 r(640, 300, 640, 480),
921 ),
922 // 1:1 with a smaller source: padded both ways, centred.
923 (
924 (640, 480),
925 (1920, 1080),
926 FitPolicy::Center,
927 r(640, 300, 640, 480),
928 r(0, 0, 640, 480),
929 ),
930 // Odd sizes: offsets even, sizes even unless they reach the edge.
931 ((7, 5), (7, 5), FitPolicy::Fit, r(0, 0, 7, 5), r(0, 0, 7, 5)),
932 (
933 (7, 5),
934 (13, 9),
935 FitPolicy::Fit,
936 r(0, 0, 13, 9),
937 r(0, 0, 7, 5),
938 ),
939 // 1:1 into a wider canvas: the 9 odd columns cannot survive an even
940 // offset without putting chroma half a sample off, so the last one
941 // is dropped -- 8 wide at x=2. Height reaches the edge, so 9 stays.
942 (
943 (9, 9),
944 (13, 9),
945 FitPolicy::Center,
946 r(2, 0, 8, 9),
947 r(0, 0, 8, 9),
948 ),
949 (
950 (13, 9),
951 (9, 9),
952 FitPolicy::Center,
953 r(0, 0, 8, 9),
954 r(2, 0, 8, 9),
955 ),
956 ];
957 for ((sw, sh), (dw, dh), policy, want_dst, want_src) in cases {
958 let got = fit_rect(sw, sh, dw, dh, policy);
959 assert_eq!(
960 got,
961 (want_dst, want_src),
962 "{sw}x{sh} -> {dw}x{dh} {policy:?}"
963 );
964 }
965 // Degenerate input is empty, not a panic.
966 assert!(fit_rect(0, 10, 10, 10, FitPolicy::Fit).0.is_empty());
967 assert!(fit_rect(10, 10, 10, 0, FitPolicy::Fill).1.is_empty());
968 }
969
970 /// Every rect a policy hands back must sit inside its plane, start on the
971 /// chroma grid, and end on it or at the plane edge -- the invariant
972 /// `compose_i420` relies on.
973 #[test]
974 fn fit_rect_stays_on_the_chroma_grid() {
975 let sizes = [1u32, 2, 3, 7, 16, 33, 640, 1080, 1920];
976 for policy in [
977 FitPolicy::Fit,
978 FitPolicy::Fill,
979 FitPolicy::Stretch,
980 FitPolicy::Center,
981 ] {
982 for &sw in &sizes {
983 for &dh in &sizes {
984 let (sh, dw) = (sizes[0] + sw / 2 + 1, dh * 2 - 1);
985 let (dst, src) = fit_rect(sw, sh, dw, dh, policy);
986 let grid = [sw, sh, dw, dh].iter().all(|&e| e >= 2);
987 for (rect, (ew, eh), what) in [(dst, (dw, dh), "dst"), (src, (sw, sh), "src")] {
988 let ctx = format!("{policy:?} {sw}x{sh}->{dw}x{dh} {what} {rect:?}");
989 assert!(rect.x + rect.w <= ew, "{ctx} overflows width");
990 assert!(rect.y + rect.h <= eh, "{ctx} overflows height");
991 assert_eq!(rect.x % 2, 0, "{ctx} odd x");
992 assert_eq!(rect.y % 2, 0, "{ctx} odd y");
993 // A plane one sample wide or high has no chroma grid to
994 // be on: `Center` from a 2-high source onto a 1-high
995 // canvas is one row, and no size satisfies both edges.
996 // Nothing real is that shape; it must merely not
997 // escape its plane, which the two asserts above cover.
998 if grid {
999 assert!(rect.w % 2 == 0 || rect.x + rect.w == ew, "{ctx} odd w");
1000 assert!(rect.h % 2 == 0 || rect.y + rect.h == eh, "{ctx} odd h");
1001 }
1002 assert!(!rect.is_empty(), "{ctx} empty");
1003 }
1004 }
1005 }
1006 }
1007 }
1008
1009 #[test]
1010 fn compose_fills_the_rect_and_nothing_else() {
1011 let (cw2, ch2) = (640usize, 360usize);
1012 let (canvas_w, canvas_h) = (640usize, 480usize);
1013 let (mut y, mut u, mut v) = black_i420(canvas_w, canvas_h);
1014 let (fcw, fch) = chroma_dims(cw2, ch2);
1015 let frame = (
1016 vec![200u8; cw2 * ch2],
1017 vec![70u8; fcw * fch],
1018 vec![30u8; fcw * fch],
1019 );
1020 let rect = Rect {
1021 x: 0,
1022 y: 60,
1023 w: cw2 as u32,
1024 h: ch2 as u32,
1025 };
1026 compose_i420(
1027 &mut y, &mut u, &mut v, canvas_w, canvas_h, &frame.0, &frame.1, &frame.2, rect,
1028 );
1029
1030 for row in 0..canvas_h {
1031 let inside = (60..420).contains(&row);
1032 let want = if inside { 200 } else { BLACK_Y };
1033 assert!(
1034 y[row * canvas_w..][..canvas_w].iter().all(|&s| s == want),
1035 "luma row {row}"
1036 );
1037 }
1038 let (ccw, cch) = chroma_dims(canvas_w, canvas_h);
1039 for row in 0..cch {
1040 let inside = (30..210).contains(&row);
1041 let (wu, wv) = if inside {
1042 (70, 30)
1043 } else {
1044 (NEUTRAL_C, NEUTRAL_C)
1045 };
1046 assert!(
1047 u[row * ccw..][..ccw].iter().all(|&s| s == wu),
1048 "U row {row}"
1049 );
1050 assert!(
1051 v[row * ccw..][..ccw].iter().all(|&s| s == wv),
1052 "V row {row}"
1053 );
1054 }
1055 }
1056
1057 /// An out-of-bounds rect clips instead of panicking or wrapping -- compose
1058 /// is public and a caller may compute a rect itself.
1059 #[test]
1060 fn compose_clips_a_rect_that_runs_off_the_canvas() {
1061 let (mut y, mut u, mut v) = black_i420(16, 16);
1062 let frame = (vec![99u8; 8 * 8], vec![99u8; 4 * 4], vec![99u8; 4 * 4]);
1063 let rect = Rect {
1064 x: 12,
1065 y: 12,
1066 w: 8,
1067 h: 8,
1068 };
1069 compose_i420(
1070 &mut y, &mut u, &mut v, 16, 16, &frame.0, &frame.1, &frame.2, rect,
1071 );
1072 assert_eq!(y[15 * 16 + 15], 99);
1073 assert_eq!(y[11 * 16 + 15], BLACK_Y);
1074 // Wholly outside: no write at all.
1075 let before = y.clone();
1076 compose_i420(
1077 &mut y,
1078 &mut u,
1079 &mut v,
1080 16,
1081 16,
1082 &frame.0,
1083 &frame.1,
1084 &frame.2,
1085 Rect {
1086 x: 100,
1087 y: 0,
1088 w: 8,
1089 h: 8,
1090 },
1091 );
1092 assert_eq!(y, before);
1093 }
1094
1095 /// The whole pipeline the wiring slice will call: 4:3 media onto a 16:9
1096 /// project canvas, letterbox bars intact.
1097 #[test]
1098 fn fit_scale_compose_letterboxes() {
1099 let (sw, sh) = (640usize, 480usize);
1100 let (dw, dh) = (1920usize, 1080usize);
1101 let src = gradient(sw, sh);
1102 let (dst_rect, src_rect) =
1103 fit_rect(sw as u32, sh as u32, dw as u32, dh as u32, FitPolicy::Fit);
1104 assert_eq!(
1105 src_rect,
1106 Rect {
1107 x: 0,
1108 y: 0,
1109 w: 640,
1110 h: 480
1111 }
1112 );
1113 let (rw, rh) = (dst_rect.w as usize, dst_rect.h as usize);
1114 let picture = scaled(&src, sw, sh, rw, rh);
1115 let (mut y, mut u, mut v) = black_i420(dw, dh);
1116 compose_i420(
1117 &mut y, &mut u, &mut v, dw, dh, &picture.0, &picture.1, &picture.2, dst_rect,
1118 );
1119 // Pillarbox columns stay black, the picture area does not.
1120 let mid = (dh / 2) * dw;
1121 assert!(
1122 y[mid..mid + dst_rect.x as usize]
1123 .iter()
1124 .all(|&s| s == BLACK_Y)
1125 );
1126 assert_eq!(
1127 y[mid + dst_rect.x as usize..][..rw],
1128 picture.0[(rh / 2) * rw..][..rw]
1129 );
1130 }
1131
1132 /// The wiring invariant: a project at its media's own resolution hands the
1133 /// decoder's own slices back, not a copy that happens to be equal. Asserted
1134 /// on the pointer, because "identical bytes" is cheap and "no work at all"
1135 /// is what the common case is promised.
1136 #[test]
1137 fn a_canvas_of_the_source_size_is_a_pass_through() {
1138 let (w, h) = (64usize, 48usize);
1139 let src = gradient(w, h);
1140 for mut canvas in [
1141 Composer::new(w as u32, h as u32, FitPolicy::Fit),
1142 Composer::new(w as u32, h as u32, FitPolicy::Fill),
1143 Composer::new(w as u32, h as u32, FitPolicy::Center),
1144 Composer::passthrough(),
1145 ] {
1146 let (y, u, v, cw, ch) = canvas.place(&src.0, &src.1, &src.2, w as u32, h as u32);
1147 assert_eq!(y.as_ptr(), src.0.as_ptr(), "luma was copied");
1148 assert_eq!(u.as_ptr(), src.1.as_ptr());
1149 assert_eq!(v.as_ptr(), src.2.as_ptr());
1150 assert_eq!((cw, ch), (w as u32, h as u32));
1151 }
1152 }
1153
1154 /// 4:3 media on a 16:9 project: the picture lands where `fit_rect` says and
1155 /// the pillarbox columns are limited-range black, exactly -- a bar that is
1156 /// merely dark is a bar the grade reached.
1157 #[test]
1158 fn fit_pillarboxes_with_exact_black_bars() {
1159 let (sw, sh) = (640u32, 480u32);
1160 let (dw, dh) = (1920u32, 1080u32);
1161 let src = (
1162 vec![200u8; (sw * sh) as usize],
1163 vec![70u8; (sw * sh / 4) as usize],
1164 vec![30u8; (sw * sh / 4) as usize],
1165 );
1166 let mut canvas = Composer::new(dw, dh, FitPolicy::Fit);
1167 let (y, u, v, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1168 assert_eq!((w, h), (dw, dh));
1169 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Fit);
1170 assert_eq!(
1171 rect,
1172 Rect {
1173 x: 240,
1174 y: 0,
1175 w: 1440,
1176 h: 1080
1177 },
1178 "geometry moved"
1179 );
1180 let (w, h) = (w as usize, h as usize);
1181 let row = &y[(h / 2) * w..][..w];
1182 let x = rect.x as usize;
1183 assert!(row[..x].iter().all(|&s| s == BLACK_Y), "left bar not black");
1184 assert!(
1185 row[x + rect.w as usize..].iter().all(|&s| s == BLACK_Y),
1186 "right bar not black"
1187 );
1188 assert!(
1189 row[x..x + rect.w as usize].iter().all(|&s| s == 200),
1190 "picture"
1191 );
1192 // ...and the bars are neutral in chroma too, or they would be a colour.
1193 let (cw, _) = chroma_dims(w, h);
1194 let crow = &u[(h / 4) * cw..][..cw];
1195 assert!(
1196 crow[..x / 2].iter().all(|&s| s == NEUTRAL_C),
1197 "bar has colour"
1198 );
1199 assert!(crow[x / 2 + 8].abs_diff(70) <= 1, "picture chroma");
1200 assert_eq!(v[(h / 4) * cw], NEUTRAL_C);
1201 }
1202
1203 /// The other three policies, on the same pair: `Fill` and `Stretch` cover
1204 /// the canvas (no bar anywhere), `Center` pads without resampling.
1205 #[test]
1206 fn fill_and_stretch_leave_no_bars_and_center_pads_1_to_1() {
1207 let (sw, sh) = (640u32, 480u32);
1208 let (dw, dh) = (1920u32, 1080u32);
1209 let src = (
1210 vec![200u8; (sw * sh) as usize],
1211 vec![70u8; (sw * sh / 4) as usize],
1212 vec![30u8; (sw * sh / 4) as usize],
1213 );
1214 for policy in [FitPolicy::Fill, FitPolicy::Stretch] {
1215 let mut canvas = Composer::new(dw, dh, policy);
1216 let (y, ..) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1217 assert!(
1218 y.iter().all(|&s| s == 200),
1219 "{policy:?} left a bar: the canvas is not covered"
1220 );
1221 }
1222 let mut canvas = Composer::new(dw, dh, FitPolicy::Center);
1223 let (y, _, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw, sh);
1224 let (rect, _) = fit_rect(sw, sh, dw, dh, FitPolicy::Center);
1225 assert_eq!(rect.w, sw, "Center resampled the picture");
1226 let (w, h) = (w as usize, h as usize);
1227 let row = &y[(h / 2) * w..][..w];
1228 assert!(row[..rect.x as usize].iter().all(|&s| s == BLACK_Y));
1229 assert!(
1230 row[rect.x as usize..][..sw as usize]
1231 .iter()
1232 .all(|&s| s == 200)
1233 );
1234 }
1235
1236 /// A crop (`Fill` on a wider source) must gather the *middle* of the
1237 /// picture, chroma with it: a marked band at a known column has to come out
1238 /// at the column the geometry puts it at.
1239 #[test]
1240 fn fill_crops_about_the_centre() {
1241 let (sw, sh) = (32usize, 8usize);
1242 let (dw, dh) = (8u32, 8u32);
1243 // Column 16 (the centre) is bright, everything else is dark.
1244 let y: Vec<u8> = (0..sw * sh)
1245 .map(|i| if i % sw == 16 { 240 } else { 40 })
1246 .collect();
1247 let (cw, ch) = chroma_dims(sw, sh);
1248 let src = (y, vec![100u8; cw * ch], vec![150u8; cw * ch]);
1249 let mut canvas = Composer::new(dw, dh, FitPolicy::Fill);
1250 let (y, u, _, w, h) = canvas.place(&src.0, &src.1, &src.2, sw as u32, sh as u32);
1251 assert_eq!((w, h), (dw, dh));
1252 let (dst, crop) = fit_rect(sw as u32, sh as u32, dw, dh, FitPolicy::Fill);
1253 assert_eq!(
1254 dst,
1255 Rect {
1256 x: 0,
1257 y: 0,
1258 w: 8,
1259 h: 8
1260 },
1261 "Fill must cover"
1262 );
1263 assert_eq!(
1264 crop,
1265 Rect {
1266 x: 12,
1267 y: 0,
1268 w: 8,
1269 h: 8
1270 },
1271 "crop off centre"
1272 );
1273 // The bright column is crop-relative column 4 of 8, untouched by the
1274 // 1:1 scale, and no sample of the canvas is black: nothing is a bar.
1275 let row = &y[..8];
1276 assert_eq!(row[4], 240, "the marked column moved: {row:?}");
1277 assert!(y.iter().all(|&s| s != BLACK_Y), "Fill left a bar");
1278 assert!(u.iter().all(|&s| s == 100), "chroma crop lost its plane");
1279 }
1280
1281 /// Not asserted: only the release number means anything. Run with
1282 /// `cargo test -p engine --release scale::tests::perf -- --nocapture`.
1283 #[test]
1284 fn perf_720p_to_1080p() {
1285 let src = gradient(1280, 720);
1286 let (cw, ch) = chroma_dims(1920, 1080);
1287 let mut dst = (
1288 vec![0u8; 1920 * 1080],
1289 vec![0u8; cw * ch],
1290 vec![0u8; cw * ch],
1291 );
1292 let runs = 30;
1293 let t = std::time::Instant::now();
1294 for _ in 0..runs {
1295 scale_i420(
1296 &src.0, &src.1, &src.2, 1280, 720, &mut dst.0, &mut dst.1, &mut dst.2, 1920, 1080,
1297 );
1298 }
1299 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1300 println!("scale::scale_i420 1280x720 -> 1920x1080: {ms:.3} ms/frame");
1301 }
1302
1303 /// The whole per-frame cost of a mixed-resolution timeline -- black fill,
1304 /// scale and blit -- which is what the playback budget has to hold. Printed,
1305 /// not asserted, like every other perf test here.
1306 #[test]
1307 fn perf_compose_720p_onto_1080p() {
1308 let src = gradient(1280, 720);
1309 let mut canvas = Composer::new(1920, 1080, FitPolicy::Fit);
1310 let runs = 30;
1311 let t = std::time::Instant::now();
1312 for _ in 0..runs {
1313 std::hint::black_box(canvas.place(&src.0, &src.1, &src.2, 1280, 720));
1314 }
1315 let ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs);
1316 println!("scale::Composer::place 1280x720 onto 1920x1080 Fit: {ms:.3} ms/frame");
1317 }
1318}