1use alpha2_media::{DecodedVideoFrame, PixelFormat, Plane, Rect};
4
5const SCORE_GRID: (u32, u32) = (128, 72);
6
7pub const THUMBNAIL_LUMA_RANGE: (f64, f64) = (0.08, 0.92);
10
11#[must_use]
14pub fn unpremultiplied(mut pixels: Vec<u8>) -> Vec<u8> {
15 for pixel in pixels.as_chunks_mut::<4>().0 {
16 let alpha = u16::from(pixel[3]);
17 if alpha == 0 || alpha == 255 {
18 continue;
19 }
20 for channel in &mut pixel[..3] {
21 let straight = (u16::from(*channel) * 255 + alpha / 2) / alpha;
22 *channel = u8::try_from(straight.min(255)).unwrap_or(u8::MAX);
23 }
24 }
25 pixels
26}
27
28#[derive(Copy, Clone, Debug, PartialEq)]
30pub struct FrameScore {
31 pub mean_luma: f64,
33 pub sharpness: f64,
36}
37
38#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
43pub fn score_frame(frame: &DecodedVideoFrame) -> Result<FrameScore, String> {
44 let (columns, rows) = SCORE_GRID;
45 let crop = frame.visible_rect;
46 if crop.width == 0 || crop.height == 0 {
47 return Err("frame has no visible pixels".into());
48 }
49 let mut luma = Vec::with_capacity((columns * rows) as usize);
50 for row in 0..rows {
51 for column in 0..columns {
52 let x =
53 crop.x + (u64::from(column) * u64::from(crop.width) / u64::from(columns)) as u32;
54 let y = crop.y + (u64::from(row) * u64::from(crop.height) / u64::from(rows)) as u32;
55 luma.push(luma_at(frame, x, y)?);
56 }
57 }
58 let mean = luma.iter().sum::<f64>() / luma.len() as f64;
59 let at = |column: u32, row: u32| luma[(row * columns + column) as usize];
60 let mut laplacians = Vec::with_capacity(luma.len());
61 for row in 1..rows - 1 {
62 for column in 1..columns - 1 {
63 laplacians.push(
64 4.0 * at(column, row)
65 - at(column - 1, row)
66 - at(column + 1, row)
67 - at(column, row - 1)
68 - at(column, row + 1),
69 );
70 }
71 }
72 let average = laplacians.iter().sum::<f64>() / laplacians.len() as f64;
73 let sharpness = laplacians
74 .iter()
75 .map(|value| (value - average).powi(2))
76 .sum::<f64>()
77 / laplacians.len() as f64;
78 Ok(FrameScore {
79 mean_luma: mean,
80 sharpness,
81 })
82}
83
84#[must_use]
87pub fn choose_thumbnail(scores: &[FrameScore]) -> Option<usize> {
88 let (dark, bright) = THUMBNAIL_LUMA_RANGE;
89 let sharpest = |acceptable: &dyn Fn(&FrameScore) -> bool| {
90 scores
91 .iter()
92 .enumerate()
93 .filter(|(_, score)| acceptable(score))
94 .max_by(|(_, a), (_, b)| a.sharpness.total_cmp(&b.sharpness))
95 .map(|(index, _)| index)
96 };
97 sharpest(&|score| (dark..=bright).contains(&score.mean_luma)).or_else(|| sharpest(&|_| true))
98}
99
100fn luma_at(frame: &DecodedVideoFrame, x: u32, y: u32) -> Result<f64, String> {
102 let plane = frame.planes.first().ok_or("frame has no planes")?;
103 match frame.pixel_format {
104 PixelFormat::Yuv(format) => {
105 let wide = format.bit_depth > 8;
106 let value = f64::from(sample(plane, x, y, if wide { 2 } else { 1 }, 1, 0)?);
107 let full_scale = if format.msb_aligned {
109 65_535.0
110 } else {
111 f64::from((1_u32 << format.bit_depth) - 1)
112 };
113 Ok(value / full_scale)
114 }
115 PixelFormat::Rgba8 => {
116 let channel = |index| sample(plane, x, y, 1, 4, index).map(f64::from);
117 Ok((0.2126 * channel(0)? + 0.7152 * channel(1)? + 0.0722 * channel(2)?) / 255.0)
118 }
119 other => Err(format!("cannot read luma from {other:?}")),
120 }
121}
122
123fn sample(
125 plane: &Plane,
126 x: u32,
127 y: u32,
128 bytes: usize,
129 components: usize,
130 component: usize,
131) -> Result<u16, String> {
132 let offset = y as usize * plane.stride as usize + (x as usize * components + component) * bytes;
133 let slice = plane
134 .bytes
135 .get(offset..offset + bytes)
136 .ok_or("plane is shorter than its layout")?;
137 Ok(if bytes == 2 {
138 u16::from_le_bytes([slice[0], slice[1]])
139 } else {
140 u16::from(slice[0])
141 })
142}
143
144pub fn downscale_frame(
150 frame: &DecodedVideoFrame,
151 factor: u32,
152) -> Result<DecodedVideoFrame, String> {
153 if factor < 2 {
154 return Err("a proxy factor is 2 or more".into());
155 }
156 let crop = frame.visible_rect;
157 let (width, height) = ((crop.width / factor) & !1, (crop.height / factor) & !1);
158 if width == 0 || height == 0 {
159 return Err(format!(
160 "a {}x{} frame is too small to shrink by {factor}",
161 crop.width, crop.height
162 ));
163 }
164 let planes = match frame.pixel_format {
165 PixelFormat::Rgba8 => vec![shrink_plane(
166 plane(frame, 0)?,
167 (crop.x, crop.y),
168 (width, height),
169 factor,
170 1,
171 4,
172 )?],
173 PixelFormat::Yuv(format) => {
174 let bytes = if format.bit_depth > 8 { 2 } else { 1 };
175 let (shift_x, shift_y) = (
176 u32::from(format.chroma_shift_x),
177 u32::from(format.chroma_shift_y),
178 );
179 let chroma_size = (width.div_ceil(1 << shift_x), height.div_ceil(1 << shift_y));
180 let chroma_origin = (crop.x >> shift_x, crop.y >> shift_y);
181 let mut planes = vec![shrink_plane(
182 plane(frame, 0)?,
183 (crop.x, crop.y),
184 (width, height),
185 factor,
186 bytes,
187 1,
188 )?];
189 if format.interleaved_chroma {
190 planes.push(shrink_plane(
191 plane(frame, 1)?,
192 chroma_origin,
193 chroma_size,
194 factor,
195 bytes,
196 2,
197 )?);
198 } else {
199 for index in 1..frame.planes.len() {
200 planes.push(shrink_plane(
201 plane(frame, index)?,
202 chroma_origin,
203 chroma_size,
204 factor,
205 bytes,
206 1,
207 )?);
208 }
209 }
210 planes
211 }
212 other => return Err(format!("cannot shrink {other:?} frames")),
213 };
214 Ok(DecodedVideoFrame {
215 visible_rect: Rect {
216 x: 0,
217 y: 0,
218 width,
219 height,
220 },
221 planes,
222 ..frame.clone()
223 })
224}
225
226pub fn resize_rgba(
235 pixels: &[u8],
236 (width, height): (u32, u32),
237 (new_width, new_height): (u32, u32),
238) -> Result<Vec<u8>, String> {
239 let (columns, rows) = (width as usize, height as usize);
240 if width == 0 || height == 0 || new_width == 0 || new_height == 0 {
241 return Err("cannot resize an empty picture".to_owned());
242 }
243 if columns
244 .checked_mul(rows)
245 .and_then(|count| count.checked_mul(4))
246 != Some(pixels.len())
247 {
248 return Err("RGBA buffer does not match its size".to_owned());
249 }
250 let mut picture = pixels
252 .as_chunks::<4>()
253 .0
254 .iter()
255 .flat_map(|&[r, g, b, a]| {
256 let alpha = f32::from(a) / 255.0;
257 [
258 f32::from(r) / 255.0 * alpha,
259 f32::from(g) / 255.0 * alpha,
260 f32::from(b) / 255.0 * alpha,
261 alpha,
262 ]
263 })
264 .collect::<Vec<_>>();
265 let (mut current_columns, mut current_rows) = (columns, rows);
266 if new_width != width {
267 let taps = tent_taps(columns, new_width as usize);
268 let mut resized = vec![0.0_f32; new_width as usize * rows * 4];
269 for y in 0..rows {
270 for (x, row_taps) in taps.iter().enumerate() {
271 let out = &mut resized[(y * new_width as usize + x) * 4..][..4];
272 for &(source, weight) in row_taps {
273 for (channel, value) in out.iter_mut().enumerate() {
274 *value += weight * picture[(y * columns + source) * 4 + channel];
275 }
276 }
277 }
278 }
279 picture = resized;
280 current_columns = new_width as usize;
281 }
282 if new_height != height {
283 let taps = tent_taps(rows, new_height as usize);
284 let mut resized = vec![0.0_f32; current_columns * new_height as usize * 4];
285 for (y, column_taps) in taps.iter().enumerate() {
286 for x in 0..current_columns {
287 let out = &mut resized[(y * current_columns + x) * 4..][..4];
288 for &(source, weight) in column_taps {
289 for (channel, value) in out.iter_mut().enumerate() {
290 *value += weight * picture[(source * current_columns + x) * 4 + channel];
291 }
292 }
293 }
294 }
295 picture = resized;
296 current_rows = new_height as usize;
297 }
298 debug_assert_eq!(picture.len(), current_columns * current_rows * 4);
299 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
300 let code = |value: f32| (value.clamp(0.0, 1.0) * 255.0).round() as u8;
301 Ok(picture
302 .as_chunks::<4>()
303 .0
304 .iter()
305 .flat_map(|&[r, g, b, a]| {
306 let colour = |value: f32| if a > 0.0 { code(value / a) } else { 0 };
307 [colour(r), colour(g), colour(b), code(a)]
308 })
309 .collect())
310}
311
312#[allow(
315 clippy::cast_precision_loss,
316 clippy::cast_possible_truncation,
317 clippy::cast_possible_wrap,
318 clippy::cast_sign_loss
319)]
320fn tent_taps(inputs: usize, outputs: usize) -> Vec<Vec<(usize, f32)>> {
321 let scale = inputs as f64 / outputs as f64;
322 let radius = scale.max(1.0);
323 (0..outputs)
324 .map(|output| {
325 let centre = (output as f64 + 0.5) * scale - 0.5;
326 let first = (centre - radius).floor() as i64;
327 let last = (centre + radius).ceil() as i64;
328 let mut taps = Vec::new();
329 for input in first..=last {
330 let weight = 1.0 - (input as f64 - centre).abs() / radius;
331 if weight <= 0.0 {
332 continue;
333 }
334 let clamped = input.clamp(0, inputs as i64 - 1) as usize;
335 match taps.iter_mut().find(|(index, _)| *index == clamped) {
336 Some((_, total)) => *total += weight,
337 None => taps.push((clamped, weight)),
338 }
339 }
340 let sum: f64 = taps.iter().map(|(_, weight)| weight).sum();
341 taps.into_iter()
342 .map(|(index, weight)| (index, (weight / sum) as f32))
343 .collect()
344 })
345 .collect()
346}
347
348fn plane(frame: &DecodedVideoFrame, index: usize) -> Result<&Plane, String> {
349 frame
350 .planes
351 .get(index)
352 .ok_or_else(|| format!("frame has no plane {index}"))
353}
354
355fn shrink_plane(
357 source: &Plane,
358 origin: (u32, u32),
359 size: (u32, u32),
360 factor: u32,
361 bytes: usize,
362 components: usize,
363) -> Result<Plane, String> {
364 let (width, height) = size;
365 let stride = width as usize * components * bytes;
366 let (source_width, source_height) = (source.width as usize, source.height as usize);
367 let source_stride = source.stride as usize;
368 let row_bytes = source_width * components * bytes;
369 if source_width == 0
370 || source_height == 0
371 || source_stride < row_bytes
372 || source.bytes.len() < (source_height - 1) * source_stride + row_bytes
373 {
374 return Err("plane is shorter than its layout".to_owned());
375 }
376 let columns = (0..width as usize)
378 .flat_map(|x| {
379 (0..factor as usize)
380 .map(move |dx| (origin.0 as usize + x * factor as usize + dx).min(source_width - 1))
381 })
382 .collect::<Vec<_>>();
383 let count = u64::from(factor * factor);
384 let mut sums = vec![0_u64; width as usize * components];
385 let mut output = Vec::with_capacity(stride * height as usize);
386 for y in 0..height as usize {
387 sums.fill(0);
388 for dy in 0..factor as usize {
389 let sy = (origin.1 as usize + y * factor as usize + dy).min(source_height - 1);
390 let row = &source.bytes[sy * source_stride..sy * source_stride + row_bytes];
391 if bytes == 2 {
392 accumulate(&mut sums, &columns, factor as usize, components, |at| {
393 u64::from(u16::from_le_bytes([row[2 * at], row[2 * at + 1]]))
394 });
395 } else {
396 accumulate(&mut sums, &columns, factor as usize, components, |at| {
397 u64::from(row[at])
398 });
399 }
400 }
401 for sum in &sums {
402 let mean = (sum + count / 2) / count;
403 if bytes == 2 {
404 output.extend_from_slice(&u16::try_from(mean).unwrap_or(u16::MAX).to_le_bytes());
405 } else {
406 output.push(u8::try_from(mean).unwrap_or(u8::MAX));
407 }
408 }
409 }
410 Ok(Plane {
411 bytes: output.into(),
412 stride: u32::try_from(stride).map_err(|_| "plane is too wide")?,
413 width,
414 height,
415 })
416}
417
418fn accumulate(
420 sums: &mut [u64],
421 columns: &[usize],
422 factor: usize,
423 components: usize,
424 read: impl Fn(usize) -> u64,
425) {
426 for (x, sources) in columns.chunks_exact(factor).enumerate() {
427 for component in 0..components {
428 sums[x * components + component] += sources
429 .iter()
430 .map(|column| read(column * components + component))
431 .sum::<u64>();
432 }
433 }
434}
435
436#[cfg(test)]
437mod tests {
438
439 #[test]
440 fn premultiplied_pixels_are_divided_by_their_alpha() {
441 assert_eq!(
442 super::unpremultiplied(vec![
443 10, 20, 30, 255, 0, 0, 0, 0, 64, 32, 0, 128, 200, 0, 0, 100
444 ]),
445 vec![10, 20, 30, 255, 0, 0, 0, 0, 128, 64, 0, 128, 255, 0, 0, 100]
446 );
447 }
448
449 use super::*;
450 use alpha2_media::{ChromaLocation, Orientation, SampleAspectRatio, YuvFormat};
451 use alpha2_time::MediaTime;
452
453 fn frame(width: u32, height: u32, luma: impl Fn(u32, u32) -> u8) -> DecodedVideoFrame {
454 let y_plane = Plane {
455 bytes: (0..height)
456 .flat_map(|y| (0..width).map(move |x| (x, y)))
457 .map(|(x, y)| luma(x, y))
458 .collect::<Vec<_>>()
459 .into(),
460 stride: width,
461 width,
462 height,
463 };
464 let chroma = |value| Plane {
465 bytes: vec![value; (width.div_ceil(2) * height.div_ceil(2)) as usize].into(),
466 stride: width.div_ceil(2),
467 width: width.div_ceil(2),
468 height: height.div_ceil(2),
469 };
470 DecodedVideoFrame {
471 pts: MediaTime::ZERO,
472 dts: None,
473 duration: None,
474 visible_rect: Rect {
475 x: 0,
476 y: 0,
477 width,
478 height,
479 },
480 sample_aspect_ratio: SampleAspectRatio::default(),
481 orientation: Orientation::UPRIGHT,
482 pixel_format: PixelFormat::Yuv(YuvFormat::I420),
483 chroma_location: ChromaLocation::default(),
484 color: None,
485 planes: vec![y_plane, chroma(128), chroma(128)],
486 }
487 }
488
489 #[test]
490 fn the_thumbnail_is_the_sharpest_frame_neither_black_nor_white() {
491 let black = frame(128, 72, |_, _| 5);
492 let white = frame(
494 128,
495 72,
496 |x, y| {
497 if x % 4 == 0 && y % 4 == 0 { 0 } else { 255 }
498 },
499 );
500 let soft = frame(128, 72, |x, _| {
501 u8::try_from(40 + x * 150 / 128).expect("small")
502 });
503 let detailed = frame(
504 128,
505 72,
506 |x, y| {
507 if (x / 4 + y / 4) % 2 == 0 { 40 } else { 200 }
508 },
509 );
510 let scores =
511 [&black, &white, &soft, &detailed].map(|frame| score_frame(frame).expect("score"));
512 assert!(scores[0].mean_luma < THUMBNAIL_LUMA_RANGE.0);
513 assert!(scores[1].mean_luma > THUMBNAIL_LUMA_RANGE.1);
514 assert!(scores[3].sharpness > scores[2].sharpness);
515 assert!(scores[1].sharpness > scores[3].sharpness);
516 assert_eq!(choose_thumbnail(&scores), Some(3));
517 assert_eq!(choose_thumbnail(&scores[..2]), Some(1));
519 assert_eq!(choose_thumbnail(&[]), None);
520 }
521
522 #[test]
523 fn a_proxy_averages_blocks_and_keeps_an_even_size() {
524 let source = frame(10, 6, |x, _| u8::try_from(x * 20).expect("small"));
526 let half = downscale_frame(&source, 2).expect("proxy");
527 assert_eq!((half.visible_rect.width, half.visible_rect.height), (4, 2));
528 assert_eq!(&half.planes[0].bytes[..4], &[10, 50, 90, 130]);
529 assert_eq!((half.planes[1].width, half.planes[1].height), (2, 1));
530 assert!(half.planes[1].bytes.iter().all(|value| *value == 128));
531 assert!(downscale_frame(&source, 1).is_err());
532 assert!(downscale_frame(&frame(3, 3, |_, _| 0), 4).is_err());
533 }
534
535 #[test]
536 fn a_resize_keeps_flat_colour_weighs_alpha_and_leaves_a_kept_axis_alone() {
537 let rgba = |pixels: &[[u8; 4]]| pixels.iter().flatten().copied().collect::<Vec<_>>();
538 let flat = rgba(&[[200, 100, 50, 255]; 60 * 4]);
539 for size in [(64, 4), (32, 4), (60, 7), (17, 3)] {
540 let resized = resize_rgba(&flat, (60, 4), size).expect("resize");
541 assert!(
542 resized.chunks(4).all(|pixel| pixel == [200, 100, 50, 255]),
543 "{size:?}"
544 );
545 }
546 let half = resize_rgba(&rgba(&[[255, 0, 0, 255], [0, 0, 255, 0]]), (2, 1), (1, 1))
548 .expect("resize");
549 assert_eq!(half, [255, 0, 0, 128]);
550 let ramp = rgba(&[[0, 0, 0, 255], [200, 200, 200, 255]]);
551 let stretched = resize_rgba(&ramp, (2, 1), (4, 1)).expect("resize");
552 assert_eq!(
553 stretched
554 .chunks(4)
555 .map(|pixel| pixel[0])
556 .collect::<Vec<_>>(),
557 [0, 50, 150, 200]
558 );
559 assert!(resize_rgba(&ramp, (2, 1), (0, 1)).is_err());
560 assert!(resize_rgba(&ramp, (3, 1), (4, 1)).is_err());
561 }
562
563 fn reference_shrink_plane(
565 source: &Plane,
566 origin: (u32, u32),
567 size: (u32, u32),
568 factor: u32,
569 bytes: usize,
570 components: usize,
571 ) -> Result<Plane, String> {
572 let (width, height) = size;
573 let stride = width as usize * components * bytes;
574 let mut output = Vec::with_capacity(stride * height as usize);
575 for y in 0..height {
576 for x in 0..width {
577 for component in 0..components {
578 let mut sum = 0_u64;
579 let mut count = 0_u64;
580 for dy in 0..factor {
581 for dx in 0..factor {
582 let sx =
583 (origin.0 + x * factor + dx).min(source.width.saturating_sub(1));
584 let sy =
585 (origin.1 + y * factor + dy).min(source.height.saturating_sub(1));
586 sum += u64::from(sample(source, sx, sy, bytes, components, component)?);
587 count += 1;
588 }
589 }
590 let mean = (sum + count / 2) / count;
591 if bytes == 2 {
592 output.extend_from_slice(
593 &u16::try_from(mean).unwrap_or(u16::MAX).to_le_bytes(),
594 );
595 } else {
596 output.push(u8::try_from(mean).unwrap_or(u8::MAX));
597 }
598 }
599 }
600 }
601 Ok(Plane {
602 bytes: output.into(),
603 stride: u32::try_from(stride).map_err(|_| "plane is too wide")?,
604 width,
605 height,
606 })
607 }
608
609 #[test]
610 fn shrinking_by_rows_gives_the_samples_sample_by_sample_did() {
611 let plane = |width: u32, height: u32, bytes: usize, components: usize| {
612 let stride = width as usize * components * bytes + 3;
613 Plane {
614 bytes: (0..stride * height as usize)
615 .map(|index| u8::try_from((index * 7919 + index / 13) % 251).expect("byte"))
616 .collect::<Vec<_>>()
617 .into(),
618 stride: u32::try_from(stride).expect("stride"),
619 width,
620 height,
621 }
622 };
623 for (width, height) in [(17, 9), (64, 48), (1, 1)] {
624 for (bytes, components) in [(1, 1), (2, 1), (1, 2), (2, 2)] {
625 let source = plane(width, height, bytes, components);
626 for factor in [2, 4] {
627 for origin in [(0, 0), (3, 1)] {
628 let size = ((width / factor).max(1), (height / factor).max(1));
629 let expected = reference_shrink_plane(
630 &source, origin, size, factor, bytes, components,
631 )
632 .expect("reference");
633 let found = shrink_plane(&source, origin, size, factor, bytes, components)
634 .expect("rows");
635 assert_eq!(
636 found.bytes, expected.bytes,
637 "{width}x{height} {bytes}B x{components} /{factor} at {origin:?}"
638 );
639 }
640 }
641 }
642 }
643 }
644}