yuv 0.8.13

High performance utilities for YUV format handling and conversion.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/*
 * Copyright (c) Radzivon Bartoshyk, 10/2024. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1.  Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2.  Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3.  Neither the name of the copyright holder nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#![forbid(unsafe_code)]

use crate::built_coefficients::get_built_forward_transform;
use crate::sharpyuv::SharpYuvGammaTransfer;
use crate::yuv_error::check_rgba_destination;
use crate::yuv_support::*;
use crate::{YuvError, YuvPlanarImageMut};
#[cfg(feature = "rayon")]
use rayon::iter::{IndexedParallelIterator, ParallelIterator};
#[cfg(feature = "rayon")]
use rayon::prelude::{ParallelSlice, ParallelSliceMut};

fn sharpen_row420<const ORIGIN_CHANNELS: u8, const SAMPLING: u8, const PRECISION: i32>(
    y: usize,
    rgba: &[u8],
    y_plane: &mut [u8],
    u_plane: &mut [u8],
    v_plane: &mut [u8],
    rgb_layout: &[u16],
    rgb_layout_next_lane: &[u16],
    gamma_map_table: &[u8; u16::MAX as usize + 1],
    range: &YuvChromaRange,
    transform: &CbCrForwardTransform<i32>,
    width: usize,
) {
    let src_chans: YuvSourceChannels = ORIGIN_CHANNELS.into();
    let channels = src_chans.get_channels_count();

    let rounding_const_bias: i32 = (1 << (PRECISION - 1)) - 1;
    let bias_y = range.bias_y as i32 * (1 << PRECISION) + rounding_const_bias;
    let bias_uv = range.bias_uv as i32 * (1 << PRECISION) + rounding_const_bias;

    let i_bias_y = range.bias_y as i32;
    let i_cap_y = range.range_y as i32 + i_bias_y;
    let i_cap_uv = i_bias_y + range.range_uv as i32;

    let y_even_row = y & 1 == 0;

    for (((((y_dst, u_dst), v_dst), rgba), rgb_linearized), rgb_linearized_next) in y_plane
        .chunks_exact_mut(2)
        .zip(u_plane.iter_mut())
        .zip(v_plane.iter_mut())
        .zip(rgba.chunks_exact(channels * 2))
        .zip(rgb_layout.chunks_exact(2 * 3))
        .zip(rgb_layout_next_lane.chunks_exact(2 * 3))
    {
        let r0 = rgba[src_chans.get_r_channel_offset()] as i32;
        let g0 = rgba[src_chans.get_g_channel_offset()] as i32;
        let b0 = rgba[src_chans.get_b_channel_offset()] as i32;

        let y_0 = (r0 * transform.yr + g0 * transform.yg + b0 * transform.yb + bias_y) >> PRECISION;
        y_dst[0] = y_0.min(i_cap_y) as u8;

        let rgba_2 = &rgba[channels..channels * 2];

        let r1 = rgba_2[src_chans.get_r_channel_offset()] as i32;
        let g1 = rgba_2[src_chans.get_g_channel_offset()] as i32;
        let b1 = rgba_2[src_chans.get_b_channel_offset()] as i32;

        let y_1 = (r1 * transform.yr + g1 * transform.yg + b1 * transform.yb + bias_y) >> PRECISION;
        y_dst[1] = y_1.min(i_cap_y) as u8;

        if y_even_row {
            let sharp_r_c = rgb_linearized[src_chans.get_r_channel_offset()];
            let sharp_g_c = rgb_linearized[src_chans.get_g_channel_offset()];
            let sharp_b_c = rgb_linearized[src_chans.get_b_channel_offset()];

            let rgb_linearized_2 = &rgb_linearized[3..(3 + 3)];

            let sharp_r_next = rgb_linearized_2[src_chans.get_r_channel_offset()];
            let sharp_g_next = rgb_linearized_2[src_chans.get_g_channel_offset()];
            let sharp_b_next = rgb_linearized_2[src_chans.get_b_channel_offset()];

            let sharp_r_c_next_row = rgb_linearized_next[src_chans.get_r_channel_offset()];
            let sharp_g_c_next_row = rgb_linearized_next[src_chans.get_g_channel_offset()];
            let sharp_b_c_next_row = rgb_linearized_next[src_chans.get_b_channel_offset()];

            let rgb_linearized_next_2 = &rgb_linearized_next[3..(3 + 3)];

            let sharp_r_next_row = rgb_linearized_next_2[src_chans.get_r_channel_offset()];
            let sharp_g_next_row = rgb_linearized_next_2[src_chans.get_g_channel_offset()];
            let sharp_b_next_row = rgb_linearized_next_2[src_chans.get_b_channel_offset()];

            const ROUNDING_SHARP: i32 = 1 << 3;

            let interpolated_r = ((sharp_r_c as i32 * 9
                + sharp_r_next as i32 * 3
                + sharp_r_c_next_row as i32 * 3
                + sharp_r_next_row as i32
                + ROUNDING_SHARP)
                >> 4) as u16;
            let interpolated_g = ((sharp_g_c as i32 * 9
                + sharp_g_next as i32 * 3
                + sharp_g_c_next_row as i32 * 3
                + sharp_g_next_row as i32
                + ROUNDING_SHARP)
                >> 4) as u16;
            let interpolated_b = ((sharp_b_c as i32 * 9
                + sharp_b_next as i32 * 3
                + sharp_b_c_next_row as i32 * 3
                + sharp_b_next_row as i32
                + ROUNDING_SHARP)
                >> 4) as u16;

            let corrected_r = gamma_map_table[interpolated_r as usize] as i32;
            let corrected_g = gamma_map_table[interpolated_g as usize] as i32;
            let corrected_b = gamma_map_table[interpolated_b as usize] as i32;

            let cb = (corrected_r * transform.cb_r
                + corrected_g * transform.cb_g
                + corrected_b * transform.cb_b
                + bias_uv)
                >> PRECISION;
            let cr = (corrected_r * transform.cr_r
                + corrected_g * transform.cr_g
                + corrected_b * transform.cr_b
                + bias_uv)
                >> PRECISION;
            *u_dst = cb.max(i_bias_y).min(i_cap_uv) as u8;
            *v_dst = cr.max(i_bias_y).min(i_cap_uv) as u8;
        }
    }

    let rem_rgba = rgba.chunks_exact(channels * 2).remainder();

    if width & 1 != 0 && !rem_rgba.is_empty() {
        let rgba = &rem_rgba[0..3];
        let y_last = y_plane.last_mut().unwrap();
        let r0 = rgba[src_chans.get_r_channel_offset()] as i32;
        let g0 = rgba[src_chans.get_g_channel_offset()] as i32;
        let b0 = rgba[src_chans.get_b_channel_offset()] as i32;

        let y_1 = (r0 * transform.yr + g0 * transform.yg + b0 * transform.yb + bias_y) >> PRECISION;
        *y_last = y_1.min(i_cap_y) as u8;

        if y_even_row {
            let rgba_lin = rgb_layout.chunks_exact(3).last().unwrap();
            let rgba_lin = &rgba_lin[0..3];
            let sharp_r_c = rgba_lin[src_chans.get_r_channel_offset()];
            let sharp_g_c = rgba_lin[src_chans.get_g_channel_offset()];
            let sharp_b_c = rgba_lin[src_chans.get_b_channel_offset()];

            let rgba_lin_next = rgb_layout_next_lane.chunks_exact(3).last().unwrap();
            let rgba_lin_next = &rgba_lin_next[0..3];
            let sharp_r_c_next = rgba_lin_next[src_chans.get_r_channel_offset()];
            let sharp_g_c_next = rgba_lin_next[src_chans.get_g_channel_offset()];
            let sharp_b_c_next = rgba_lin_next[src_chans.get_b_channel_offset()];

            const ROUNDING_SHARP: i32 = 1 << 3;

            let interpolated_r =
                ((sharp_r_c as i32 * 12 + sharp_r_c_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;
            let interpolated_g =
                ((sharp_g_c as i32 * 12 + sharp_g_c_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;
            let interpolated_b =
                ((sharp_b_c as i32 * 12 + sharp_b_c_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;

            let corrected_r = gamma_map_table[interpolated_r as usize] as i32;
            let corrected_g = gamma_map_table[interpolated_g as usize] as i32;
            let corrected_b = gamma_map_table[interpolated_b as usize] as i32;

            let cb = (corrected_r * transform.cb_r
                + corrected_g * transform.cb_g
                + corrected_b * transform.cb_b
                + bias_uv)
                >> PRECISION;
            let cr = (corrected_r * transform.cr_r
                + corrected_g * transform.cr_g
                + corrected_b * transform.cr_b
                + bias_uv)
                >> PRECISION;
            let u_last = u_plane.last_mut().unwrap();
            let v_last = v_plane.last_mut().unwrap();
            *u_last = cb.max(i_bias_y).min(i_cap_uv) as u8;
            *v_last = cr.max(i_bias_y).min(i_cap_uv) as u8;
        }
    }
}

fn sharpen_row422<const ORIGIN_CHANNELS: u8, const SAMPLING: u8, const PRECISION: i32>(
    rgba: &[u8],
    y_plane: &mut [u8],
    u_plane: &mut [u8],
    v_plane: &mut [u8],
    rgb_layout: &[u16],
    gamma_map_table: &[u8; u16::MAX as usize + 1],
    range: &YuvChromaRange,
    transform: &CbCrForwardTransform<i32>,
    width: usize,
) {
    let src_chans: YuvSourceChannels = ORIGIN_CHANNELS.into();
    let channels = src_chans.get_channels_count();

    let rounding_const_bias: i32 = (1 << (PRECISION - 1)) - 1;
    let bias_y = range.bias_y as i32 * (1 << PRECISION) + rounding_const_bias;
    let bias_uv = range.bias_uv as i32 * (1 << PRECISION) + rounding_const_bias;

    let i_bias_y = range.bias_y as i32;
    let i_cap_y = range.range_y as i32 + i_bias_y;
    let i_cap_uv = i_bias_y + range.range_uv as i32;

    for ((((y_dst, u_dst), v_dst), rgba), rgb_linearized) in y_plane
        .chunks_exact_mut(2)
        .zip(u_plane.iter_mut())
        .zip(v_plane.iter_mut())
        .zip(rgba.chunks_exact(channels * 2))
        .zip(rgb_layout.chunks_exact(2 * 3))
    {
        let r0 = rgba[src_chans.get_r_channel_offset()] as i32;
        let g0 = rgba[src_chans.get_g_channel_offset()] as i32;
        let b0 = rgba[src_chans.get_b_channel_offset()] as i32;

        let sharp_r_c = rgb_linearized[src_chans.get_r_channel_offset()];
        let sharp_g_c = rgb_linearized[src_chans.get_g_channel_offset()];
        let sharp_b_c = rgb_linearized[src_chans.get_b_channel_offset()];

        let y_0 = (r0 * transform.yr + g0 * transform.yg + b0 * transform.yb + bias_y) >> PRECISION;
        y_dst[0] = y_0.min(i_cap_y) as u8;

        let rgba_2 = &rgba[channels..channels * 2];

        let r1 = rgba_2[src_chans.get_r_channel_offset()] as i32;
        let g1 = rgba_2[src_chans.get_g_channel_offset()] as i32;
        let b1 = rgba_2[src_chans.get_b_channel_offset()] as i32;

        let y_1 = (r1 * transform.yr + g1 * transform.yg + b1 * transform.yb + bias_y) >> PRECISION;
        y_dst[1] = y_1.min(i_cap_y) as u8;

        let rgb_linearized_2 = &rgb_linearized[3..(3 + 3)];

        let sharp_r_next = rgb_linearized_2[src_chans.get_r_channel_offset()];
        let sharp_g_next = rgb_linearized_2[src_chans.get_g_channel_offset()];
        let sharp_b_next = rgb_linearized_2[src_chans.get_b_channel_offset()];

        const ROUNDING_SHARP: i32 = 1 << 3;

        let interpolated_r =
            ((sharp_r_c as i32 * 12 + sharp_r_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;
        let interpolated_g =
            ((sharp_g_c as i32 * 12 + sharp_g_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;
        let interpolated_b =
            ((sharp_b_c as i32 * 12 + sharp_b_next as i32 * 4 + ROUNDING_SHARP) >> 4) as u16;

        let corrected_r = gamma_map_table[interpolated_r as usize] as i32;
        let corrected_g = gamma_map_table[interpolated_g as usize] as i32;
        let corrected_b = gamma_map_table[interpolated_b as usize] as i32;

        let cb = (corrected_r * transform.cb_r
            + corrected_g * transform.cb_g
            + corrected_b * transform.cb_b
            + bias_uv)
            >> PRECISION;
        let cr = (corrected_r * transform.cr_r
            + corrected_g * transform.cr_g
            + corrected_b * transform.cr_b
            + bias_uv)
            >> PRECISION;
        *u_dst = cb.max(i_bias_y).min(i_cap_uv) as u8;
        *v_dst = cr.max(i_bias_y).min(i_cap_uv) as u8;
    }

    let rem_rgba = rgba.chunks_exact(channels * 2).remainder();

    if width & 1 != 0 && !rem_rgba.is_empty() {
        let rgba = &rem_rgba[0..3];
        let y_last = y_plane.last_mut().unwrap();
        let r0 = rgba[src_chans.get_r_channel_offset()] as i32;
        let g0 = rgba[src_chans.get_g_channel_offset()] as i32;
        let b0 = rgba[src_chans.get_b_channel_offset()] as i32;

        let y_1 = (r0 * transform.yr + g0 * transform.yg + b0 * transform.yb + bias_y) >> PRECISION;
        *y_last = y_1.min(i_cap_y) as u8;

        let cb = (r0 * transform.cb_r + g0 * transform.cb_g + b0 * transform.cb_b + bias_uv)
            >> PRECISION;
        let cr = (r0 * transform.cr_r + g0 * transform.cr_g + b0 * transform.cr_b + bias_uv)
            >> PRECISION;

        let u_last = u_plane.last_mut().unwrap();
        let v_last = v_plane.last_mut().unwrap();
        *u_last = cb.max(i_bias_y).min(i_cap_uv) as u8;
        *v_last = cr.max(i_bias_y).min(i_cap_uv) as u8;
    }
}

fn rgbx_to_sharp_yuv<const ORIGIN_CHANNELS: u8, const SAMPLING: u8>(
    planar_image: &mut YuvPlanarImageMut<u8>,
    rgba: &[u8],
    rgba_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    sharp_yuv_gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    let chroma_subsampling: YuvChromaSubsampling = SAMPLING.into();
    let src_chans: YuvSourceChannels = ORIGIN_CHANNELS.into();

    check_rgba_destination(
        rgba,
        rgba_stride,
        planar_image.width,
        planar_image.height,
        src_chans.get_channels_count(),
    )?;
    planar_image.check_constraints(chroma_subsampling)?;

    let mut linear_map_table = [0u16; 256];
    let mut gamma_map_table = [0u8; u16::MAX as usize + 1];

    let linear_scale = (1. / 255.) as f32;
    let gamma_scale = 1. / u16::MAX as f32;

    for (i, item) in linear_map_table.iter_mut().enumerate() {
        let linear = sharp_yuv_gamma_transfer.linearize(i as f32 * linear_scale);
        *item = (linear * u16::MAX as f32) as u16;
    }

    for (i, item) in gamma_map_table.iter_mut().enumerate() {
        let gamma = sharp_yuv_gamma_transfer.gamma(i as f32 * gamma_scale);
        *item = (gamma * 255.) as u8;
    }

    // Always using 3 Channels ( RGB etc. ) layout since we do not need a alpha channel
    let mut rgb_layout: Vec<u16> =
        vec![0u16; planar_image.width as usize * planar_image.height as usize * 3];

    let rgb_layout_stride_len = planar_image.width as usize * 3;

    let iter_linearize;
    #[cfg(not(feature = "rayon"))]
    {
        iter_linearize = rgb_layout
            .chunks_exact_mut(rgb_layout_stride_len)
            .zip(rgba.chunks_exact(rgba_stride as usize));
    }
    #[cfg(feature = "rayon")]
    {
        iter_linearize = rgb_layout
            .par_chunks_exact_mut(rgb_layout_stride_len)
            .zip(rgba.par_chunks_exact(rgba_stride as usize));
    }

    iter_linearize.for_each(|(rgb_layout_cast, src_layout)| {
        for (dst, src) in rgb_layout_cast
            .chunks_exact_mut(3)
            .zip(src_layout.chunks_exact(src_chans.get_channels_count()))
        {
            dst[0] = linear_map_table[src[0] as usize];
            dst[1] = linear_map_table[src[1] as usize];
            dst[2] = linear_map_table[src[2] as usize];
        }
    });

    let chroma_range = get_yuv_range(8, range);
    let kr_kb = matrix.get_kr_kb();
    let max_range_p8 = (1u32 << 8u32) - 1u32;
    const PRECISION: i32 = 13;
    let transform =
        if let Some(stored_t) = get_built_forward_transform(PRECISION as u32, 8, range, matrix) {
            stored_t
        } else {
            let transform_precise = get_forward_transform(
                max_range_p8,
                chroma_range.range_y,
                chroma_range.range_uv,
                kr_kb.kr,
                kr_kb.kb,
            );
            transform_precise.to_integers(PRECISION as u32)
        };

    let y_iter;
    let u_iter;
    let v_iter;
    let rgb_iter;

    if chroma_subsampling == YuvChromaSubsampling::Yuv420 {
        #[cfg(feature = "rayon")]
        {
            y_iter = planar_image
                .y_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.y_stride as usize * 2);
            u_iter = planar_image
                .u_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.u_stride as usize);
            v_iter = planar_image
                .v_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.v_stride as usize);
            rgb_iter = rgba.par_chunks_exact(rgba_stride as usize * 2);
        }
        #[cfg(not(feature = "rayon"))]
        {
            y_iter = planar_image
                .y_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.y_stride as usize * 2);
            u_iter = planar_image
                .u_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.u_stride as usize);
            v_iter = planar_image
                .v_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.v_stride as usize);
            rgb_iter = rgba.chunks_exact(rgba_stride as usize * 2);
        }
    } else {
        #[cfg(feature = "rayon")]
        {
            y_iter = planar_image
                .y_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.y_stride as usize);
            u_iter = planar_image
                .u_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.u_stride as usize);
            v_iter = planar_image
                .v_plane
                .borrow_mut()
                .par_chunks_exact_mut(planar_image.v_stride as usize);
            rgb_iter = rgba.par_chunks_exact(rgba_stride as usize);
        }
        #[cfg(not(feature = "rayon"))]
        {
            y_iter = planar_image
                .y_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.y_stride as usize);
            u_iter = planar_image
                .u_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.u_stride as usize);
            v_iter = planar_image
                .v_plane
                .borrow_mut()
                .chunks_exact_mut(planar_image.v_stride as usize);
            rgb_iter = rgba.chunks_exact(rgba_stride as usize);
        }
    }

    let full_iter = rgb_iter.zip(y_iter).zip(u_iter).zip(v_iter);

    full_iter
        .enumerate()
        .for_each(|(j, (((rgba, y_plane), u_plane), v_plane))| {
            if chroma_subsampling == YuvChromaSubsampling::Yuv420 {
                let v_y = j * 2;

                for (virtual_y, (y_plane, rgba)) in y_plane
                    .chunks_exact_mut(planar_image.y_stride as usize)
                    .zip(rgba.chunks_exact(rgba_stride as usize))
                    .enumerate()
                {
                    let y = virtual_y + v_y;
                    let rgb_layout_start = y * rgb_layout_stride_len;
                    let rgb_layout_start_next = (y + 1) * rgb_layout_stride_len;
                    let rgb_layout_lane = &rgb_layout
                        [rgb_layout_start..((planar_image.width as usize) * 3 + rgb_layout_start)];
                    let rgb_layout_next_lane = if y + 1 < planar_image.height as usize {
                        &rgb_layout[rgb_layout_start_next
                            ..((planar_image.width as usize) * 3 + rgb_layout_start_next)]
                    } else {
                        rgb_layout_lane
                    };
                    sharpen_row420::<ORIGIN_CHANNELS, SAMPLING, PRECISION>(
                        y,
                        &rgba[..planar_image.width as usize * src_chans.get_channels_count()],
                        &mut y_plane[..planar_image.width as usize],
                        &mut u_plane[..(planar_image.width as usize).div_ceil(2)],
                        &mut v_plane[..(planar_image.width as usize).div_ceil(2)],
                        rgb_layout_lane,
                        rgb_layout_next_lane,
                        &gamma_map_table,
                        &chroma_range,
                        &transform,
                        planar_image.width as usize,
                    );
                }
            } else {
                let y = j;
                let rgb_layout_start = y * rgb_layout_stride_len;
                let rgb_layout_lane = &rgb_layout
                    [rgb_layout_start..((planar_image.width as usize) * 3 + rgb_layout_start)];
                sharpen_row422::<ORIGIN_CHANNELS, SAMPLING, PRECISION>(
                    &rgba[..planar_image.width as usize * src_chans.get_channels_count()],
                    &mut y_plane[..planar_image.width as usize],
                    &mut u_plane[..(planar_image.width as usize).div_ceil(2)],
                    &mut v_plane[..(planar_image.width as usize).div_ceil(2)],
                    rgb_layout_lane,
                    &gamma_map_table,
                    &chroma_range,
                    &transform,
                    planar_image.width as usize,
                );
            }
        });

    // Handle last row if image is odd
    if planar_image.height & 1 != 0 && chroma_subsampling == YuvChromaSubsampling::Yuv420 {
        let y_iter = planar_image
            .y_plane
            .borrow_mut()
            .chunks_exact_mut(planar_image.y_stride as usize)
            .rev()
            .take(1);
        let u_iter = planar_image
            .u_plane
            .borrow_mut()
            .chunks_exact_mut(planar_image.u_stride as usize)
            .rev()
            .take(1);
        let v_iter = planar_image
            .v_plane
            .borrow_mut()
            .chunks_exact_mut(planar_image.v_stride as usize)
            .rev()
            .take(1);
        let rgb_iter = rgba.chunks_exact(rgba_stride as usize).rev().take(1);
        let rgb_linearized_iter = rgb_layout
            .chunks_exact_mut(rgb_layout_stride_len)
            .rev()
            .take(1);

        let full_iter = rgb_iter
            .zip(rgb_linearized_iter)
            .zip(y_iter)
            .zip(u_iter)
            .zip(v_iter);

        full_iter.for_each(|((((rgba, rgb_layout), y_plane), u_plane), v_plane)| {
            let y = planar_image.height as usize - 1;
            let rgb_layout_lane: &[u16] = rgb_layout;
            let rgb_layout_next_lane: &[u16] = rgb_layout;
            sharpen_row420::<ORIGIN_CHANNELS, SAMPLING, PRECISION>(
                y,
                &rgba[..planar_image.width as usize * src_chans.get_channels_count()],
                &mut y_plane[..planar_image.width as usize],
                &mut u_plane[..(planar_image.width as usize).div_ceil(2)],
                &mut v_plane[..(planar_image.width as usize).div_ceil(2)],
                rgb_layout_lane,
                rgb_layout_next_lane,
                &gamma_map_table,
                &chroma_range,
                &transform,
                planar_image.width as usize,
            );
        });
    }

    Ok(())
}

/// Convert RGB image data to YUV 422 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs RGB to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV422 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `rgb` - The input RGB image data slice.
/// * `rgb_stride` - The stride (components per row) for the RGB image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input RGB data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn rgb_to_sharp_yuv422(
    planar_image: &mut YuvPlanarImageMut<u8>,
    rgb: &[u8],
    rgb_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Rgb as u8 }, { YuvChromaSubsampling::Yuv422 as u8 }>(
        planar_image,
        rgb,
        rgb_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert BGR image data to YUV 422 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs BGR to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV422 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `bgr` - The input BGR image data slice.
/// * `bgr_stride` - The stride (components per row) for the BGR image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input BGR data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn bgr_to_sharp_yuv422(
    planar_image: &mut YuvPlanarImageMut<u8>,
    bgr: &[u8],
    bgr_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Bgr as u8 }, { YuvChromaSubsampling::Yuv422 as u8 }>(
        planar_image,
        bgr,
        bgr_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert RGBA image data to YUV 422 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs RGBA to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV422 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `rgba` - The input RGBA image data slice.
/// * `rgba_stride` - The stride (components per row) for the RGBA image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input RGBA data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn rgba_to_sharp_yuv422(
    planar_image: &mut YuvPlanarImageMut<u8>,
    rgba: &[u8],
    rgba_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Rgba as u8 }, { YuvChromaSubsampling::Yuv422 as u8 }>(
        planar_image,
        rgba,
        rgba_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert BGRA image data to YUV 422 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs BGRA to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV422 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `bgra` - The input BGRA image data slice.
/// * `bgra_stride` - The stride (components per row) for the BGRA image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input BGRA data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn bgra_to_sharp_yuv422(
    planar_image: &mut YuvPlanarImageMut<u8>,
    bgra: &[u8],
    bgra_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Bgra as u8 }, { YuvChromaSubsampling::Yuv422 as u8 }>(
        planar_image,
        bgra,
        bgra_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert RGB image data to YUV 420 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs RGB to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV420 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `y_plane` - A mutable slice to store the Y (luminance) plane data.
/// * `y_stride` - The stride (components per row) for the Y plane.
/// * `u_plane` - A mutable slice to store the U (chrominance) plane data.
/// * `u_stride` - The stride (components per row) for the U plane.
/// * `v_plane` - A mutable slice to store the V (chrominance) plane data.
/// * `v_stride` - The stride (components per row) for the V plane.
/// * `rgb` - The input RGB image data slice.
/// * `rgb_stride` - The stride (components per row) for the RGB image data.
/// * `width` - The width of the image in pixels.
/// * `height` - The height of the image in pixels.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input RGB data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn rgb_to_sharp_yuv420(
    planar_image: &mut YuvPlanarImageMut<u8>,
    rgb: &[u8],
    rgb_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Rgb as u8 }, { YuvChromaSubsampling::Yuv420 as u8 }>(
        planar_image,
        rgb,
        rgb_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert BGR image data to YUV 420 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs BGR to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV420 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `bgr` - The input BGR image data slice.
/// * `bgr_stride` - The stride (components per row) for the BGR image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input RGB data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn bgr_to_sharp_yuv420(
    planar_image: &mut YuvPlanarImageMut<u8>,
    bgr: &[u8],
    bgr_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Bgr as u8 }, { YuvChromaSubsampling::Yuv420 as u8 }>(
        planar_image,
        bgr,
        bgr_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert RGBA image data to YUV 420 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs RGBA to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV420 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `rgba` - The input RGBA image data slice.
/// * `rgba_stride` - The stride (components per row) for the RGBA image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input RGBA data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn rgba_to_sharp_yuv420(
    planar_image: &mut YuvPlanarImageMut<u8>,
    rgba: &[u8],
    rgba_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Rgba as u8 }, { YuvChromaSubsampling::Yuv420 as u8 }>(
        planar_image,
        rgba,
        rgba_stride,
        range,
        matrix,
        gamma_transfer,
    )
}

/// Convert BGRA image data to YUV 420 planar format using bi-linear interpolation and gamma correction ( sharp YUV algorithm ).
///
/// This function performs BGRA to YUV conversion using bi-linear interpolation and gamma correction and stores the result in YUV420 planar format using bi-linear interpolation and gamma correction,
/// with separate planes for Y (luminance), U (chrominance), and V (chrominance) components.
///
/// # Arguments
///
/// * `planar_image` - Target planar image.
/// * `bgra` - The input BGRA image data slice.
/// * `bgra_stride` - The stride (components per row) for the BGRA image data.
/// * `range` - The YUV range (limited or full).
/// * `matrix` - The YUV standard matrix (BT.601 or BT.709 or BT.2020 or other).
///
/// # Panics
///
/// This function panics if the lengths of the planes or the input BGRA data are not valid based
/// on the specified width, height, and strides, or if invalid YUV range or matrix is provided.
///
pub fn bgra_to_sharp_yuv420(
    planar_image: &mut YuvPlanarImageMut<u8>,
    bgra: &[u8],
    bgra_stride: u32,
    range: YuvRange,
    matrix: YuvStandardMatrix,
    gamma_transfer: SharpYuvGammaTransfer,
) -> Result<(), YuvError> {
    rgbx_to_sharp_yuv::<{ YuvSourceChannels::Bgra as u8 }, { YuvChromaSubsampling::Yuv420 as u8 }>(
        planar_image,
        bgra,
        bgra_stride,
        range,
        matrix,
        gamma_transfer,
    )
}