forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

upsample.rs69 lines, 2.9 KiBHistoryRawDownload
1//! Chroma upsampling, shared by the two formats that subsample it.
2//!
3//! Both JPEG and VP8 store chroma at half resolution and both are decoded by
4//! their reference implementations with the triangle ("fancy") filter — the
5//! 9/3/3/1 weighting a separable 3:1 pass in each direction produces. Pixel
6//! replication is cheaper and visibly wrong: it puts a two-pixel staircase on
7//! every saturated colour edge, and costs about a decibel against the source.
8
9/// Triangle ("fancy") upsampling of one component to full resolution.
10///
11/// The 3:1 weighting is the same filter libjpeg uses, which is why a 4:2:0
12/// photo decoded here and by the incumbent differ by rounding rather than by a
13/// visible staircase on every colour edge.
14pub fn upsample(plane: &[u8], pw: usize, ph: usize, out_w: usize, out_h: usize) -> Vec<u8> {
15 if pw == out_w && ph == out_h {
16 return plane.to_vec();
17 }
18 // Horizontal first, then vertical; each pass either doubles with the
19 // triangle filter or falls back to nearest for uncommon ratios.
20 let mut wide = vec![0u8; out_w * ph];
21 // The source column for each output column, computed once rather than per row.
22 let columns: Vec<usize> = (0..out_w).map(|x| (x * pw / out_w).min(pw - 1)).collect();
23 for y in 0..ph {
24 let row = &plane[y * pw..y * pw + pw];
25 if out_w.div_ceil(2) == pw {
26 for x in 0..pw {
27 let left = row[x.saturating_sub(1)];
28 let right = row[(x + 1).min(pw - 1)];
29 let here = u32::from(row[x]) * 3;
30 let a = ((here + u32::from(left) + 2) >> 2) as u8;
31 let b = ((here + u32::from(right) + 1) >> 2) as u8;
32 if 2 * x < out_w {
33 wide[y * out_w + 2 * x] = a;
34 }
35 if 2 * x + 1 < out_w {
36 wide[y * out_w + 2 * x + 1] = b;
37 }
38 }
39 } else {
40 for (dst, &src) in wide[y * out_w..(y + 1) * out_w].iter_mut().zip(&columns) {
41 *dst = row[src];
42 }
43 }
44 }
45 if out_h == ph {
46 // No vertical resampling: every output row is the source row it was built from.
47 return wide;
48 }
49 let mut out = vec![0u8; out_w * out_h];
50 for y in 0..out_h {
51 if out_h.div_ceil(2) == ph {
52 let near = y / 2;
53 let far = if y % 2 == 0 {
54 near.saturating_sub(1)
55 } else {
56 (near + 1).min(ph - 1)
57 };
58 for x in 0..out_w {
59 let n = u32::from(wide[near * out_w + x]) * 3;
60 let f = u32::from(wide[far * out_w + x]);
61 out[y * out_w + x] = ((n + f + 2) >> 2) as u8;
62 }
63 } else {
64 let src = (y * ph / out_h).min(ph - 1);
65 out[y * out_w..(y + 1) * out_w].copy_from_slice(&wide[src * out_w..(src + 1) * out_w]);
66 }
67 }
68 out
69}