forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB68ca7c5Tahinli3 months ago1682 commits

upsample.rs63 lines, 2.5 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 for y in 0..ph {
22 let row = &plane[y * pw..y * pw + pw];
23 if out_w.div_ceil(2) == pw {
24 for x in 0..pw {
25 let left = row[x.saturating_sub(1)];
26 let right = row[(x + 1).min(pw - 1)];
27 let here = u32::from(row[x]) * 3;
28 let a = ((here + u32::from(left) + 2) >> 2) as u8;
29 let b = ((here + u32::from(right) + 1) >> 2) as u8;
30 if 2 * x < out_w {
31 wide[y * out_w + 2 * x] = a;
32 }
33 if 2 * x + 1 < out_w {
34 wide[y * out_w + 2 * x + 1] = b;
35 }
36 }
37 } else {
38 for x in 0..out_w {
39 wide[y * out_w + x] = row[(x * pw / out_w).min(pw - 1)];
40 }
41 }
42 }
43 let mut out = vec![0u8; out_w * out_h];
44 for y in 0..out_h {
45 if out_h.div_ceil(2) == ph {
46 let near = y / 2;
47 let far = if y % 2 == 0 {
48 near.saturating_sub(1)
49 } else {
50 (near + 1).min(ph - 1)
51 };
52 for x in 0..out_w {
53 let n = u32::from(wide[near * out_w + x]) * 3;
54 let f = u32::from(wide[far * out_w + x]);
55 out[y * out_w + x] = ((n + f + 2) >> 2) as u8;
56 }
57 } else {
58 let src = (y * ph / out_h).min(ph - 1);
59 out[y * out_w..(y + 1) * out_w].copy_from_slice(&wide[src * out_w..(src + 1) * out_w]);
60 }
61 }
62 out
63}