core/scale: add conversion into paletted format
[nihav.git] / nihav-core / src / scale / colorcvt.rs
1 use super::*;
2 use super::kernel::Kernel;
3
4 const YUV_PARAMS: &[[f32; 2]] = &[
5 [ 0.333, 0.333 ], // RGB
6 [ 0.2126, 0.0722 ], // ITU-R BT709
7 [ 0.333, 0.333 ], // unspecified
8 [ 0.333, 0.333 ], // reserved
9 [ 0.299, 0.114 ], // ITU-R BT601
10 [ 0.299, 0.114 ], // ITU-R BT470
11 [ 0.299, 0.114 ], // SMPTE 170M
12 [ 0.212, 0.087 ], // SMPTE 240M
13 [ 0.333, 0.333 ], // YCoCg
14 [ 0.2627, 0.0593 ], // ITU-R BT2020
15 [ 0.2627, 0.0593 ], // ITU-R BT2020
16 ];
17
18 const BT_PAL_COEFFS: [f32; 2] = [ 0.493, 0.877 ];
19
20 const SMPTE_NTSC_COEFFS: &[f32; 4] = &[ -0.268, 0.7358, 0.4127, 0.4778 ];
21
22 /*const RGB2YCOCG: [[f32; 3]; 3] = [
23 [ 0.25, 0.5, 0.25 ],
24 [ -0.25, 0.5, -0.25 ],
25 [ 0.5, 0.0, -0.5 ]
26 ];
27 const YCOCG2RGB: [[f32; 3]; 3] = [
28 [ 1.0, -1.0, 1.0 ],
29 [ 1.0, 1.0, 0.0 ],
30 [ 1.0, -1.0, -1.0 ]
31 ];
32
33 const XYZ2RGB: [[f32; 3]; 3] = [
34 [ 0.49, 0.31, 0.2 ],
35 [ 0.17697, 0.8124, 0.01063 ],
36 [ 0.0, 0.01, 0.99 ]
37 ];
38 const RGB2XYZ: [[f32; 3]; 3] = [
39 [ 2.364613, -0.89654, -0.46807 ],
40 [ -0.515167, 1.42641, 0.08876 ],
41 [ 0.0052, -0.01441, 1.00920 ]
42 ];*/
43
44 fn make_rgb2yuv(kr: f32, kb: f32, mat: &mut [[f32; 3]; 3]) {
45 // Y
46 mat[0][0] = kr;
47 mat[0][1] = 1.0 - kr - kb;
48 mat[0][2] = kb;
49 // Cb
50 mat[1][0] = -mat[0][0] * 0.5 / (1.0 - kb);
51 mat[1][1] = -mat[0][1] * 0.5 / (1.0 - kb);
52 mat[1][2] = 0.5;
53 // Cr
54 mat[2][0] = 0.5;
55 mat[2][1] = -mat[0][1] * 0.5 / (1.0 - kr);
56 mat[2][2] = -mat[0][2] * 0.5 / (1.0 - kr);
57 }
58
59 fn make_yuv2rgb(kr: f32, kb: f32, mat: &mut [[f32; 3]; 3]) {
60 let kg = 1.0 - kr - kb;
61
62 // R
63 mat[0][0] = 1.0;
64 mat[0][1] = 0.0;
65 mat[0][2] = 2.0 * (1.0 - kr);
66 // G
67 mat[1][0] = 1.0;
68 mat[1][1] = -kb * 2.0 * (1.0 - kb) / kg;
69 mat[1][2] = -kr * 2.0 * (1.0 - kr) / kg;
70 // B
71 mat[2][0] = 1.0;
72 mat[2][1] = 2.0 * (1.0 - kb);
73 mat[2][2] = 0.0;
74 }
75
76 fn apply_pal_rgb2yuv(eu: f32, ev: f32, mat: &mut [[f32; 3]; 3]) {
77 let ufac = 2.0 * (1.0 - mat[0][2]) * eu;
78 let vfac = 2.0 * (1.0 - mat[0][0]) * ev;
79
80 // U
81 mat[1][0] *= ufac;
82 mat[1][1] *= ufac;
83 mat[1][2] = eu * (1.0 - mat[0][2]);
84 // V
85 mat[2][0] = ev * (1.0 - mat[0][0]);
86 mat[2][1] *= vfac;
87 mat[2][2] *= vfac;
88 }
89
90 fn apply_pal_yuv2rgb(eu: f32, ev: f32, mat: &mut [[f32; 3]; 3]) {
91 let ufac = 1.0 / (mat[2][1] * eu);
92 let vfac = 1.0 / (mat[0][2] * ev);
93
94 // R
95 mat[0][2] *= vfac;
96 // G
97 mat[1][1] *= ufac;
98 mat[1][2] *= vfac;
99 // B
100 mat[2][1] *= ufac;
101 }
102
103 fn apply_ntsc_rgb2yiq(params: &[f32; 4], mat: &mut [[f32; 3]; 3]) {
104 let ufac = 2.0 * (1.0 - mat[0][2]);
105 let vfac = 2.0 * (1.0 - mat[0][0]);
106 let mut tmp: [[f32; 3]; 2] = [[0.0; 3]; 2];
107
108 for i in 0..3 {
109 tmp[0][i] = mat[1][i] * ufac;
110 tmp[1][i] = mat[2][i] * vfac;
111 }
112 for i in 0..3 {
113 mat[1][i] = params[0] * tmp[0][i] + params[1] * tmp[1][i];
114 mat[2][i] = params[2] * tmp[0][i] + params[3] * tmp[1][i];
115 }
116 }
117
118 fn subm_det(mat: &[[f32; 3]; 3], col: usize, row: usize) -> f32 {
119 let row0 = if row == 0 { 1 } else { 0 };
120 let row1 = if (row == 1) || (row0 == 1) { 2 } else { 1 };
121 let col0 = if col == 0 { 1 } else { 0 };
122 let col1 = if (col == 1) || (col0 == 1) { 2 } else { 1 };
123
124 let det = mat[row0][col0] * mat[row1][col1] - mat[row0][col1] * mat[row1][col0];
125 if ((col ^ row) & 1) == 0 {
126 det
127 } else {
128 -det
129 }
130 }
131
132 fn invert_matrix(mat: &mut [[f32; 3]; 3]) {
133 let d00 = subm_det(mat, 0, 0);
134 let d01 = subm_det(mat, 0, 1);
135 let d02 = subm_det(mat, 0, 2);
136 let d10 = subm_det(mat, 1, 0);
137 let d11 = subm_det(mat, 1, 1);
138 let d12 = subm_det(mat, 1, 2);
139 let d20 = subm_det(mat, 2, 0);
140 let d21 = subm_det(mat, 2, 1);
141 let d22 = subm_det(mat, 2, 2);
142 let det = 1.0 / (mat[0][0] * d00 + mat[0][1] * d10 + mat[0][2] * d20).abs();
143
144 mat[0][0] = det * d00;
145 mat[0][1] = det * d01;
146 mat[0][2] = det * d02;
147 mat[1][0] = det * d10;
148 mat[1][1] = det * d11;
149 mat[1][2] = det * d12;
150 mat[2][0] = det * d20;
151 mat[2][1] = det * d21;
152 mat[2][2] = det * d22;
153 }
154
155 fn matrix_mul(mat: &[[f32; 3]; 3], a: f32, b: f32, c: f32) -> (f32, f32, f32) {
156 (a * mat[0][0] + b * mat[0][1] + c * mat[0][2],
157 a * mat[1][0] + b * mat[1][1] + c * mat[1][2],
158 a * mat[2][0] + b * mat[2][1] + c * mat[2][2] )
159 }
160
161 #[derive(Default)]
162 struct RgbToYuv {
163 matrix: [[f32; 3]; 3],
164 }
165
166 impl RgbToYuv {
167 fn new() -> Self { Self::default() }
168 }
169
170 #[allow(clippy::many_single_char_names)]
171 impl Kernel for RgbToYuv {
172 fn init(&mut self, in_fmt: &ScaleInfo, dest_fmt: &ScaleInfo) -> ScaleResult<NABufferType> {
173 let mut df = dest_fmt.fmt;
174 //todo coeff selection
175 make_rgb2yuv(YUV_PARAMS[2][0], YUV_PARAMS[2][1], &mut self.matrix);
176 if let ColorModel::YUV(yuvsm) = df.get_model() {
177 match yuvsm {
178 YUVSubmodel::YCbCr => {},
179 YUVSubmodel::YIQ => { apply_ntsc_rgb2yiq(SMPTE_NTSC_COEFFS, &mut self.matrix); },
180 YUVSubmodel::YUVJ => { apply_pal_rgb2yuv(BT_PAL_COEFFS[0], BT_PAL_COEFFS[1], &mut self.matrix); },
181 };
182 } else {
183 return Err(ScaleError::InvalidArgument);
184 }
185 for i in 0..MAX_CHROMATONS {
186 if let Some(ref mut chr) = df.comp_info[i] {
187 chr.packed = false;
188 chr.comp_offs = i as u8;
189 chr.h_ss = 0;
190 chr.v_ss = 0;
191 }
192 }
193 println!(" [intermediate format {}]", df);
194 let res = alloc_video_buffer(NAVideoInfo::new(in_fmt.width, in_fmt.height, false, df), 3);
195 if res.is_err() { return Err(ScaleError::AllocError); }
196 Ok(res.unwrap())
197 }
198 fn process(&mut self, pic_in: &NABufferType, pic_out: &mut NABufferType) {
199 if let (Some(ref sbuf), Some(ref mut dbuf)) = (pic_in.get_vbuf(), pic_out.get_vbuf()) {
200 let istrides = [sbuf.get_stride(0), sbuf.get_stride(1), sbuf.get_stride(2)];
201 let dstrides = [dbuf.get_stride(0), dbuf.get_stride(1), dbuf.get_stride(2)];
202 let (w, h) = sbuf.get_dimensions(0);
203
204 let mut roff = sbuf.get_offset(0);
205 let mut goff = sbuf.get_offset(1);
206 let mut boff = sbuf.get_offset(2);
207 let mut yoff = dbuf.get_offset(0);
208 let mut uoff = dbuf.get_offset(1);
209 let mut voff = dbuf.get_offset(2);
210 let src = sbuf.get_data();
211 let dst = dbuf.get_data_mut().unwrap();
212 for _y in 0..h {
213 for x in 0..w {
214 let r = f32::from(src[roff + x]);
215 let g = f32::from(src[goff + x]);
216 let b = f32::from(src[boff + x]);
217 let (y, u, v) = matrix_mul(&self.matrix, r, g, b);
218
219 dst[yoff + x] = (y as i16).max(0).min(255) as u8;
220 dst[uoff + x] = ((u as i16).max(-128).min(128) + 128) as u8;
221 dst[voff + x] = ((v as i16).max(-128).min(128) + 128) as u8;
222 }
223 roff += istrides[0];
224 goff += istrides[1];
225 boff += istrides[2];
226 yoff += dstrides[0];
227 uoff += dstrides[1];
228 voff += dstrides[2];
229 }
230 }
231 }
232 }
233
234 pub fn create_rgb2yuv() -> Box<dyn Kernel> {
235 Box::new(RgbToYuv::new())
236 }
237
238 #[derive(Default)]
239 struct YuvToRgb {
240 matrix: [[f32; 3]; 3],
241 yscale: Vec<i16>,
242 r_chr: Vec<i16>,
243 g_u: Vec<i16>,
244 g_v: Vec<i16>,
245 b_chr: Vec<i16>,
246 }
247
248 impl YuvToRgb {
249 fn new() -> Self { Self::default() }
250 }
251
252 #[allow(clippy::many_single_char_names)]
253 impl Kernel for YuvToRgb {
254 fn init(&mut self, in_fmt: &ScaleInfo, dest_fmt: &ScaleInfo) -> ScaleResult<NABufferType> {
255 let mut df = dest_fmt.fmt;
256 df.palette = false;
257 //todo coeff selection
258 make_yuv2rgb(YUV_PARAMS[2][0], YUV_PARAMS[2][1], &mut self.matrix);
259 if let ColorModel::YUV(yuvsm) = in_fmt.fmt.get_model() {
260 match yuvsm {
261 YUVSubmodel::YCbCr => {},
262 YUVSubmodel::YIQ => {
263 make_rgb2yuv(YUV_PARAMS[2][0], YUV_PARAMS[2][1], &mut self.matrix);
264 apply_ntsc_rgb2yiq(SMPTE_NTSC_COEFFS, &mut self.matrix);
265 invert_matrix(&mut self.matrix);
266 },
267 YUVSubmodel::YUVJ => {
268 apply_pal_yuv2rgb(BT_PAL_COEFFS[0], BT_PAL_COEFFS[1], &mut self.matrix);
269 },
270 };
271 if yuvsm != YUVSubmodel::YIQ {
272 self.yscale = Vec::with_capacity(256);
273 self.r_chr = Vec::with_capacity(256);
274 self.g_u = Vec::with_capacity(256);
275 self.g_v = Vec::with_capacity(256);
276 self.b_chr = Vec::with_capacity(256);
277 for i in 0..256 {
278 let yval = i as i16; // todo limited range as well
279 self.yscale.push(yval);
280 let rval = (((i as f32) - 128.0) * self.matrix[0][2]) as i16;
281 self.r_chr.push(rval);
282 let uval = (((i as f32) - 128.0) * self.matrix[1][1]) as i16;
283 self.g_u.push(uval);
284 let vval = (((i as f32) - 128.0) * self.matrix[1][2]) as i16;
285 self.g_v.push(vval);
286 let bval = (((i as f32) - 128.0) * self.matrix[2][1]) as i16;
287 self.b_chr.push(bval);
288 }
289 }
290 } else {
291 return Err(ScaleError::InvalidArgument);
292 }
293 for i in 0..MAX_CHROMATONS {
294 if let Some(ref mut chr) = df.comp_info[i] {
295 chr.packed = false;
296 chr.comp_offs = i as u8;
297 }
298 }
299 println!(" [intermediate format {}]", df);
300 let res = alloc_video_buffer(NAVideoInfo::new(in_fmt.width, in_fmt.height, false, df), 3);
301 if res.is_err() { return Err(ScaleError::AllocError); }
302 Ok(res.unwrap())
303 }
304 fn process(&mut self, pic_in: &NABufferType, pic_out: &mut NABufferType) {
305 if let (Some(ref sbuf), Some(ref mut dbuf)) = (pic_in.get_vbuf(), pic_out.get_vbuf()) {
306 let istrides = [sbuf.get_stride(0), sbuf.get_stride(1), sbuf.get_stride(2)];
307 let dstrides = [dbuf.get_stride(0), dbuf.get_stride(1), dbuf.get_stride(2)];
308 let (w, h) = sbuf.get_dimensions(0);
309 let (sv0, sh0) = sbuf.get_info().get_format().get_chromaton(1).unwrap().get_subsampling();
310 let (sv1, sh1) = sbuf.get_info().get_format().get_chromaton(2).unwrap().get_subsampling();
311
312 let uhmask = (1 << sh0) - 1;
313 let vhmask = (1 << sh1) - 1;
314 let mut roff = dbuf.get_offset(0);
315 let mut goff = dbuf.get_offset(1);
316 let mut boff = dbuf.get_offset(2);
317 let mut yoff = sbuf.get_offset(0);
318 let mut uoff = sbuf.get_offset(1);
319 let mut voff = sbuf.get_offset(2);
320 let src = sbuf.get_data();
321 let dst = dbuf.get_data_mut().unwrap();
322 if self.yscale.len() > 0 {
323 for y in 0..h {
324 for x in 0..w {
325 let y = self.yscale[src[yoff + x] as usize];
326 let u = src[uoff + (x >> sv0)] as usize;
327 let v = src[voff + (x >> sv1)] as usize;
328 let r = y + self.r_chr[v];
329 let g = y + self.g_u[u] + self.g_v[v];
330 let b = y + self.b_chr[u];
331 dst[roff + x] = r.max(0).min(255) as u8;
332 dst[goff + x] = g.max(0).min(255) as u8;
333 dst[boff + x] = b.max(0).min(255) as u8;
334 }
335 roff += dstrides[0];
336 goff += dstrides[1];
337 boff += dstrides[2];
338 yoff += istrides[0];
339 if (y & uhmask) == uhmask {
340 uoff += istrides[1];
341 }
342 if (y & vhmask) == vhmask {
343 voff += istrides[2];
344 }
345 }
346 return;
347 }
348 for y in 0..h {
349 for x in 0..w {
350 let y = f32::from(src[yoff + x]);
351 let u = f32::from(i16::from(src[uoff + (x >> sv0)]) - 128);
352 let v = f32::from(i16::from(src[voff + (x >> sv1)]) - 128);
353
354 let (r, g, b) = matrix_mul(&self.matrix, y, u, v);
355 dst[roff + x] = (r as i16).max(0).min(255) as u8;
356 dst[goff + x] = (g as i16).max(0).min(255) as u8;
357 dst[boff + x] = (b as i16).max(0).min(255) as u8;
358 }
359 roff += dstrides[0];
360 goff += dstrides[1];
361 boff += dstrides[2];
362 yoff += istrides[0];
363 if (y & uhmask) == uhmask {
364 uoff += istrides[1];
365 }
366 if (y & vhmask) == vhmask {
367 voff += istrides[2];
368 }
369 }
370 }
371 }
372 }
373
374 pub fn create_yuv2rgb() -> Box<dyn Kernel> {
375 Box::new(YuvToRgb::new())
376 }