forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

remap.rs177 lines, 8.0 KiBHistoryRawDownload
1//! Rewriting samples coded against one YUV matrix as the same picture coded
2//! against another — the one colour operation an encode performs when a clip's
3//! space is not the space the file being written declares.
4
5use ec_core::color::Matrix;
6
7/// Rewrites planar 4:2:0 samples coded against `from` as the same picture coded
8/// against `to`, in place. Both spaces here are limited range with the same
9/// primaries, so this is the matrix and nothing else: no gamut mapping, no range
10/// scaling, and the 16/128/128 of black lands on itself either way — which is
11/// what makes a letterboxed bar and a gap's black frame cost nothing.
12///
13/// Derived from the two matrices, not tabulated: with R,G,B eliminated between
14/// them, luma picks up a chroma term and the two chroma planes mix only with
15/// each other — so chroma never needs the luma plane and is remapped at its own
16/// resolution, while luma reads the co-sited chroma sample. 8.8 fixed point.
17///
18/// A no-op when the two spaces are the same, so the caller may hand any pair;
19/// BT.2020 is never a target here — an HDR source goes through a tone map, not
20/// through this.
21pub fn remap(from: Matrix, to: Matrix, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize) {
22 // On normalised samples the two rows are Y' = Y - 0.1182 Cb - 0.2127 Cr,
23 // Cb' = 1.0185 Cb + 0.1146 Cr, Cr' = 0.0751 Cb + 1.0251 Cr; in *code* values
24 // the luma row's chroma terms carry a further 219/224, the ratio of the two
25 // limited-range spans, while the chroma rows' do not (both sides are
26 // chroma). That is the whole difference between these numbers and the
27 // published ones.
28 let coeffs = match (from, to) {
29 (Matrix::Bt601, Matrix::Bt709) => [-30, -53, 261, 29, 19, 262],
30 // ...and its inverse, which round-trips to within a code.
31 (Matrix::Bt709, Matrix::Bt601) => [25, 49, 253, -28, -19, 252],
32 _ => return,
33 };
34 let [yb, yr, ub, ur, vb, vr] = coeffs;
35 let cw = width.div_ceil(2);
36 for (i, y) in y.iter_mut().enumerate() {
37 let (row, col) = (i / width, i % width);
38 let ci = (row / 2) * cw + col / 2;
39 let (d, e) = (u[ci] as i32 - 128, v[ci] as i32 - 128);
40 *y = (*y as i32 + ((yb * d + yr * e + 128) >> 8)).clamp(0, 255) as u8;
41 }
42 for (u, v) in u.iter_mut().zip(v) {
43 let (d, e) = (*u as i32 - 128, *v as i32 - 128);
44 *u = (128 + ((ub * d + ur * e + 128) >> 8)).clamp(0, 255) as u8;
45 *v = (128 + ((vb * d + vr * e + 128) >> 8)).clamp(0, 255) as u8;
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 /// The published luma weights (kr, kb) of each matrix — the numbers the
54 /// fixed-point coefficients above are derived from.
55 fn weights(matrix: Matrix) -> (f64, f64) {
56 match matrix {
57 Matrix::Bt601 => (0.299, 0.114),
58 Matrix::Bt709 => (0.2126, 0.0722),
59 Matrix::Bt2020Ncl => (0.2627, 0.0593),
60 }
61 }
62
63 /// Limited-range 4:2:0 samples for one colour, in `matrix`, the float way —
64 /// what a correct encoder would have written.
65 fn encode(matrix: Matrix, rgb: [f64; 3]) -> (u8, u8, u8) {
66 let (kr, kb) = weights(matrix);
67 let [r, g, b] = rgb.map(|c| c / 255.0);
68 let luma = kr * r + (1.0 - kr - kb) * g + kb * b;
69 let round = |x: f64| x.round().clamp(0.0, 255.0) as u8;
70 (
71 round(16.0 + 219.0 * luma),
72 round(128.0 + 224.0 * 0.5 * (b - luma) / (1.0 - kb)),
73 round(128.0 + 224.0 * 0.5 * (r - luma) / (1.0 - kr)),
74 )
75 }
76
77 /// ...and back out of `matrix`, unrounded, which is what a player shows.
78 fn decode(matrix: Matrix, (y, u, v): (u8, u8, u8)) -> [f64; 3] {
79 let (kr, kb) = weights(matrix);
80 let luma = (f64::from(y) - 16.0) / 219.0;
81 let cb = (f64::from(u) - 128.0) / 224.0;
82 let cr = (f64::from(v) - 128.0) / 224.0;
83 let r = luma + 2.0 * (1.0 - kr) * cr;
84 let b = luma + 2.0 * (1.0 - kb) * cb;
85 let g = (luma - kr * r - kb * b) / (1.0 - kr - kb);
86 [r, g, b].map(|c| c * 255.0)
87 }
88
89 /// One colour as a 2x2 picture — four luma samples over one chroma pair, the
90 /// smallest thing [`remap`] indexes the way it indexes a frame.
91 fn tile((y, u, v): (u8, u8, u8)) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
92 (vec![y; 4], vec![u], vec![v])
93 }
94
95 /// The claim the whole reconcile rests on: samples coded against one matrix,
96 /// remapped, and then *decoded by the other matrix* are the colour that went
97 /// in — not a second conversion of it. Within a code or two, which is what
98 /// 8-bit 8.8 fixed point can promise.
99 #[test]
100 fn a_remap_is_the_same_colour_read_by_the_other_matrix() {
101 let colours = [
102 [255.0, 0.0, 0.0],
103 [0.0, 255.0, 0.0],
104 [0.0, 0.0, 255.0],
105 [255.0, 255.0, 0.0],
106 [18.0, 200.0, 140.0],
107 [128.0, 128.0, 128.0],
108 [235.0, 210.0, 30.0],
109 ];
110 for (from, to) in [
111 (Matrix::Bt601, Matrix::Bt709),
112 (Matrix::Bt709, Matrix::Bt601),
113 ] {
114 for rgb in colours {
115 let (mut y, mut u, mut v) = tile(encode(from, rgb));
116 remap(from, to, &mut y, &mut u, &mut v, 2);
117 let out = decode(to, (y[0], u[0], v[0]));
118 for (want, got) in rgb.iter().zip(&out) {
119 assert!(
120 (want - got).abs() <= 2.0,
121 "{from:?}->{to:?} {rgb:?} came out {out:?}"
122 );
123 }
124 }
125 }
126 }
127
128 /// Black, white and neutral grey are the same samples in both matrices, and
129 /// a remap has to leave them alone: those are the letterbox bars, the gap
130 /// frames and every grey in the picture, and a shift there is visible as a
131 /// tint on nothing at all.
132 #[test]
133 fn a_remap_leaves_the_greys_where_they_are() {
134 for (from, to) in [
135 (Matrix::Bt601, Matrix::Bt709),
136 (Matrix::Bt709, Matrix::Bt601),
137 ] {
138 for luma in [16u8, 128, 235] {
139 let (mut y, mut u, mut v) = tile((luma, 128, 128));
140 remap(from, to, &mut y, &mut u, &mut v, 2);
141 assert_eq!((y[0], u[0], v[0]), (luma, 128, 128), "{from:?}->{to:?}");
142 }
143 }
144 }
145
146 /// The zero-cost path, asserted where it is decided: a clip already in the
147 /// file's own space comes out byte for byte the samples it went in as, so an
148 /// ordinary single-space project is not touched by any of this.
149 #[test]
150 fn a_same_space_remap_touches_nothing() {
151 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
152 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
153 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
154 let (before_y, before_u, before_v) = (y.clone(), u.clone(), v.clone());
155 for matrix in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] {
156 remap(matrix, matrix, &mut y, &mut u, &mut v, 64);
157 }
158 assert_eq!((y, u, v), (before_y, before_u, before_v));
159 }
160
161 /// There and back is the picture again: the two directions are one matrix
162 /// and its inverse, not two independent approximations.
163 #[test]
164 fn a_remap_round_trips_within_a_code() {
165 let y: Vec<u8> = (0..64 * 48).map(|i| (16 + i % 220) as u8).collect();
166 let u: Vec<u8> = (0..32 * 24).map(|i| (16 + i % 225) as u8).collect();
167 let v: Vec<u8> = (0..32 * 24).map(|i| (240 - i % 225) as u8).collect();
168 let (mut ry, mut ru, mut rv) = (y.clone(), u.clone(), v.clone());
169 remap(Matrix::Bt601, Matrix::Bt709, &mut ry, &mut ru, &mut rv, 64);
170 remap(Matrix::Bt709, Matrix::Bt601, &mut ry, &mut ru, &mut rv, 64);
171 let worst =
172 |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap();
173 assert!(worst(&y, &ry) <= 2, "luma drifted by {}", worst(&y, &ry));
174 assert!(worst(&u, &ru) <= 2, "cb drifted by {}", worst(&u, &ru));
175 assert!(worst(&v, &rv) <= 2, "cr drifted by {}", worst(&v, &rv));
176 }
177}