forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

rgb.rs385 lines, 11.9 KiBHistoryRawDownload
1//! RGB to YUV conversion.
2
3/// Packed sRGB RGBA8 to planar BT.709 limited-range I420 with MPEG-2 left chroma siting. Alpha is ignored; `width` and `height` must be even.
4pub fn rgba_to_i420_709(
5 rgba: &[u8],
6 width: usize,
7 height: usize,
8 y: &mut [u8],
9 u: &mut [u8],
10 v: &mut [u8],
11) {
12 i420_709(rgba, width, height, [0, 1, 2], y, u, v);
13}
14
15/// Packed sRGB BGRA8 to planar BT.709 limited-range I420 with MPEG-2 left chroma siting. Alpha is ignored; `width` and `height` must be even.
16pub fn bgra_to_i420_709(
17 bgra: &[u8],
18 width: usize,
19 height: usize,
20 y: &mut [u8],
21 u: &mut [u8],
22 v: &mut [u8],
23) {
24 i420_709(bgra, width, height, [2, 1, 0], y, u, v);
25}
26
27/// Box-filter downscale of packed 4-byte pixels (`src` rows `stride` bytes apart, `sw` x `sh` source) to `dw` x `dh` packed rows; each channel is the rounded mean of its source footprint.
28pub fn rgb_box_downscale(
29 src: &[u8],
30 sw: usize,
31 sh: usize,
32 stride: usize,
33 dst: &mut [u8],
34 dw: usize,
35 dh: usize,
36) {
37 assert!(
38 sw >= dw && sh >= dh && dw > 0 && dh > 0,
39 "source smaller than output"
40 );
41 assert!(stride >= sw * 4 && src.len() >= stride * sh);
42 assert_eq!(dst.len(), dw * dh * 4);
43 for oy in 0..dh {
44 let (y0, y1) = footprint(oy, sh, dh);
45 for ox in 0..dw {
46 let (x0, x1) = footprint(ox, sw, dw);
47 let mut sum = [0u32; 4];
48 for row in src[y0 * stride..y1 * stride].chunks_exact(stride) {
49 for px in row[x0 * 4..x1 * 4].chunks_exact(4) {
50 for (s, &c) in sum.iter_mut().zip(px) {
51 *s += u32::from(c);
52 }
53 }
54 }
55 let n = ((x1 - x0) * (y1 - y0)) as u32;
56 for (d, s) in dst[(oy * dw + ox) * 4..][..4].iter_mut().zip(sum) {
57 *d = ((s + n / 2) / n) as u8;
58 }
59 }
60 }
61}
62
63/// Integer 8-bit limited-range YUV to RGB: `R = (ky*(Y-16) + rv*(V-128) + 128) >> 8`, and `G` and `B` alike. The one source of these numbers: the Vulkan shader takes them as push constants.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct YuvToRgb {
66 /// Luma scale.
67 pub ky: i32,
68 /// Red from Cr.
69 pub rv: i32,
70 /// Green from Cb.
71 pub gu: i32,
72 /// Green from Cr.
73 pub gv: i32,
74 /// Blue from Cb.
75 pub bu: i32,
76}
77
78impl YuvToRgb {
79 /// The five coefficients in shader push-constant order.
80 pub fn words(self) -> [i32; 5] {
81 [self.ky, self.rv, self.gu, self.gv, self.bu]
82 }
83}
84
85/// BT.601, limited range.
86pub const BT601_LIMITED: YuvToRgb = YuvToRgb {
87 ky: 298,
88 rv: 409,
89 gu: -100,
90 gv: -208,
91 bu: 516,
92};
93
94/// BT.709, limited range.
95pub const BT709_LIMITED: YuvToRgb = YuvToRgb {
96 ky: 298,
97 rv: 459,
98 gu: -55,
99 gv: -136,
100 bu: 541,
101};
102
103/// Planar 8-bit I420 (`u` and `v` at half size, bilinear chroma) to packed 4-byte pixels at `dw` x `dh`, downscaled by a separable Catmull-Rom kernel widened by the scale ratio ([`taps`]); out == in is the plain conversion. Alpha is 255. `bgra` picks the byte order.
104pub fn i420_to_packed(
105 y: &[u8],
106 u: &[u8],
107 v: &[u8],
108 (w, h): (usize, usize),
109 (dw, dh): (usize, usize),
110 bgra: bool,
111 k: &YuvToRgb,
112) -> Vec<u8> {
113 assert!(w % 2 == 0 && h % 2 == 0, "width and height must be even");
114 assert!(
115 w >= dw && h >= dh && dw > 0 && dh > 0,
116 "source smaller than output"
117 );
118 assert!(y.len() == w * h && u.len() == w * h / 4 && v.len() == w * h / 4);
119 let cw = w / 2;
120 let mut rgb = vec![[0i32; 3]; w * h];
121 for sy in 0..h {
122 for sx in 0..w {
123 let yy = i32::from(y[sy * w + sx]) - 16;
124 let uu = chroma_at(u, (cw, h / 2), sx, sy) - 128;
125 let vv = chroma_at(v, (cw, h / 2), sx, sy) - 128;
126 let r = ((k.ky * yy + k.rv * vv + 128) >> 8).clamp(0, 255);
127 let g = ((k.ky * yy + k.gu * uu + k.gv * vv + 128) >> 8).clamp(0, 255);
128 let b = ((k.ky * yy + k.bu * uu + 128) >> 8).clamp(0, 255);
129 rgb[sy * w + sx] = [r, g, b];
130 }
131 }
132 let xt: Vec<(i32, Vec<i32>)> = (0..dw).map(|o| taps(o, w, dw)).collect();
133 let yt: Vec<(i32, Vec<i32>)> = (0..dh).map(|o| taps(o, h, dh)).collect();
134 let mut rows = vec![[0i32; 3]; h * dw];
135 for sy in 0..h {
136 for (ox, (lo, wx)) in xt.iter().enumerate() {
137 let mut s = [0i32; 3];
138 for (i, &c) in wx.iter().enumerate() {
139 let px = rgb[sy * w + edge(lo + i as i32, w)];
140 for (s, p) in s.iter_mut().zip(px) {
141 *s += c * p;
142 }
143 }
144 rows[sy * dw + ox] = s;
145 }
146 }
147 let mut out = vec![255u8; dw * dh * 4];
148 for (oy, (lo, wy)) in yt.iter().enumerate() {
149 for ox in 0..dw {
150 let mut s = [0i32; 3];
151 for (j, &c) in wy.iter().enumerate() {
152 let row = rows[edge(lo + j as i32, h) * dw + ox];
153 for (s, p) in s.iter_mut().zip(row) {
154 *s += c * p;
155 }
156 }
157 let [r, g, b] =
158 s.map(|s| ((s + (1 << (2 * TAP_BITS - 1))) >> (2 * TAP_BITS)).clamp(0, 255) as u8);
159 let o = (oy * dw + ox) * 4;
160 let px = if bgra { [b, g, r] } else { [r, g, b] };
161 out[o..o + 3].copy_from_slice(&px);
162 }
163 }
164 out
165}
166
167const TAP_BITS: i32 = 10;
168
169/// Catmull-Rom (a = -0.5) taps of output sample `o` scaling `n_in` to `n_out <= n_in` samples: support 2 * n_in / n_out source samples each side of the output centre, weights in Q12 normalised to sum to 1 << TAP_BITS (the rounding residue goes to the tap nearest the centre). Returns the first tap's index (may lie outside the picture: [`edge`] clamps) and the weights. The Vulkan shader nv12_to_rgb.comp computes the same integers.
170fn taps(o: usize, n_in: usize, n_out: usize) -> (i32, Vec<i32>) {
171 let (o, n, m) = (o as i32, n_in as i32, n_out as i32);
172 let c2 = (2 * o + 1) * n - m;
173 let centre = (c2 + m) / (2 * m);
174 let reach = 2 * n / m + 2;
175 let (lo, hi) = (centre - reach, centre + reach);
176 let kernel = |i: i32| {
177 let t = ((2 * m * i - c2).abs() * 4096 / (2 * n)).min(8192);
178 let t2 = (t * t) >> 12;
179 let t3 = (t2 * t) >> 12;
180 if t < 4096 {
181 (3 * t3 - 5 * t2 + 8192) >> 1
182 } else {
183 (-t3 + 5 * t2 - 8 * t + 16384) >> 1
184 }
185 };
186 let k: Vec<i32> = (lo..=hi).map(kernel).collect();
187 let sum: i32 = k.iter().sum();
188 let mut wts: Vec<i32> = k
189 .iter()
190 .map(|&k| k.signum() * ((k.abs() * (1 << TAP_BITS) + (sum >> 1)) / sum))
191 .collect();
192 wts[(centre - lo) as usize] += (1 << TAP_BITS) - wts.iter().sum::<i32>();
193 (lo, wts)
194}
195
196fn edge(i: i32, n: usize) -> usize {
197 i.clamp(0, n as i32 - 1) as usize
198}
199
200/// Bilinear 4:2:0 chroma at luma `(x, y)`: samples left-sited on even columns and centred between row pairs, as the RGB to I420 conversions write them.
201fn chroma_at(plane: &[u8], (cw, ch): (usize, usize), x: usize, y: usize) -> i32 {
202 let j = x / 2;
203 let row = |r: usize| {
204 let a = i32::from(plane[r * cw + j]);
205 if x % 2 == 0 {
206 2 * a
207 } else {
208 a + i32::from(plane[r * cw + (j + 1).min(cw - 1)])
209 }
210 };
211 let k = y / 2;
212 let s = if y % 2 == 0 {
213 row(k.saturating_sub(1)) + 3 * row(k)
214 } else {
215 3 * row(k) + row((k + 1).min(ch - 1))
216 };
217 (s + 4) >> 3
218}
219
220fn footprint(o: usize, n_in: usize, n_out: usize) -> (usize, usize) {
221 (o * n_in / n_out, ((o + 1) * n_in).div_ceil(n_out))
222}
223
224fn i420_709(
225 rgba: &[u8],
226 width: usize,
227 height: usize,
228 order: [usize; 3],
229 y: &mut [u8],
230 u: &mut [u8],
231 v: &mut [u8],
232) {
233 assert!(
234 width.is_multiple_of(2) && height.is_multiple_of(2),
235 "width and height must be even"
236 );
237 assert_eq!(rgba.len(), width * height * 4);
238 assert_eq!(y.len(), width * height);
239 let (cw, ch) = (width / 2, height / 2);
240 assert_eq!(u.len(), cw * ch);
241 assert_eq!(v.len(), cw * ch);
242 if ch == 0 {
243 return;
244 }
245
246 let k = Coeffs::bt709();
247 let threads = std::thread::available_parallelism()
248 .map_or(1, |n| n.get())
249 .min(8)
250 .min(ch);
251 let rows = ch.div_ceil(threads);
252 let band = rows * 2 * width;
253
254 std::thread::scope(|s| {
255 let bands = rgba
256 .chunks(band * 4)
257 .zip(y.chunks_mut(band))
258 .zip(u.chunks_mut(rows * cw))
259 .zip(v.chunks_mut(rows * cw));
260 for (((src, y), u), v) in bands {
261 let k = &k;
262 s.spawn(move || convert_band(src, width, order, k, y, u, v));
263 }
264 });
265}
266
267struct Coeffs {
268 y: [i32; 3],
269 cb: [i32; 3],
270 cr: [i32; 3],
271}
272
273impl Coeffs {
274 fn bt709() -> Self {
275 let kr = 0.2126;
276 let kb = 0.0722;
277 let kg = 1.0 - kr - kb;
278 let ky = 219.0 / 255.0;
279 let kc = 224.0 / 255.0;
280 let q = |c: f64| (c * 65536.0).round() as i32;
281 Self {
282 y: [q(ky * kr), q(ky * kg), q(ky * kb)],
283 cb: [
284 q(-kc * kr / (2.0 * (1.0 - kb))),
285 q(-kc * kg / (2.0 * (1.0 - kb))),
286 q(kc / 2.0),
287 ],
288 cr: [
289 q(kc / 2.0),
290 q(-kc * kg / (2.0 * (1.0 - kr))),
291 q(-kc * kb / (2.0 * (1.0 - kr))),
292 ],
293 }
294 }
295}
296
297fn convert_band(
298 rgba: &[u8],
299 width: usize,
300 order: [usize; 3],
301 k: &Coeffs,
302 y: &mut [u8],
303 u: &mut [u8],
304 v: &mut [u8],
305) {
306 let cw = width / 2;
307 let mut cb = vec![0i32; width];
308 let mut cr = vec![0i32; width];
309 let pairs = rgba
310 .chunks_exact(2 * width * 4)
311 .zip(y.chunks_exact_mut(2 * width))
312 .zip(u.chunks_exact_mut(cw))
313 .zip(v.chunks_exact_mut(cw));
314 for (((pair, luma), u), v) in pairs {
315 let (top, bottom) = pair.split_at(width * 4);
316 let (y0, y1) = luma.split_at_mut(width);
317 cb.fill(0);
318 cr.fill(0);
319 pixel_row(top, order, y0, &mut cb, &mut cr, k);
320 pixel_row(bottom, order, y1, &mut cb, &mut cr, k);
321 subsample(&cb, u);
322 subsample(&cr, v);
323 }
324}
325
326fn pixel_row(
327 rgba: &[u8],
328 order: [usize; 3],
329 y: &mut [u8],
330 cb: &mut [i32],
331 cr: &mut [i32],
332 k: &Coeffs,
333) {
334 let px = rgba.as_chunks::<4>().0;
335 for (((px, y), cb), cr) in px
336 .iter()
337 .zip(y.iter_mut())
338 .zip(cb.iter_mut())
339 .zip(cr.iter_mut())
340 {
341 let (r, g, b) = (
342 i32::from(px[order[0]]),
343 i32::from(px[order[1]]),
344 i32::from(px[order[2]]),
345 );
346 let luma = k.y[0] * r + k.y[1] * g + k.y[2] * b;
347 *y = (((luma + 0x8000) >> 16) + 16).clamp(0, 255) as u8;
348 *cb += k.cb[0] * r + k.cb[1] * g + k.cb[2] * b;
349 *cr += k.cr[0] * r + k.cr[1] * g + k.cr[2] * b;
350 }
351}
352
353fn subsample(sums: &[i32], out: &mut [u8]) {
354 const HALF: i32 = 1 << 18;
355 let fin = |acc: i32| (((acc + HALF) >> 19) + 128).clamp(0, 255) as u8;
356 out[0] = fin(3 * sums[0] + sums[1]);
357 for (o, w) in out[1..].iter_mut().zip(sums[1..].windows(3).step_by(2)) {
358 *o = fin(w[0] + 2 * w[1] + w[2]);
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn four_by_two_matches_hand_values() {
368 let white = [255, 255, 255, 255];
369 let red = [255, 0, 0, 255];
370 let black = [0, 0, 0, 255];
371 let rgba: Vec<u8> = [white, white, red, red, black, black, black, black]
372 .into_iter()
373 .flatten()
374 .collect();
375 let (mut y, mut u, mut v) = (vec![0u8; 8], vec![0u8; 2], vec![0u8; 2]);
376 rgba_to_i420_709(&rgba, 4, 2, &mut y, &mut u, &mut v);
377 let close = |got: u8, want: i32| (i32::from(got) - want).abs() <= 1;
378 for (got, want) in y.iter().zip([235, 235, 63, 63, 16, 16, 16, 16]) {
379 assert!(close(*got, want), "y {got} vs {want}");
380 }
381 assert!(close(u[0], 128) && close(v[0], 128));
382 assert!(close(u[1], 118), "u {}", u[1]);
383 assert!(close(v[1], 170), "v {}", v[1]);
384 }
385}