Debian Codegraph @

debian/missing-sources/image/src/codecs/avif/yuv.rs

raw
1 use crate::error::DecodingError;
2 use crate::{ImageError, ImageFormat};
3 use num_traits::AsPrimitive;
4 use std::fmt::{Display, Formatter};
5 use std::mem::size_of;
6
7 #[derive(Debug, Copy, Clone)]
8 /// Representation of inversion matrix
9 pub(crate) struct CbCrInverseTransform<T> {
10 y_coef: T,
11 cr_coef: T,
12 cb_coef: T,
13 g_coeff_1: T,
14 g_coeff_2: T,
15 }
16
17 impl CbCrInverseTransform<f32> {
18 fn to_integers(self, precision: u32) -> CbCrInverseTransform<i32> {
19 let precision_scale: i32 = 1i32 << (precision as i32);
20 let cr_coef = (self.cr_coef * precision_scale as f32) as i32;
21 let cb_coef = (self.cb_coef * precision_scale as f32) as i32;
22 let y_coef = (self.y_coef * precision_scale as f32) as i32;
23 let g_coef_1 = (self.g_coeff_1 * precision_scale as f32) as i32;
24 let g_coef_2 = (self.g_coeff_2 * precision_scale as f32) as i32;
25 CbCrInverseTransform::<i32> {
26 y_coef,
27 cr_coef,
28 cb_coef,
29 g_coeff_1: g_coef_1,
30 g_coeff_2: g_coef_2,
31 }
32 }
33 }
34
35 #[derive(Copy, Clone, Debug)]
36 struct ErrorSize {
37 expected: usize,
38 received: usize,
39 }
40
41 #[derive(Copy, Clone, Debug)]
42 pub(crate) enum PlaneDefinition {
43 Y,
44 U,
45 V,
46 }
47
48 impl Display for PlaneDefinition {
49 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
50 match self {
51 PlaneDefinition::Y => f.write_str("Luma"),
52 PlaneDefinition::U => f.write_str("U chroma"),
53 PlaneDefinition::V => f.write_str("V chroma"),
54 }
55 }
56 }
57
58 #[derive(Debug, Clone, Copy)]
59 enum YuvConversionError {
60 YuvPlaneSizeMismatch(PlaneDefinition, ErrorSize),
61 RgbDestinationSizeMismatch(ErrorSize),
62 }
63
64 impl Display for YuvConversionError {
65 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66 match self {
67 YuvConversionError::YuvPlaneSizeMismatch(plane, error_size) => {
68 f.write_fmt(format_args!(
69 "For plane {} expected size is {} but was received {}",
70 plane, error_size.received, error_size.expected,
71 ))
72 }
73 YuvConversionError::RgbDestinationSizeMismatch(error_size) => {
74 f.write_fmt(format_args!(
75 "For RGB destination expected size is {} but was received {}",
76 error_size.received, error_size.expected,
77 ))
78 }
79 }
80 }
81 }
82
83 impl std::error::Error for YuvConversionError {}
84
85 #[inline]
86 pub(crate) fn check_yuv_plane_preconditions<V>(
87 plane: &[V],
88 plane_definition: PlaneDefinition,
89 stride: usize,
90 height: usize,
91 ) -> Result<(), ImageError> {
92 if plane.len() != stride * height {
93 return Err(ImageError::Decoding(DecodingError::new(
94 ImageFormat::Avif.into(),
95 YuvConversionError::YuvPlaneSizeMismatch(
96 plane_definition,
97 ErrorSize {
98 expected: stride * height,
99 received: plane.len(),
100 },
101 ),
102 )));
103 }
104 Ok(())
105 }
106
107 #[inline]
108 pub(crate) fn check_rgb_preconditions<V>(
109 rgb_data: &[V],
110 stride: usize,
111 height: usize,
112 ) -> Result<(), ImageError> {
113 if rgb_data.len() != stride * height {
114 return Err(ImageError::Decoding(DecodingError::new(
115 ImageFormat::Avif.into(),
116 YuvConversionError::RgbDestinationSizeMismatch(ErrorSize {
117 expected: stride * height,
118 received: rgb_data.len(),
119 }),
120 )));
121 }
122 Ok(())
123 }
124
125 /// Transformation YUV to RGB with coefficients as specified in [ITU-R](https://www.itu.int/rec/T-REC-H.273/en)
126 fn get_inverse_transform(
127 range_bgra: u32,
128 range_y: u32,
129 range_uv: u32,
130 kr: f32,
131 kb: f32,
132 precision: u32,
133 ) -> CbCrInverseTransform<i32> {
134 let range_uv = range_bgra as f32 / range_uv as f32;
135 let y_coef = range_bgra as f32 / range_y as f32;
136 let cr_coeff = (2f32 * (1f32 - kr)) * range_uv;
137 let cb_coeff = (2f32 * (1f32 - kb)) * range_uv;
138 let kg = 1.0f32 - kr - kb;
139 assert_ne!(kg, 0., "1.0f - kr - kg must not be 0");
140 let g_coeff_1 = (2f32 * ((1f32 - kr) * kr / kg)) * range_uv;
141 let g_coeff_2 = (2f32 * ((1f32 - kb) * kb / kg)) * range_uv;
142 let exact_transform = CbCrInverseTransform {
143 y_coef,
144 cr_coef: cr_coeff,
145 cb_coef: cb_coeff,
146 g_coeff_1,
147 g_coeff_2,
148 };
149 exact_transform.to_integers(precision)
150 }
151
152 #[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
153 /// Declares YUV range TV (limited) or PC (full),
154 /// more info [ITU-R](https://www.itu.int/rec/T-REC-H.273/en)
155 pub(crate) enum YuvIntensityRange {
156 /// Limited range Y ∈ [16 << (depth - 8), 16 << (depth - 8) + 224 << (depth - 8)],
157 /// UV ∈ [-1 << (depth - 1), -1 << (depth - 1) + 1 << (depth - 1)]
158 Tv,
159 /// Full range Y ∈ [0, 2^bit_depth - 1],
160 /// UV ∈ [-1 << (depth - 1), -1 << (depth - 1) + 2^bit_depth - 1]
161 Pc,
162 }
163
164 #[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
165 pub(crate) struct YuvChromaRange {
166 pub(crate) bias_y: u32,
167 pub(crate) bias_uv: u32,
168 pub(crate) range_y: u32,
169 pub(crate) range_uv: u32,
170 pub(crate) range: YuvIntensityRange,
171 }
172
173 impl YuvIntensityRange {
174 pub(crate) const fn get_yuv_range(self, depth: u32) -> YuvChromaRange {
175 match self {
176 YuvIntensityRange::Tv => YuvChromaRange {
177 bias_y: 16 << (depth - 8),
178 bias_uv: 1 << (depth - 1),
179 range_y: 219 << (depth - 8),
180 range_uv: 224 << (depth - 8),
181 range: self,
182 },
183 YuvIntensityRange::Pc => YuvChromaRange {
184 bias_y: 0,
185 bias_uv: 1 << (depth - 1),
186 range_uv: (1 << depth) - 1,
187 range_y: (1 << depth) - 1,
188 range: self,
189 },
190 }
191 }
192 }
193
194 #[derive(Debug, Copy, Clone, PartialOrd, PartialEq, Eq)]
195 /// Declares standard prebuilt YUV conversion matrices,
196 /// check [ITU-R](https://www.itu.int/rec/T-REC-H.273/en) information for more info
197 pub(crate) enum YuvStandardMatrix {
198 Bt601,
199 Bt709,
200 Bt2020,
201 Smpte240,
202 Bt470_6,
203 }
204
205 #[derive(Debug, Copy, Clone, PartialOrd, PartialEq)]
206 struct YuvBias {
207 kr: f32,
208 kb: f32,
209 }
210
211 impl YuvStandardMatrix {
212 const fn get_kr_kb(self) -> YuvBias {
213 match self {
214 YuvStandardMatrix::Bt601 => YuvBias {
215 kr: 0.299f32,
216 kb: 0.114f32,
217 },
218 YuvStandardMatrix::Bt709 => YuvBias {
219 kr: 0.2126f32,
220 kb: 0.0722f32,
221 },
222 YuvStandardMatrix::Bt2020 => YuvBias {
223 kr: 0.2627f32,
224 kb: 0.0593f32,
225 },
226 YuvStandardMatrix::Smpte240 => YuvBias {
227 kr: 0.087f32,
228 kb: 0.212f32,
229 },
230 YuvStandardMatrix::Bt470_6 => YuvBias {
231 kr: 0.2220f32,
232 kb: 0.0713f32,
233 },
234 }
235 }
236 }
237
238 pub(crate) struct YuvPlanarImage<'a, T> {
239 pub(crate) y_plane: &'a [T],
240 pub(crate) y_stride: usize,
241 pub(crate) u_plane: &'a [T],
242 pub(crate) u_stride: usize,
243 pub(crate) v_plane: &'a [T],
244 pub(crate) v_stride: usize,
245 pub(crate) width: usize,
246 pub(crate) height: usize,
247 }
248
249 #[inline(always)]
250 /// Saturating rounding shift right against bit depth
251 pub(crate) fn qrshr<const PRECISION: i32, const BIT_DEPTH: usize>(val: i32) -> i32 {
252 let rounding: i32 = 1 << (PRECISION - 1);
253 let max_value: i32 = (1 << BIT_DEPTH) - 1;
254 ((val + rounding) >> PRECISION).clamp(0, max_value)
255 }
256
257 /// Converts Yuv 400 planar format 8 bit to Rgba 8 bit
258 ///
259 /// # Arguments
260 ///
261 /// * `image`: see [YuvGrayImage]
262 /// * `rgba`: RGBA image layout
263 /// * `range`: see [YuvIntensityRange]
264 /// * `matrix`: see [YuvStandardMatrix]
265 ///
266 pub(crate) fn yuv400_to_rgba8(
267 image: YuvPlanarImage<u8>,
268 rgba: &mut [u8],
269 range: YuvIntensityRange,
270 matrix: YuvStandardMatrix,
271 ) -> Result<(), ImageError> {
272 yuv400_to_rgbx_impl::<u8, 4, 8>(image, rgba, range, matrix)
273 }
274
275 /// Converts Yuv 400 planar format 10 bit to Rgba 10 bit
276 ///
277 /// # Arguments
278 ///
279 /// * `image`: see [YuvGrayImage]
280 /// * `rgba`: RGBA image layout
281 /// * `range`: see [YuvIntensityRange]
282 /// * `matrix`: see [YuvStandardMatrix]
283 ///
284 pub(crate) fn yuv400_to_rgba10(
285 image: YuvPlanarImage<u16>,
286 rgba: &mut [u16],
287 range: YuvIntensityRange,
288 matrix: YuvStandardMatrix,
289 ) -> Result<(), ImageError> {
290 yuv400_to_rgbx_impl::<u16, 4, 10>(image, rgba, range, matrix)
291 }
292
293 /// Converts Yuv 400 planar format 12 bit to Rgba 12 bit
294 ///
295 /// # Arguments
296 ///
297 /// * `image`: see [YuvGrayImage]
298 /// * `rgba`: RGBA image layout
299 /// * `range`: see [YuvIntensityRange]
300 /// * `matrix`: see [YuvStandardMatrix]
301 ///
302 pub(crate) fn yuv400_to_rgba12(
303 image: YuvPlanarImage<u16>,
304 rgba: &mut [u16],
305 range: YuvIntensityRange,
306 matrix: YuvStandardMatrix,
307 ) -> Result<(), ImageError> {
308 yuv400_to_rgbx_impl::<u16, 4, 12>(image, rgba, range, matrix)
309 }
310
311 /// Converts Yuv 400 planar format to Rgba
312 ///
313 /// # Arguments
314 ///
315 /// * `image`: see [YuvGrayImage]
316 /// * `rgba`: RGBA image layout
317 /// * `range`: see [YuvIntensityRange]
318 /// * `matrix`: see [YuvStandardMatrix]
319 ///
320 #[inline]
321 fn yuv400_to_rgbx_impl<
322 V: Copy + AsPrimitive<i32> + 'static + Sized,
323 const CHANNELS: usize,
324 const BIT_DEPTH: usize,
325 >(
326 image: YuvPlanarImage<V>,
327 rgba: &mut [V],
328 range: YuvIntensityRange,
329 matrix: YuvStandardMatrix,
330 ) -> Result<(), ImageError>
331 where
332 i32: AsPrimitive<V>,
333 {
334 assert!(
335 CHANNELS == 3 || CHANNELS == 4,
336 "YUV 4:0:0 -> RGB is implemented only on 3 and 4 channels"
337 );
338 assert!(
339 (8..=16).contains(&BIT_DEPTH),
340 "Invalid bit depth is provided"
341 );
342 assert!(
343 if BIT_DEPTH > 8 {
344 size_of::<V>() == 2
345 } else {
346 size_of::<V>() == 1
347 },
348 "Unsupported bit depth and data type combination"
349 );
350
351 let y_plane = image.y_plane;
352 let y_stride = image.y_stride;
353 let height = image.height;
354 let width = image.width;
355
356 check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, height)?;
357 check_rgb_preconditions(rgba, width * CHANNELS, height)?;
358
359 let rgba_stride = width * CHANNELS;
360
361 let max_value = (1 << BIT_DEPTH) - 1;
362
363 // If luma plane is in full range it can be just redistributed across the image
364 if range == YuvIntensityRange::Pc {
365 let y_iter = y_plane.chunks_exact(y_stride);
366 let rgb_iter = rgba.chunks_exact_mut(rgba_stride);
367
368 // All branches on generic const will be optimized out.
369 for (y_src, rgb) in y_iter.zip(rgb_iter) {
370 let rgb_chunks = rgb.as_chunks_mut::<CHANNELS>().0.iter_mut();
371
372 for (y_src, rgb_dst) in y_src.iter().zip(rgb_chunks) {
373 let r = *y_src;
374 rgb_dst[0] = r;
375 rgb_dst[1] = r;
376 rgb_dst[2] = r;
377 if CHANNELS == 4 {
378 rgb_dst[3] = max_value.as_();
379 }
380 }
381 }
382 return Ok(());
383 }
384
385 let range = range.get_yuv_range(BIT_DEPTH as u32);
386 let kr_kb = matrix.get_kr_kb();
387 const PRECISION: i32 = 11;
388
389 let inverse_transform = get_inverse_transform(
390 (1 << BIT_DEPTH) - 1,
391 range.range_y,
392 range.range_uv,
393 kr_kb.kr,
394 kr_kb.kb,
395 PRECISION as u32,
396 );
397 let y_coef = inverse_transform.y_coef;
398
399 let bias_y = range.bias_y as i32;
400
401 let y_iter = y_plane.chunks_exact(y_stride);
402 let rgb_iter = rgba.chunks_exact_mut(rgba_stride);
403
404 // All branches on generic const will be optimized out.
405 for (y_src, rgb) in y_iter.zip(rgb_iter) {
406 let rgb_chunks = rgb.as_chunks_mut::<CHANNELS>().0.iter_mut();
407
408 for (y_src, rgb_dst) in y_src.iter().zip(rgb_chunks) {
409 let y_value = (y_src.as_() - bias_y) * y_coef;
410
411 let r = qrshr::<PRECISION, BIT_DEPTH>(y_value);
412 rgb_dst[0] = r.as_();
413 rgb_dst[1] = r.as_();
414 rgb_dst[2] = r.as_();
415 if CHANNELS == 4 {
416 rgb_dst[3] = max_value.as_();
417 }
418 }
419 }
420
421 Ok(())
422 }
423
424 /// Converts YUV420 8 bit-depth to Rgba 8 bit
425 ///
426 /// # Arguments
427 ///
428 /// * `image`: see [YuvPlanarImage]
429 /// * `rgb`: RGB image layout
430 /// * `range`: see [YuvIntensityRange]
431 /// * `matrix`: see [YuvStandardMatrix]
432 ///
433 pub(crate) fn yuv420_to_rgba8(
434 image: YuvPlanarImage<u8>,
435 rgb: &mut [u8],
436 range: YuvIntensityRange,
437 matrix: YuvStandardMatrix,
438 ) -> Result<(), ImageError> {
439 const P: i32 = 13;
440 yuv420_to_rgbx_invoker::<u8, HalvedRowHandler<u8>, P, 4, 8>(
441 image,
442 rgb,
443 range,
444 matrix,
445 process_halved_chroma_row_cbcr::<u8, P, 4, 8>,
446 )
447 }
448
449 /// Converts YUV420 10 bit-depth to Rgba 10 bit-depth
450 ///
451 /// # Arguments
452 ///
453 /// * `image`: see [YuvPlanarImage]
454 /// * `rgb`: RGB image layout
455 /// * `range`: see [YuvIntensityRange]
456 /// * `matrix`: see [YuvStandardMatrix]
457 ///
458 pub(crate) fn yuv420_to_rgba10(
459 image: YuvPlanarImage<u16>,
460 rgb: &mut [u16],
461 range: YuvIntensityRange,
462 matrix: YuvStandardMatrix,
463 ) -> Result<(), ImageError> {
464 const P: i32 = 13;
465 yuv420_to_rgbx_invoker::<u16, HalvedRowHandler<u16>, P, 4, 10>(
466 image,
467 rgb,
468 range,
469 matrix,
470 process_halved_chroma_row_cbcr::<u16, P, 4, 10>,
471 )
472 }
473
474 pub(crate) type HalvedRowHandler<V> =
475 fn(YuvPlanarImage<V>, &mut [V], &CbCrInverseTransform<i32>, &YuvChromaRange);
476
477 /// Converts YUV420 12 bit-depth to Rgba 12 bit-depth
478 ///
479 /// # Arguments
480 ///
481 /// * `image`: see [YuvPlanarImage]
482 /// * `rgb`: RGB image layout
483 /// * `range`: see [YuvIntensityRange]
484 /// * `matrix`: see [YuvStandardMatrix]
485 ///
486 pub(crate) fn yuv420_to_rgba12(
487 image: YuvPlanarImage<u16>,
488 rgb: &mut [u16],
489 range: YuvIntensityRange,
490 matrix: YuvStandardMatrix,
491 ) -> Result<(), ImageError> {
492 const P: i32 = 13;
493 yuv420_to_rgbx_invoker::<u16, HalvedRowHandler<u16>, P, 4, 12>(
494 image,
495 rgb,
496 range,
497 matrix,
498 process_halved_chroma_row_cbcr::<u16, P, 4, 12>,
499 )
500 }
501
502 /// Computes YCbCr inverse
503 /// # Arguments
504 /// - `dst` - dest buffer
505 /// - `y_value` - Y value with subtracted bias
506 /// - `cb` - Cb value with subtracted bias
507 /// - `cr` - Cr value with subtracted bias
508 #[inline(always)]
509 fn ycbcr_execute<
510 V: Copy + AsPrimitive<i32> + 'static + Sized,
511 const PRECISION: i32,
512 const CHANNELS: usize,
513 const BIT_DEPTH: usize,
514 >(
515 dst: &mut [V; CHANNELS],
516 y_value: i32,
517 cb: i32,
518 cr: i32,
519 t: &CbCrInverseTransform<i32>,
520 ) where
521 i32: AsPrimitive<V>,
522 {
523 let y_scaled = y_value * t.y_coef;
524 let r = qrshr::<PRECISION, BIT_DEPTH>(y_scaled + t.cr_coef * cr);
525 let b = qrshr::<PRECISION, BIT_DEPTH>(y_scaled + t.cb_coef * cb);
526 let g = qrshr::<PRECISION, BIT_DEPTH>(y_scaled - t.g_coeff_1 * cr - t.g_coeff_2 * cb);
527
528 if CHANNELS == 4 {
529 dst[0] = r.as_();
530 dst[1] = g.as_();
531 dst[2] = b.as_();
532 dst[3] = ((1i32 << BIT_DEPTH) - 1).as_();
533 } else if CHANNELS == 3 {
534 dst[0] = r.as_();
535 dst[1] = g.as_();
536 dst[2] = b.as_();
537 } else {
538 unreachable!();
539 }
540 }
541
542 #[inline]
543 fn process_halved_chroma_row_cbcr<
544 V: Copy + AsPrimitive<i32> + 'static + Sized,
545 const PRECISION: i32,
546 const CHANNELS: usize,
547 const BIT_DEPTH: usize,
548 >(
549 image: YuvPlanarImage<V>,
550 rgba: &mut [V],
551 transform: &CbCrInverseTransform<i32>,
552 range: &YuvChromaRange,
553 ) where
554 i32: AsPrimitive<V>,
555 {
556 // If the stride is larger than the plane size,
557 // it might contain junk data beyond the actual valid region.
558 // To avoid processing artifacts when working with odd-sized images,
559 // the buffer is reshaped to its actual size,
560 // preventing accidental use of invalid values from the trailing region.
561
562 let y_plane = &image.y_plane[0..image.width];
563 let chroma_size = image.width.div_ceil(2);
564 let u_plane = &image.u_plane[0..chroma_size];
565 let v_plane = &image.v_plane[0..chroma_size];
566 let rgba = &mut rgba[0..image.width * CHANNELS];
567
568 let bias_y = range.bias_y as i32;
569 let bias_uv = range.bias_uv as i32;
570 let (y_iter, y_left) = y_plane.as_chunks::<2>();
571 let mut rgb_chunks = rgba.chunks_exact_mut(CHANNELS * 2);
572 for (((y_src, &u_src), &v_src), rgb_dst) in
573 y_iter.iter().zip(u_plane).zip(v_plane).zip(&mut rgb_chunks)
574 {
575 let y_value0: i32 = y_src[0].as_() - bias_y;
576 let cb_value: i32 = u_src.as_() - bias_uv;
577 let cr_value: i32 = v_src.as_() - bias_uv;
578
579 let dst0 = &mut rgb_dst[..CHANNELS];
580
581 ycbcr_execute::<V, PRECISION, CHANNELS, BIT_DEPTH>(
582 dst0.try_into().unwrap(),
583 y_value0,
584 cb_value,
585 cr_value,
586 transform,
587 );
588
589 let y_value1 = y_src[1].as_() - bias_y;
590
591 let dst1 = &mut rgb_dst[CHANNELS..2 * CHANNELS];
592
593 ycbcr_execute::<V, PRECISION, CHANNELS, BIT_DEPTH>(
594 dst1.try_into().unwrap(),
595 y_value1,
596 cb_value,
597 cr_value,
598 transform,
599 );
600 }
601
602 // Process remainder if width is odd.
603 if image.width & 1 != 0 {
604 let rgb_chunks = rgb_chunks
605 .into_remainder()
606 .as_chunks_mut::<CHANNELS>()
607 .0
608 .iter_mut();
609 let u_iter = u_plane.iter().rev();
610 let v_iter = v_plane.iter().rev();
611
612 for (((y_src, u_src), v_src), rgb_dst) in
613 y_left.iter().zip(u_iter).zip(v_iter).zip(rgb_chunks)
614 {
615 let y_value = y_src.as_() - bias_y;
616 let cb_value = u_src.as_() - bias_uv;
617 let cr_value = v_src.as_() - bias_uv;
618
619 ycbcr_execute::<V, PRECISION, CHANNELS, BIT_DEPTH>(
620 rgb_dst, y_value, cb_value, cr_value, transform,
621 );
622 }
623 }
624 }
625
626 /// Converts YUV420 to Rgba
627 ///
628 /// # Arguments
629 ///
630 /// * `image`: see [YuvPlanarImage]
631 /// * `rgb`: RGB image layout
632 /// * `range`: see [YuvIntensityRange]
633 /// * `matrix`: see [YuvStandardMatrix]
634 ///
635 pub(crate) fn yuv420_to_rgbx_invoker<
636 V: Copy + AsPrimitive<i32> + 'static + Sized,
637 W: Fn(YuvPlanarImage<V>, &mut [V], &CbCrInverseTransform<i32>, &YuvChromaRange),
638 const PRECISION: i32,
639 const CHANNELS: usize,
640 const BIT_DEPTH: usize,
641 >(
642 image: YuvPlanarImage<V>,
643 rgb: &mut [V],
644 range: YuvIntensityRange,
645 matrix: YuvStandardMatrix,
646 worker: W,
647 ) -> Result<(), ImageError>
648 where
649 i32: AsPrimitive<V>,
650 {
651 assert!(
652 CHANNELS == 3 || CHANNELS == 4,
653 "YUV 4:2:0 -> RGB is implemented only on 3 and 4 channels"
654 );
655 assert!(
656 (8..=16).contains(&BIT_DEPTH),
657 "Invalid bit depth is provided"
658 );
659 assert!(
660 if BIT_DEPTH > 8 {
661 size_of::<V>() == 2
662 } else {
663 size_of::<V>() == 1
664 },
665 "Unsupported bit depth and data type combination"
666 );
667 let y_plane = image.y_plane;
668 let u_plane = image.u_plane;
669 let v_plane = image.v_plane;
670 let y_stride = image.y_stride;
671 let u_stride = image.u_stride;
672 let v_stride = image.v_stride;
673 let chroma_height = image.height.div_ceil(2);
674
675 check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, image.height)?;
676 check_yuv_plane_preconditions(u_plane, PlaneDefinition::U, u_stride, chroma_height)?;
677 check_yuv_plane_preconditions(v_plane, PlaneDefinition::V, v_stride, chroma_height)?;
678
679 check_rgb_preconditions(rgb, image.width * CHANNELS, image.height)?;
680
681 let range = range.get_yuv_range(BIT_DEPTH as u32);
682 let kr_kb = matrix.get_kr_kb();
683 let inverse_transform = get_inverse_transform(
684 (1 << BIT_DEPTH) - 1,
685 range.range_y,
686 range.range_uv,
687 kr_kb.kr,
688 kr_kb.kb,
689 PRECISION as u32,
690 );
691
692 let rgb_stride = image.width * CHANNELS;
693
694 let y_iter = y_plane.chunks_exact(y_stride * 2);
695 let rgb_iter = rgb.chunks_exact_mut(rgb_stride * 2);
696 let u_iter = u_plane.chunks_exact(u_stride);
697 let v_iter = v_plane.chunks_exact(v_stride);
698
699 /*
700 Sample 4x4 YUV420 planar image
701 start_y + 0: Y00 Y01 Y02 Y03
702 start_y + 4: Y04 Y05 Y06 Y07
703 start_y + 8: Y08 Y09 Y10 Y11
704 start_y + 12: Y12 Y13 Y14 Y15
705 start_cb + 0: Cb00 Cb01
706 start_cb + 2: Cb02 Cb03
707 start_cr + 0: Cr00 Cr01
708 start_cr + 2: Cr02 Cr03
709
710 For 4 luma components (2x2 on rows and cols) there are 1 chroma Cb/Cr components.
711 Luma channel must have always exact size as RGB target layout, but chroma is not.
712
713 We're sectioning an image by pair of rows, then for each pair of luma and RGB row,
714 there is one chroma row.
715
716 As chroma is shrunk by factor of 2 then we're processing by pairs of RGB and luma,
717 for each RGB and luma pair there is one chroma component.
718
719 If image have odd width then luma channel must be exact, and we're replicating last
720 chroma component.
721
722 If image have odd height then luma channel is exact, and we're replicating last chroma rows.
723 */
724
725 // All branches on generic const will be optimized out.
726 for (((y_src, u_src), v_src), rgb) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
727 // Since we're processing two rows in one loop we need to re-slice once more
728 let y_iter = y_src.chunks_exact(y_stride);
729 let rgb_iter = rgb.chunks_exact_mut(rgb_stride);
730 for (y_src, rgba) in y_iter.zip(rgb_iter) {
731 let image = YuvPlanarImage {
732 y_plane: y_src,
733 y_stride: 0,
734 u_plane: u_src,
735 u_stride: 0,
736 v_plane: v_src,
737 v_stride: 0,
738 width: image.width,
739 height: image.height,
740 };
741 worker(image, rgba, &inverse_transform, &range);
742 }
743 }
744
745 // Process remainder if height is odd
746
747 let y_iter = y_plane
748 .chunks_exact(y_stride * 2)
749 .remainder()
750 .chunks_exact(y_stride);
751 let rgb_iter = rgb.chunks_exact_mut(rgb_stride).rev();
752 let u_iter = u_plane.chunks_exact(u_stride).rev();
753 let v_iter = v_plane.chunks_exact(v_stride).rev();
754
755 for (((y_src, u_src), v_src), rgba) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
756 let image = YuvPlanarImage {
757 y_plane: y_src,
758 y_stride: 0,
759 u_plane: u_src,
760 u_stride: 0,
761 v_plane: v_src,
762 v_stride: 0,
763 width: image.width,
764 height: image.height,
765 };
766 worker(image, rgba, &inverse_transform, &range);
767 }
768
769 Ok(())
770 }
771
772 /// Converts Yuv 422 8-bit planar format to Rgba 8-bit
773 ///
774 /// # Arguments
775 ///
776 /// * `image`: see [YuvPlanarImage]
777 /// * `rgb`: RGB image layout
778 /// * `range`: see [YuvIntensityRange]
779 /// * `matrix`: see [YuvStandardMatrix]
780 ///
781 pub(crate) fn yuv422_to_rgba8(
782 image: YuvPlanarImage<u8>,
783 rgb: &mut [u8],
784 range: YuvIntensityRange,
785 matrix: YuvStandardMatrix,
786 ) -> Result<(), ImageError> {
787 const P: i32 = 13;
788 yuv422_to_rgbx_invoker::<u8, HalvedRowHandler<u8>, P, 4, 8>(
789 image,
790 rgb,
791 range,
792 matrix,
793 process_halved_chroma_row_cbcr::<u8, P, 4, 8>,
794 )
795 }
796
797 /// Converts Yuv 422 10-bit planar format to Rgba 10-bit
798 ///
799 /// # Arguments
800 ///
801 /// * `image`: see [YuvPlanarImage]
802 /// * `rgb`: RGB image layout
803 /// * `range`: see [YuvIntensityRange]
804 /// * `matrix`: see [YuvStandardMatrix]
805 ///
806 pub(crate) fn yuv422_to_rgba10(
807 image: YuvPlanarImage<u16>,
808 rgb: &mut [u16],
809 range: YuvIntensityRange,
810 matrix: YuvStandardMatrix,
811 ) -> Result<(), ImageError> {
812 const P: i32 = 13;
813 yuv422_to_rgbx_invoker::<u16, HalvedRowHandler<u16>, P, 4, 10>(
814 image,
815 rgb,
816 range,
817 matrix,
818 process_halved_chroma_row_cbcr::<u16, P, 4, 10>,
819 )
820 }
821
822 /// Converts Yuv 422 12-bit planar format to Rgba 12-bit
823 ///
824 /// # Arguments
825 ///
826 /// * `image`: see [YuvPlanarImage]
827 /// * `rgb`: RGB image layout
828 /// * `range`: see [YuvIntensityRange]
829 /// * `matrix`: see [YuvStandardMatrix]
830 ///
831 pub(crate) fn yuv422_to_rgba12(
832 image: YuvPlanarImage<u16>,
833 rgb: &mut [u16],
834 range: YuvIntensityRange,
835 matrix: YuvStandardMatrix,
836 ) -> Result<(), ImageError> {
837 const P: i32 = 13;
838 yuv422_to_rgbx_invoker::<u16, HalvedRowHandler<u16>, P, 4, 12>(
839 image,
840 rgb,
841 range,
842 matrix,
843 process_halved_chroma_row_cbcr::<u16, P, 4, 12>,
844 )
845 }
846
847 /// Converts Yuv 422 planar format to Rgba
848 ///
849 /// # Arguments
850 ///
851 /// * `image`: see [YuvPlanarImage]
852 /// * `rgb`: RGB image layout
853 /// * `range`: see [YuvIntensityRange]
854 /// * `matrix`: see [YuvStandardMatrix]
855 ///
856 pub(crate) fn yuv422_to_rgbx_invoker<
857 V: Copy + AsPrimitive<i32> + 'static + Sized,
858 W: Fn(YuvPlanarImage<V>, &mut [V], &CbCrInverseTransform<i32>, &YuvChromaRange),
859 const PRECISION: i32,
860 const CHANNELS: usize,
861 const BIT_DEPTH: usize,
862 >(
863 image: YuvPlanarImage<V>,
864 rgb: &mut [V],
865 range: YuvIntensityRange,
866 matrix: YuvStandardMatrix,
867 worker: W,
868 ) -> Result<(), ImageError>
869 where
870 i32: AsPrimitive<V>,
871 {
872 assert!(
873 CHANNELS == 3 || CHANNELS == 4,
874 "YUV 4:2:2 -> RGB is implemented only on 3 and 4 channels"
875 );
876 assert!(
877 (8..=16).contains(&BIT_DEPTH),
878 "Invalid bit depth is provided"
879 );
880 assert!(PRECISION < 16);
881 assert!(
882 if BIT_DEPTH > 8 {
883 size_of::<V>() == 2
884 } else {
885 size_of::<V>() == 1
886 },
887 "Unsupported bit depth and data type combination"
888 );
889 let y_plane = image.y_plane;
890 let u_plane = image.u_plane;
891 let v_plane = image.v_plane;
892 let y_stride = image.y_stride;
893 let u_stride = image.u_stride;
894 let v_stride = image.v_stride;
895 let width = image.width;
896
897 check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, image.height)?;
898 check_yuv_plane_preconditions(u_plane, PlaneDefinition::U, u_stride, image.height)?;
899 check_yuv_plane_preconditions(v_plane, PlaneDefinition::V, v_stride, image.height)?;
900
901 check_rgb_preconditions(rgb, image.width * CHANNELS, image.height)?;
902
903 let range = range.get_yuv_range(BIT_DEPTH as u32);
904 let kr_kb = matrix.get_kr_kb();
905
906 let inverse_transform = get_inverse_transform(
907 (1 << BIT_DEPTH) - 1,
908 range.range_y,
909 range.range_uv,
910 kr_kb.kr,
911 kr_kb.kb,
912 PRECISION as u32,
913 );
914
915 /*
916 Sample 4x4 YUV422 planar image
917 start_y + 0: Y00 Y01 Y02 Y03
918 start_y + 4: Y04 Y05 Y06 Y07
919 start_y + 8: Y08 Y09 Y10 Y11
920 start_y + 12: Y12 Y13 Y14 Y15
921 start_cb + 0: Cb00 Cb01
922 start_cb + 2: Cb02 Cb03
923 start_cb + 4: Cb04 Cb05
924 start_cb + 6: Cb06 Cb07
925 start_cr + 0: Cr00 Cr01
926 start_cr + 2: Cr02 Cr03
927 start_cr + 4: Cr04 Cr05
928 start_cr + 6: Cr06 Cr07
929
930 For 2 luma components there are 1 chroma Cb/Cr components.
931 Luma channel must have always exact size as RGB target layout, but chroma is not.
932
933 As chroma is shrunk by factor of 2 then we're processing by pairs of RGB and luma,
934 for each RGB and luma pair there is one chroma component.
935
936 If image have odd width then luma channel must be exact, and we're replicating last
937 chroma component.
938 */
939
940 let rgb_stride = width * CHANNELS;
941
942 let y_iter = y_plane.chunks_exact(y_stride);
943 let rgb_iter = rgb.chunks_exact_mut(rgb_stride);
944 let u_iter = u_plane.chunks_exact(u_stride);
945 let v_iter = v_plane.chunks_exact(v_stride);
946
947 // All branches on generic const will be optimized out.
948 for (((y_src, u_src), v_src), rgba) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
949 let image = YuvPlanarImage {
950 y_plane: y_src,
951 y_stride: 0,
952 u_plane: u_src,
953 u_stride: 0,
954 v_plane: v_src,
955 v_stride: 0,
956 width: image.width,
957 height: image.height,
958 };
959 worker(image, rgba, &inverse_transform, &range);
960 }
961
962 Ok(())
963 }
964
965 /// Converts Yuv 444 planar format 8 bit-depth to Rgba 8 bit
966 ///
967 /// # Arguments
968 ///
969 /// * `image`: see [YuvPlanarImage]
970 /// * `rgba`: RGB image layout
971 /// * `range`: see [YuvIntensityRange]
972 /// * `matrix`: see [YuvStandardMatrix]
973 ///
974 pub(crate) fn yuv444_to_rgba8(
975 image: YuvPlanarImage<u8>,
976 rgba: &mut [u8],
977 range: YuvIntensityRange,
978 matrix: YuvStandardMatrix,
979 ) -> Result<(), ImageError> {
980 yuv444_to_rgbx_impl::<u8, 4, 8>(image, rgba, range, matrix)
981 }
982
983 /// Converts Yuv 444 planar format 10 bit-depth to Rgba 10 bit
984 ///
985 /// # Arguments
986 ///
987 /// * `image`: see [YuvPlanarImage]
988 /// * `rgba`: RGB image layout
989 /// * `range`: see [YuvIntensityRange]
990 /// * `matrix`: see [YuvStandardMatrix]
991 ///
992 pub(super) fn yuv444_to_rgba10(
993 image: YuvPlanarImage<u16>,
994 rgba: &mut [u16],
995 range: YuvIntensityRange,
996 matrix: YuvStandardMatrix,
997 ) -> Result<(), ImageError> {
998 yuv444_to_rgbx_impl::<u16, 4, 10>(image, rgba, range, matrix)
999 }
1000
1001 /// Converts Yuv 444 planar format 12 bit-depth to Rgba 12 bit
1002 ///
1003 /// # Arguments
1004 ///
1005 /// * `image`: see [YuvPlanarImage]
1006 /// * `rgba`: RGB image layout
1007 /// * `range`: see [YuvIntensityRange]
1008 /// * `matrix`: see [YuvStandardMatrix]
1009 ///
1010 pub(super) fn yuv444_to_rgba12(
1011 image: YuvPlanarImage<u16>,
1012 rgba: &mut [u16],
1013 range: YuvIntensityRange,
1014 matrix: YuvStandardMatrix,
1015 ) -> Result<(), ImageError> {
1016 yuv444_to_rgbx_impl::<u16, 4, 12>(image, rgba, range, matrix)
1017 }
1018
1019 /// Converts Yuv 444 planar format to Rgba
1020 ///
1021 /// # Arguments
1022 ///
1023 /// * `image`: see [YuvPlanarImage]
1024 /// * `rgba`: RGB image layout
1025 /// * `range`: see [YuvIntensityRange]
1026 /// * `matrix`: see [YuvStandardMatrix]
1027 ///
1028 #[inline]
1029 fn yuv444_to_rgbx_impl<
1030 V: Copy + AsPrimitive<i32> + 'static + Sized,
1031 const CHANNELS: usize,
1032 const BIT_DEPTH: usize,
1033 >(
1034 image: YuvPlanarImage<V>,
1035 rgba: &mut [V],
1036 range: YuvIntensityRange,
1037 matrix: YuvStandardMatrix,
1038 ) -> Result<(), ImageError>
1039 where
1040 i32: AsPrimitive<V>,
1041 {
1042 assert!(
1043 CHANNELS == 3 || CHANNELS == 4,
1044 "YUV 4:4:4 -> RGB is implemented only on 3 and 4 channels"
1045 );
1046 assert!(
1047 (8..=16).contains(&BIT_DEPTH),
1048 "Invalid bit depth is provided"
1049 );
1050 assert!(
1051 if BIT_DEPTH > 8 {
1052 size_of::<V>() == 2
1053 } else {
1054 size_of::<V>() == 1
1055 },
1056 "Unsupported bit depth and data type combination"
1057 );
1058
1059 let y_plane = image.y_plane;
1060 let u_plane = image.u_plane;
1061 let v_plane = image.v_plane;
1062 let y_stride = image.y_stride;
1063 let u_stride = image.u_stride;
1064 let v_stride = image.v_stride;
1065 let height = image.height;
1066 let width = image.width;
1067
1068 check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, height)?;
1069 check_yuv_plane_preconditions(u_plane, PlaneDefinition::U, u_stride, height)?;
1070 check_yuv_plane_preconditions(v_plane, PlaneDefinition::V, v_stride, height)?;
1071
1072 check_rgb_preconditions(rgba, image.width * CHANNELS, height)?;
1073
1074 let range = range.get_yuv_range(BIT_DEPTH as u32);
1075 let kr_kb = matrix.get_kr_kb();
1076 const PRECISION: i32 = 13;
1077
1078 let inverse_transform = get_inverse_transform(
1079 (1 << BIT_DEPTH) - 1,
1080 range.range_y,
1081 range.range_uv,
1082 kr_kb.kr,
1083 kr_kb.kb,
1084 PRECISION as u32,
1085 );
1086
1087 let bias_y = range.bias_y as i32;
1088 let bias_uv = range.bias_uv as i32;
1089
1090 let rgb_stride = width * CHANNELS;
1091
1092 let y_iter = y_plane.chunks_exact(y_stride);
1093 let rgb_iter = rgba.chunks_exact_mut(rgb_stride);
1094 let u_iter = u_plane.chunks_exact(u_stride);
1095 let v_iter = v_plane.chunks_exact(v_stride);
1096
1097 // All branches on generic const will be optimized out.
1098 for (((y_src, u_src), v_src), rgb) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
1099 let rgb_chunks = rgb.as_chunks_mut::<CHANNELS>().0.iter_mut();
1100
1101 for (((y_src, u_src), v_src), rgb_dst) in y_src.iter().zip(u_src).zip(v_src).zip(rgb_chunks)
1102 {
1103 let y_value = y_src.as_() - bias_y;
1104 let cb_value = u_src.as_() - bias_uv;
1105 let cr_value = v_src.as_() - bias_uv;
1106
1107 ycbcr_execute::<V, PRECISION, CHANNELS, BIT_DEPTH>(
1108 rgb_dst,
1109 y_value,
1110 cb_value,
1111 cr_value,
1112 &inverse_transform,
1113 );
1114 }
1115 }
1116
1117 Ok(())
1118 }
1119
1120 /// Converts Gbr 8 bit planar format to Rgba 8 bit-depth
1121 ///
1122 /// # Arguments
1123 ///
1124 /// * `image`: see [YuvPlanarImage]
1125 /// * `rgb`: RGB image layout
1126 /// * `range`: see [YuvIntensityRange]
1127 ///
1128 pub(crate) fn gbr_to_rgba8(
1129 image: YuvPlanarImage<u8>,
1130 rgb: &mut [u8],
1131 range: YuvIntensityRange,
1132 ) -> Result<(), ImageError> {
1133 gbr_to_rgbx_impl::<u8, 4, 8>(image, rgb, range)
1134 }
1135
1136 /// Converts Gbr 10 bit planar format to Rgba 10 bit-depth
1137 ///
1138 ///
1139 /// # Arguments
1140 ///
1141 /// * `image`: see [YuvPlanarImage]
1142 /// * `rgba`: RGBx image layout
1143 /// * `range`: see [YuvIntensityRange]
1144 ///
1145 pub(crate) fn gbr_to_rgba10(
1146 image: YuvPlanarImage<u16>,
1147 rgba: &mut [u16],
1148 range: YuvIntensityRange,
1149 ) -> Result<(), ImageError> {
1150 gbr_to_rgbx_impl::<u16, 4, 10>(image, rgba, range)
1151 }
1152
1153 /// Converts Gbr 12 bit planar format to Rgba 12 bit-depth
1154 ///
1155 /// # Arguments
1156 ///
1157 /// * `image`: see [YuvPlanarImage]
1158 /// * `rgba`: RGBx image layout
1159 /// * `range`: see [YuvIntensityRange]
1160 ///
1161 pub(crate) fn gbr_to_rgba12(
1162 image: YuvPlanarImage<u16>,
1163 rgba: &mut [u16],
1164 range: YuvIntensityRange,
1165 ) -> Result<(), ImageError> {
1166 gbr_to_rgbx_impl::<u16, 4, 12>(image, rgba, range)
1167 }
1168
1169 /// Converts Gbr planar format to Rgba
1170 ///
1171 /// # Arguments
1172 ///
1173 /// * `image`: see [YuvPlanarImage]
1174 /// * `rgb`: RGB image layout
1175 /// * `range`: see [YuvIntensityRange]
1176 ///
1177 #[inline]
1178 fn gbr_to_rgbx_impl<
1179 V: Copy + AsPrimitive<i32> + 'static + Sized,
1180 const CHANNELS: usize,
1181 const BIT_DEPTH: usize,
1182 >(
1183 image: YuvPlanarImage<V>,
1184 rgba: &mut [V],
1185 yuv_range: YuvIntensityRange,
1186 ) -> Result<(), ImageError>
1187 where
1188 i32: AsPrimitive<V>,
1189 {
1190 assert!(
1191 CHANNELS == 3 || CHANNELS == 4,
1192 "GBR -> RGB is implemented only on 3 and 4 channels"
1193 );
1194 assert!(
1195 (8..=16).contains(&BIT_DEPTH),
1196 "Invalid bit depth is provided"
1197 );
1198 assert!(
1199 if BIT_DEPTH > 8 {
1200 size_of::<V>() == 2
1201 } else {
1202 size_of::<V>() == 1
1203 },
1204 "Unsupported bit depth and data type combination"
1205 );
1206 let y_plane = image.y_plane;
1207 let u_plane = image.u_plane;
1208 let v_plane = image.v_plane;
1209 let y_stride = image.y_stride;
1210 let u_stride = image.u_stride;
1211 let v_stride = image.v_stride;
1212 let height = image.height;
1213 let width = image.width;
1214
1215 check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, height)?;
1216 check_yuv_plane_preconditions(u_plane, PlaneDefinition::U, u_stride, height)?;
1217 check_yuv_plane_preconditions(v_plane, PlaneDefinition::V, v_stride, height)?;
1218
1219 check_rgb_preconditions(rgba, width * CHANNELS, height)?;
1220
1221 let max_value = (1 << BIT_DEPTH) - 1;
1222
1223 let rgb_stride = width * CHANNELS;
1224
1225 let y_iter = y_plane.chunks_exact(y_stride);
1226 let rgb_iter = rgba.chunks_exact_mut(rgb_stride);
1227 let u_iter = u_plane.chunks_exact(u_stride);
1228 let v_iter = v_plane.chunks_exact(v_stride);
1229
1230 match yuv_range {
1231 YuvIntensityRange::Tv => {
1232 const PRECISION: i32 = 11;
1233 // All channels on identity should use Y range
1234 let range = yuv_range.get_yuv_range(BIT_DEPTH as u32);
1235 let range_rgba = (1 << BIT_DEPTH) - 1;
1236 let y_coef =
1237 ((range_rgba as f32 / range.range_y as f32) * (1 << PRECISION) as f32) as i32;
1238 let y_bias = range.bias_y as i32;
1239
1240 for (((y_src, u_src), v_src), rgb) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
1241 let rgb_chunks = rgb.as_chunks_mut::<CHANNELS>().0.iter_mut();
1242
1243 for (((&y_src, &u_src), &v_src), rgb_dst) in
1244 y_src.iter().zip(u_src).zip(v_src).zip(rgb_chunks)
1245 {
1246 rgb_dst[0] =
1247 qrshr::<PRECISION, BIT_DEPTH>((v_src.as_() - y_bias) * y_coef).as_();
1248 rgb_dst[1] =
1249 qrshr::<PRECISION, BIT_DEPTH>((y_src.as_() - y_bias) * y_coef).as_();
1250 rgb_dst[2] =
1251 qrshr::<PRECISION, BIT_DEPTH>((u_src.as_() - y_bias) * y_coef).as_();
1252 if CHANNELS == 4 {
1253 rgb_dst[3] = max_value.as_();
1254 }
1255 }
1256 }
1257 }
1258 YuvIntensityRange::Pc => {
1259 for (((y_src, u_src), v_src), rgb) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
1260 let rgb_chunks = rgb.as_chunks_mut::<CHANNELS>().0.iter_mut();
1261
1262 for (((&y_src, &u_src), &v_src), rgb_dst) in
1263 y_src.iter().zip(u_src).zip(v_src).zip(rgb_chunks)
1264 {
1265 rgb_dst[0] = v_src;
1266 rgb_dst[1] = y_src;
1267 rgb_dst[2] = u_src;
1268 if CHANNELS == 4 {
1269 rgb_dst[3] = max_value.as_();
1270 }
1271 }
1272 }
1273 }
1274 }
1275
1276 Ok(())
1277 }