yscv-video 0.1.8

Video decoding (H.264, HEVC), MP4 parsing, and camera I/O
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
//! H.264 YUV-to-RGB conversion, deinterlacing, and FMO helpers.

use super::h264_params::{Pps, Sps};
use crate::VideoError;

// ---------------------------------------------------------------------------
// Interlaced (MBAFF/PAFF) field-pair deinterlacing
// ---------------------------------------------------------------------------

/// Deinterlaces a field pair by interleaving top-field and bottom-field rows.
///
/// `top_field` and `bottom_field` each contain `height` rows of `width * 3` bytes
/// (RGB8). The output frame has `height * 2` rows where even rows come from the
/// top field and odd rows come from the bottom field.
pub fn deinterlace_fields(
    top_field: &[u8],
    bottom_field: &[u8],
    width: usize,
    height: usize,
) -> Vec<u8> {
    let row_bytes = width * 3; // RGB
    let mut frame = vec![0u8; height * 2 * row_bytes];
    for y in 0..height {
        // Even rows from top field
        let dst_even_start = y * 2 * row_bytes;
        let src_top_start = y * row_bytes;
        if src_top_start + row_bytes <= top_field.len() && dst_even_start + row_bytes <= frame.len()
        {
            frame[dst_even_start..dst_even_start + row_bytes]
                .copy_from_slice(&top_field[src_top_start..src_top_start + row_bytes]);
        }
        // Odd rows from bottom field
        let dst_odd_start = (y * 2 + 1) * row_bytes;
        let src_bot_start = y * row_bytes;
        if src_bot_start + row_bytes <= bottom_field.len()
            && dst_odd_start + row_bytes <= frame.len()
        {
            frame[dst_odd_start..dst_odd_start + row_bytes]
                .copy_from_slice(&bottom_field[src_bot_start..src_bot_start + row_bytes]);
        }
    }
    frame
}

// ---------------------------------------------------------------------------
// FMO (Flexible Macroblock Ordering) — slice group map generation
// ---------------------------------------------------------------------------

/// Generates the macroblock-to-slice-group mapping for FMO.
///
/// When `num_slice_groups <= 1`, all MBs belong to group 0 (raster scan order,
/// the default non-FMO case). Otherwise the mapping is determined by
/// `slice_group_map_type` (0–6) as specified in ITU-T H.264 section 8.2.2.
pub fn generate_slice_group_map(pps: &Pps, sps: &Sps) -> Vec<u8> {
    let pic_width = sps.pic_width_in_mbs as usize;
    let pic_height = sps.pic_height_in_map_units as usize;
    let num_mbs = pic_width * pic_height;
    let mut map = vec![0u8; num_mbs];

    if pps.num_slice_groups <= 1 {
        return map; // all MBs in group 0
    }

    let num_groups = pps.num_slice_groups as usize;

    match pps.slice_group_map_type {
        0 => {
            // Interleaved: run_length based cyclic assignment
            let mut i = 0;
            loop {
                if i >= num_mbs {
                    break;
                }
                for group in 0..num_groups {
                    let run = if group < pps.run_length_minus1.len() {
                        pps.run_length_minus1[group] as usize + 1
                    } else {
                        1
                    };
                    for _ in 0..run {
                        if i >= num_mbs {
                            break;
                        }
                        map[i] = group as u8;
                        i += 1;
                    }
                }
            }
        }
        1 => {
            // Dispersed: modular mapping
            for i in 0..num_mbs {
                let x = i % pic_width;
                let y = i / pic_width;
                let group = ((x + ((y * num_groups) / 2)) % num_groups) as u8;
                map[i] = group;
            }
        }
        2 => {
            // Foreground with left-over: rectangular regions
            // Initially all MBs in the last group (background)
            let bg_group = (num_groups - 1) as u8;
            for m in map.iter_mut() {
                *m = bg_group;
            }
            // Assign foreground regions (highest group index has priority)
            for group in (0..num_groups.saturating_sub(1)).rev() {
                if group >= pps.top_left.len() || group >= pps.bottom_right.len() {
                    continue;
                }
                let tl = pps.top_left[group] as usize;
                let br = pps.bottom_right[group] as usize;
                let tl_x = tl % pic_width;
                let tl_y = tl / pic_width;
                let br_x = br % pic_width;
                let br_y = br / pic_width;
                for y in tl_y..=br_y.min(pic_height.saturating_sub(1)) {
                    for x in tl_x..=br_x.min(pic_width.saturating_sub(1)) {
                        let idx = y * pic_width + x;
                        if idx < num_mbs {
                            map[idx] = group as u8;
                        }
                    }
                }
            }
        }
        3..=5 => {
            // Box-out / raster-scan / wipe: evolving slice groups
            // These types use slice_group_change_rate to determine a moving
            // boundary. For a single-frame decode the boundary position comes
            // from `slice_group_change_cycle` in the slice header. As a
            // simplification we map the first `change_rate` MBs to group 0
            // and the rest to group 1.
            let change = (pps.slice_group_change_rate as usize).min(num_mbs);
            for (i, m) in map.iter_mut().enumerate() {
                *m = if i < change { 0 } else { 1 };
            }
        }
        6 => {
            // Explicit: per-MB group IDs stored in PPS
            for (i, m) in map.iter_mut().enumerate() {
                if i < pps.slice_group_id.len() {
                    *m = pps.slice_group_id[i] as u8;
                }
            }
        }
        _ => {
            // Unknown type — fall back to single group
        }
    }

    map
}

// ---------------------------------------------------------------------------
// Chroma format helpers (High 4:2:2 / 4:4:4 profile support)
// ---------------------------------------------------------------------------

/// Returns the chroma plane dimensions `(chroma_width, chroma_height)` given
/// the luma dimensions and `chroma_format_idc` from the SPS.
///
/// - 0 = monochrome (no chroma planes)
/// - 1 = YUV 4:2:0 (default, half width and half height)
/// - 2 = YUV 4:2:2 (half width, full height)
/// - 3 = YUV 4:4:4 (full width, full height)
pub fn chroma_dimensions(width: usize, height: usize, chroma_format: u32) -> (usize, usize) {
    match chroma_format {
        0 => (0, 0),                  // monochrome
        1 => (width / 2, height / 2), // 4:2:0
        2 => (width / 2, height),     // 4:2:2
        3 => (width, height),         // 4:4:4
        _ => (width / 2, height / 2), // default to 4:2:0
    }
}

/// Converts YUV 4:2:2 planar to RGB8 interleaved using BT.601 coefficients.
///
/// Chroma planes are half-width, full-height relative to luma.
pub fn yuv422_to_rgb8(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    width: usize,
    height: usize,
) -> Result<Vec<u8>, VideoError> {
    let expected_y = width * height;
    let expected_uv = (width / 2) * height;

    if y_plane.len() < expected_y {
        return Err(VideoError::Codec(format!(
            "Y plane too small: expected {expected_y}, got {}",
            y_plane.len()
        )));
    }
    if u_plane.len() < expected_uv || v_plane.len() < expected_uv {
        return Err(VideoError::Codec(format!(
            "UV planes too small for 4:2:2: expected {expected_uv}, got U={} V={}",
            u_plane.len(),
            v_plane.len()
        )));
    }

    let mut rgb = vec![0u8; width * height * 3];
    let uv_stride = width / 2;

    for row in 0..height {
        let y_off = row * width;
        let uv_off = row * uv_stride;

        for col in 0..width {
            let y_val = y_plane[y_off + col] as i16;
            let u_val = u_plane[uv_off + col / 2] as i16 - 128;
            let v_val = v_plane[uv_off + col / 2] as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = (row * width + col) * 3;
            rgb[idx] = r.clamp(0, 255) as u8;
            rgb[idx + 1] = g.clamp(0, 255) as u8;
            rgb[idx + 2] = b.clamp(0, 255) as u8;
        }
    }

    Ok(rgb)
}

/// Converts YUV 4:4:4 planar to RGB8 interleaved using BT.601 coefficients.
///
/// All three planes have the same dimensions (no chroma subsampling).
pub fn yuv444_to_rgb8(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    width: usize,
    height: usize,
) -> Result<Vec<u8>, VideoError> {
    let expected = width * height;

    if y_plane.len() < expected {
        return Err(VideoError::Codec(format!(
            "Y plane too small: expected {expected}, got {}",
            y_plane.len()
        )));
    }
    if u_plane.len() < expected || v_plane.len() < expected {
        return Err(VideoError::Codec(format!(
            "UV planes too small for 4:4:4: expected {expected}, got U={} V={}",
            u_plane.len(),
            v_plane.len()
        )));
    }

    let mut rgb = vec![0u8; width * height * 3];

    for i in 0..expected {
        let y_val = y_plane[i] as i16;
        let u_val = u_plane[i] as i16 - 128;
        let v_val = v_plane[i] as i16 - 128;

        let r = y_val + ((v_val * 179) >> 7);
        let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
        let b = y_val + ((u_val * 227) >> 7);

        let idx = i * 3;
        rgb[idx] = r.clamp(0, 255) as u8;
        rgb[idx + 1] = g.clamp(0, 255) as u8;
        rgb[idx + 2] = b.clamp(0, 255) as u8;
    }

    Ok(rgb)
}

/// Converts a monochrome (luma-only) plane to RGB8 (grayscale).
pub fn mono_to_rgb8(y_plane: &[u8], width: usize, height: usize) -> Result<Vec<u8>, VideoError> {
    let expected = width * height;
    if y_plane.len() < expected {
        return Err(VideoError::Codec(format!(
            "Y plane too small: expected {expected}, got {}",
            y_plane.len()
        )));
    }
    let mut rgb = vec![0u8; expected * 3];
    for i in 0..expected {
        let v = y_plane[i];
        let idx = i * 3;
        rgb[idx] = v;
        rgb[idx + 1] = v;
        rgb[idx + 2] = v;
    }
    Ok(rgb)
}

/// Dispatches YUV-to-RGB conversion based on `chroma_format_idc`.
pub(crate) fn yuv_to_rgb8_by_format(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    width: usize,
    height: usize,
    chroma_format_idc: u32,
) -> Result<Vec<u8>, VideoError> {
    match chroma_format_idc {
        0 => mono_to_rgb8(y_plane, width, height),
        1 => yuv420_to_rgb8(y_plane, u_plane, v_plane, width, height),
        2 => yuv422_to_rgb8(y_plane, u_plane, v_plane, width, height),
        3 => yuv444_to_rgb8(y_plane, u_plane, v_plane, width, height),
        _ => yuv420_to_rgb8(y_plane, u_plane, v_plane, width, height),
    }
}

// ---------------------------------------------------------------------------
// Generic YUV to RGB for non-4:2:0 chroma formats
// ---------------------------------------------------------------------------

/// Converts planar YUV to RGB8 for arbitrary chroma subsampling ratios.
///
/// `sub_w` and `sub_h` give the horizontal and vertical chroma subsampling
/// factors (e.g. `sub_w=2, sub_h=2` for 4:2:0, `sub_w=2, sub_h=1` for 4:2:2,
/// `sub_w=1, sub_h=1` for 4:4:4). Uses BT.601 fixed-point conversion.
pub fn yuv_to_rgb8_generic(
    y: &[u8],
    u: &[u8],
    v: &[u8],
    w: usize,
    h: usize,
    sub_w: usize,
    sub_h: usize,
) -> Vec<u8> {
    let sub_w = sub_w.max(1);
    let sub_h = sub_h.max(1);
    let uv_stride = w / sub_w;
    let mut rgb = vec![0u8; w * h * 3];
    for row in 0..h {
        let y_off = row * w;
        let uv_row = (row / sub_h) * uv_stride;
        for col in 0..w {
            let y_val = y.get(y_off + col).copied().unwrap_or(128) as i16;
            let u_val = u.get(uv_row + col / sub_w).copied().unwrap_or(128) as i16 - 128;
            let v_val = v.get(uv_row + col / sub_w).copied().unwrap_or(128) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = (row * w + col) * 3;
            rgb[idx] = r.clamp(0, 255) as u8;
            rgb[idx + 1] = g.clamp(0, 255) as u8;
            rgb[idx + 2] = b.clamp(0, 255) as u8;
        }
    }
    rgb
}

// ---------------------------------------------------------------------------
// HDR 10-bit YUV420 to RGB16 conversion
// ---------------------------------------------------------------------------

/// Converts 10/12-bit YUV 4:2:0 planar (u16 samples) to RGB16 interleaved
/// using BT.709 fixed-point conversion.
///
/// Output values are scaled to fill the full 16-bit range.
/// Chroma planes are `(w/2) x (h/2)` samples. Returns `3 * w * h` u16 values.
pub fn yuv420_p16_to_rgb16(
    y: &[u16],
    u: &[u16],
    v: &[u16],
    w: usize,
    h: usize,
    bit_depth: u8,
) -> Result<Vec<u16>, VideoError> {
    let expected_y = w * h;
    let expected_uv = (w / 2) * (h / 2);
    if y.len() < expected_y {
        return Err(VideoError::Codec(format!(
            "Y16 plane too small: expected {expected_y}, got {}",
            y.len()
        )));
    }
    if u.len() < expected_uv || v.len() < expected_uv {
        return Err(VideoError::Codec(format!(
            "UV16 planes too small: expected {expected_uv}, got U={} V={}",
            u.len(),
            v.len()
        )));
    }

    let max_in = (1i32 << bit_depth) - 1;
    // Scale factor to expand input range to u16: 65535 / max_in
    let upshift = 16u32.saturating_sub(bit_depth as u32);
    let uv_stride = w / 2;
    let mid = 1i32 << (bit_depth - 1);

    let mut rgb = vec![0u16; w * h * 3];
    for row in 0..h {
        let y_off = row * w;
        let uv_off = (row / 2) * uv_stride;
        for col in 0..w {
            let y_val = y[y_off + col] as i32;
            let u_val = u[uv_off + col / 2] as i32 - mid;
            let v_val = v[uv_off + col / 2] as i32 - mid;

            // BT.709: R = Y + 1.5748*V, G = Y - 0.1873*U - 0.4681*V, B = Y + 1.8556*U
            // Fixed-point Q10: 1.5748*1024=1613, 0.1873*1024=192, 0.4681*1024=479, 1.8556*1024=1901
            let r = y_val + ((v_val * 1613) >> 10);
            let g = y_val - ((u_val * 192 + v_val * 479) >> 10);
            let b = y_val + ((u_val * 1901) >> 10);

            let idx = (row * w + col) * 3;
            rgb[idx] = (r.clamp(0, max_in) as u32).wrapping_shl(upshift) as u16;
            rgb[idx + 1] = (g.clamp(0, max_in) as u32).wrapping_shl(upshift) as u16;
            rgb[idx + 2] = (b.clamp(0, max_in) as u32).wrapping_shl(upshift) as u16;
        }
    }
    Ok(rgb)
}

// ---------------------------------------------------------------------------
// YUV to RGB conversion
// ---------------------------------------------------------------------------

/// Converts YUV 4:2:0 planar to RGB8 interleaved using BT.601 coefficients.
///
/// Input: separate Y, U, V planes. Y is `width * height`, U and V are `(width/2) * (height/2)`.
/// Output: RGB8 interleaved, `width * height * 3` bytes.
///
/// Uses SIMD (NEON on aarch64, SSE2 on x86_64) with fixed-point i16 arithmetic
/// and multi-threaded row processing for high throughput.
#[allow(unsafe_code)]
pub fn yuv420_to_rgb8(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    width: usize,
    height: usize,
) -> Result<Vec<u8>, VideoError> {
    let expected_y = width * height;
    let expected_uv = (width / 2) * (height / 2);

    if y_plane.len() < expected_y {
        return Err(VideoError::Codec(format!(
            "Y plane too small: expected {expected_y}, got {}",
            y_plane.len()
        )));
    }
    if u_plane.len() < expected_uv || v_plane.len() < expected_uv {
        return Err(VideoError::Codec(format!(
            "UV planes too small: expected {expected_uv}, got U={} V={}",
            u_plane.len(),
            v_plane.len()
        )));
    }

    let mut rgb = vec![0u8; width * height * 3];
    let uv_stride = width / 2;

    if height < 4 {
        // Single-threaded path for very small images.
        yuv420_to_rgb8_rows(
            y_plane, u_plane, v_plane, &mut rgb, width, uv_stride, 0, height,
        );
    } else {
        // Use rayon par_chunks_mut for near-zero thread dispatch overhead
        // (rayon reuses a warm thread pool vs std::thread::scope which spawns
        // new threads each call).
        use rayon::prelude::*;

        let row_bytes = width * 3;
        rgb.par_chunks_mut(row_bytes)
            .enumerate()
            .for_each(|(row_idx, row_slice)| {
                yuv420_to_rgb8_rows(
                    y_plane,
                    u_plane,
                    v_plane,
                    row_slice,
                    width,
                    uv_stride,
                    row_idx,
                    row_idx + 1,
                );
            });
    }

    Ok(rgb)
}

/// Like [`yuv420_to_rgb8`] but writes into a caller-supplied buffer,
/// avoiding per-frame allocation. `rgb_out` must be at least `width * height * 3` bytes.
pub fn yuv420_to_rgb8_into(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    width: usize,
    height: usize,
    rgb_out: &mut Vec<u8>,
) -> Result<(), VideoError> {
    let expected_y = width * height;
    let expected_uv = (width / 2) * (height / 2);

    if y_plane.len() < expected_y {
        return Err(VideoError::Codec(format!(
            "Y plane too small: expected {expected_y}, got {}",
            y_plane.len()
        )));
    }
    if u_plane.len() < expected_uv || v_plane.len() < expected_uv {
        return Err(VideoError::Codec(format!(
            "UV planes too small: expected {expected_uv}, got U={} V={}",
            u_plane.len(),
            v_plane.len()
        )));
    }

    let total = width * height * 3;
    rgb_out.resize(total, 0);
    let uv_stride = width / 2;

    if height < 4 {
        yuv420_to_rgb8_rows(
            y_plane, u_plane, v_plane, rgb_out, width, uv_stride, 0, height,
        );
    } else {
        use rayon::prelude::*;
        let row_bytes = width * 3;
        rgb_out
            .par_chunks_mut(row_bytes)
            .enumerate()
            .for_each(|(row_idx, row_slice)| {
                yuv420_to_rgb8_rows(
                    y_plane,
                    u_plane,
                    v_plane,
                    row_slice,
                    width,
                    uv_stride,
                    row_idx,
                    row_idx + 1,
                );
            });
    }

    Ok(())
}

/// Convert rows `start_row..end_row` from YUV420 to RGB8.
/// `rgb_out` starts at the byte corresponding to `start_row`.
#[inline]
#[allow(unsafe_code)]
fn yuv420_to_rgb8_rows(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    rgb_out: &mut [u8],
    width: usize,
    uv_stride: usize,
    start_row: usize,
    end_row: usize,
) {
    #[cfg(target_arch = "aarch64")]
    {
        if std::arch::is_aarch64_feature_detected!("neon") {
            // SAFETY: feature detected at runtime.
            unsafe {
                yuv420_to_rgb8_rows_neon(
                    y_plane, u_plane, v_plane, rgb_out, width, uv_stride, start_row, end_row,
                );
            }
            return;
        }
    }

    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            unsafe {
                yuv420_to_rgb8_rows_avx2(
                    y_plane, u_plane, v_plane, rgb_out, width, uv_stride, start_row, end_row,
                );
            }
            return;
        }
        if is_x86_feature_detected!("sse2") {
            unsafe {
                yuv420_to_rgb8_rows_sse2(
                    y_plane, u_plane, v_plane, rgb_out, width, uv_stride, start_row, end_row,
                );
            }
            return;
        }
    }

    yuv420_to_rgb8_rows_scalar(
        y_plane, u_plane, v_plane, rgb_out, width, uv_stride, start_row, end_row,
    );
}

/// Scalar fallback for YUV420→RGB8 conversion.
#[inline]
fn yuv420_to_rgb8_rows_scalar(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    rgb_out: &mut [u8],
    width: usize,
    uv_stride: usize,
    start_row: usize,
    end_row: usize,
) {
    // BT.601 fixed-point constants (Q7, fits in i16 without overflow):
    // 1.402 * 128 ≈ 179, 0.344 * 128 ≈ 44, 0.714 * 128 ≈ 91, 1.772 * 128 ≈ 227
    // R = Y + (V-128)*179 >> 7
    // G = Y - ((U-128)*44 + (V-128)*91) >> 7
    // B = Y + (U-128)*227 >> 7
    for row in start_row..end_row {
        let out_row = row - start_row;
        let y_row_off = row * width;
        let uv_row_off = (row / 2) * uv_stride;

        for col in 0..width {
            let y_val = y_plane[y_row_off + col] as i16;
            let u_val = u_plane[uv_row_off + col / 2] as i16 - 128;
            let v_val = v_plane[uv_row_off + col / 2] as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = (out_row * width + col) * 3;
            rgb_out[idx] = r.clamp(0, 255) as u8;
            rgb_out[idx + 1] = g.clamp(0, 255) as u8;
            rgb_out[idx + 2] = b.clamp(0, 255) as u8;
        }
    }
}

/// NEON-accelerated YUV420→RGB8 conversion (aarch64).
/// Processes 8 pixels per iteration using i16 fixed-point arithmetic.
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn yuv420_to_rgb8_rows_neon(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    rgb_out: &mut [u8],
    width: usize,
    uv_stride: usize,
    start_row: usize,
    end_row: usize,
) {
    use std::arch::aarch64::*;

    // BT.601 fixed-point Q7 constants (fit in i16 without overflow)
    let c_179 = vdupq_n_s16(179); // 1.402 * 128
    let c_44 = vdupq_n_s16(44); // 0.344 * 128
    let c_91 = vdupq_n_s16(91); // 0.714 * 128
    let c_227 = vdupq_n_s16(227); // 1.772 * 128
    let c_128 = vdupq_n_s16(128);

    for row in start_row..end_row {
        let out_row = row - start_row;
        let y_row_ptr = y_plane.as_ptr().add(row * width);
        let uv_row = (row / 2) * uv_stride;
        let u_row_ptr = u_plane.as_ptr().add(uv_row);
        let v_row_ptr = v_plane.as_ptr().add(uv_row);
        let rgb_row_ptr = rgb_out.as_mut_ptr().add(out_row * width * 3);

        let mut col = 0usize;

        // Process 16 pixels per iteration (16 Y, 8 U, 8 V)
        while col + 16 <= width {
            // Load 16 Y values
            let y16 = vld1q_u8(y_row_ptr.add(col));
            // Load 8 U and 8 V values, each covers 16 horizontal pixels
            let u8_vals = vld1_u8(u_row_ptr.add(col / 2));
            let v8_vals = vld1_u8(v_row_ptr.add(col / 2));

            // Duplicate each U/V to cover 2 pixels horizontally → 16 values
            let u16_dup = vcombine_u8(vzip1_u8(u8_vals, u8_vals), vzip2_u8(u8_vals, u8_vals));
            let v16_dup = vcombine_u8(vzip1_u8(v8_vals, v8_vals), vzip2_u8(v8_vals, v8_vals));

            // Process low 8 pixels
            let y_lo = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(y16)));
            let u_lo = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(u16_dup))), c_128);
            let v_lo = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(v16_dup))), c_128);

            // R = Y + (V * 359) >> 8
            let r_lo = vaddq_s16(y_lo, vshrq_n_s16::<7>(vmulq_s16(v_lo, c_179)));
            // G = Y - ((U * 88 + V * 183) >> 8)
            let g_lo = vsubq_s16(
                y_lo,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_lo, c_44), vmulq_s16(v_lo, c_91))),
            );
            // B = Y + (U * 454) >> 8
            let b_lo = vaddq_s16(y_lo, vshrq_n_s16::<7>(vmulq_s16(u_lo, c_227)));

            // Saturate to u8
            let r_lo_u8 = vqmovun_s16(r_lo);
            let g_lo_u8 = vqmovun_s16(g_lo);
            let b_lo_u8 = vqmovun_s16(b_lo);

            // Process high 8 pixels
            let y_hi = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(y16)));
            let u_hi = vsubq_s16(
                vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(u16_dup))),
                c_128,
            );
            let v_hi = vsubq_s16(
                vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(v16_dup))),
                c_128,
            );

            let r_hi = vaddq_s16(y_hi, vshrq_n_s16::<7>(vmulq_s16(v_hi, c_179)));
            let g_hi = vsubq_s16(
                y_hi,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_hi, c_44), vmulq_s16(v_hi, c_91))),
            );
            let b_hi = vaddq_s16(y_hi, vshrq_n_s16::<7>(vmulq_s16(u_hi, c_227)));

            let r_hi_u8 = vqmovun_s16(r_hi);
            let g_hi_u8 = vqmovun_s16(g_hi);
            let b_hi_u8 = vqmovun_s16(b_hi);

            // Interleave R, G, B into RGB8 and store
            let rgb_lo = uint8x8x3_t(r_lo_u8, g_lo_u8, b_lo_u8);
            vst3_u8(rgb_row_ptr.add(col * 3), rgb_lo);

            let rgb_hi = uint8x8x3_t(r_hi_u8, g_hi_u8, b_hi_u8);
            vst3_u8(rgb_row_ptr.add((col + 8) * 3), rgb_hi);

            col += 16;
        }

        // Process 8 pixels
        if col + 8 <= width {
            let y8_vals = vld1_u8(y_row_ptr.add(col));
            let u4_vals_raw = u_row_ptr.add(col / 2);
            let v4_vals_raw = v_row_ptr.add(col / 2);

            // Load 4 U/V values manually and duplicate
            let mut u_buf = [0u8; 8];
            let mut v_buf = [0u8; 8];
            for i in 0..4 {
                u_buf[i * 2] = *u4_vals_raw.add(i);
                u_buf[i * 2 + 1] = *u4_vals_raw.add(i);
                v_buf[i * 2] = *v4_vals_raw.add(i);
                v_buf[i * 2 + 1] = *v4_vals_raw.add(i);
            }
            let u8_dup = vld1_u8(u_buf.as_ptr());
            let v8_dup = vld1_u8(v_buf.as_ptr());

            let y_i16 = vreinterpretq_s16_u16(vmovl_u8(y8_vals));
            let u_i16 = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(u8_dup)), c_128);
            let v_i16 = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(v8_dup)), c_128);

            let r = vaddq_s16(y_i16, vshrq_n_s16::<7>(vmulq_s16(v_i16, c_179)));
            let g = vsubq_s16(
                y_i16,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_i16, c_44), vmulq_s16(v_i16, c_91))),
            );
            let b = vaddq_s16(y_i16, vshrq_n_s16::<7>(vmulq_s16(u_i16, c_227)));

            let r_u8 = vqmovun_s16(r);
            let g_u8 = vqmovun_s16(g);
            let b_u8 = vqmovun_s16(b);

            let rgb = uint8x8x3_t(r_u8, g_u8, b_u8);
            vst3_u8(rgb_row_ptr.add(col * 3), rgb);

            col += 8;
        }

        // Scalar tail for remaining pixels
        while col < width {
            let y_val = *y_row_ptr.add(col) as i16;
            let u_val = *u_row_ptr.add(col / 2) as i16 - 128;
            let v_val = *v_row_ptr.add(col / 2) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - (((u_val * 44) + (v_val * 91)) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = col * 3;
            *rgb_row_ptr.add(idx) = r.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 1) = g.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 2) = b.clamp(0, 255) as u8;

            col += 1;
        }
    }
}

/// AVX2-accelerated YUV420→RGB8 conversion (x86_64).
/// Processes 16 pixels per iteration using i16 fixed-point arithmetic.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn yuv420_to_rgb8_rows_avx2(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    rgb_out: &mut [u8],
    width: usize,
    uv_stride: usize,
    start_row: usize,
    end_row: usize,
) {
    use std::arch::x86_64::*;

    // BT.601 fixed-point Q7 constants
    let c_179 = _mm256_set1_epi16(179);
    let c_44 = _mm256_set1_epi16(44);
    let c_91 = _mm256_set1_epi16(91);
    let c_227 = _mm256_set1_epi16(227);
    let c_128 = _mm256_set1_epi16(128);
    let zero = _mm256_setzero_si256();

    for row in start_row..end_row {
        let out_row = row - start_row;
        let y_row_ptr = y_plane.as_ptr().add(row * width);
        let uv_row = (row / 2) * uv_stride;
        let u_row_ptr = u_plane.as_ptr().add(uv_row);
        let v_row_ptr = v_plane.as_ptr().add(uv_row);
        let rgb_row_ptr = rgb_out.as_mut_ptr().add(out_row * width * 3);

        let mut col = 0usize;

        // Process 16 pixels per iteration (16 Y, 8 U, 8 V)
        while col + 16 <= width {
            // Load 16 Y values into the low 128 bits, widen to i16 in 256 bits
            let y16 = _mm_loadu_si128(y_row_ptr.add(col) as *const __m128i);
            let y_lo = _mm256_cvtepu8_epi16(y16);

            // Load 8 U/V values, duplicate each for 2 horizontal pixels → 16 values
            let mut u_buf = [0u8; 16];
            let mut v_buf = [0u8; 16];
            for i in 0..8 {
                u_buf[i * 2] = *u_row_ptr.add(col / 2 + i);
                u_buf[i * 2 + 1] = *u_row_ptr.add(col / 2 + i);
                v_buf[i * 2] = *v_row_ptr.add(col / 2 + i);
                v_buf[i * 2 + 1] = *v_row_ptr.add(col / 2 + i);
            }
            let u16_raw = _mm_loadu_si128(u_buf.as_ptr() as *const __m128i);
            let v16_raw = _mm_loadu_si128(v_buf.as_ptr() as *const __m128i);

            let u_i16 = _mm256_sub_epi16(_mm256_cvtepu8_epi16(u16_raw), c_128);
            let v_i16 = _mm256_sub_epi16(_mm256_cvtepu8_epi16(v16_raw), c_128);

            // R = Y + (V * 179) >> 7
            let r = _mm256_add_epi16(
                y_lo,
                _mm256_srai_epi16::<7>(_mm256_mullo_epi16(v_i16, c_179)),
            );
            // G = Y - ((U * 44 + V * 91) >> 7)
            let g = _mm256_sub_epi16(
                y_lo,
                _mm256_srai_epi16::<7>(_mm256_add_epi16(
                    _mm256_mullo_epi16(u_i16, c_44),
                    _mm256_mullo_epi16(v_i16, c_91),
                )),
            );
            // B = Y + (U * 227) >> 7
            let b = _mm256_add_epi16(
                y_lo,
                _mm256_srai_epi16::<7>(_mm256_mullo_epi16(u_i16, c_227)),
            );

            // Saturating pack i16 → u8 (packus packs lanes independently, then
            // vpermute corrects the cross-lane ordering)
            let r_packed = _mm256_packus_epi16(r, zero);
            let g_packed = _mm256_packus_epi16(g, zero);
            let b_packed = _mm256_packus_epi16(b, zero);

            // Extract lower 16 bytes (the valid u8 results) after fixing lane order
            let r_perm = _mm256_permute4x64_epi64::<0xD8>(r_packed);
            let g_perm = _mm256_permute4x64_epi64::<0xD8>(g_packed);
            let b_perm = _mm256_permute4x64_epi64::<0xD8>(b_packed);

            let r_lo128 = _mm256_castsi256_si128(r_perm);
            let g_lo128 = _mm256_castsi256_si128(g_perm);
            let b_lo128 = _mm256_castsi256_si128(b_perm);

            // Interleave and store RGB (manual interleave since x86 has no vst3)
            let mut r_arr = [0u8; 16];
            let mut g_arr = [0u8; 16];
            let mut b_arr = [0u8; 16];
            _mm_storeu_si128(r_arr.as_mut_ptr() as *mut __m128i, r_lo128);
            _mm_storeu_si128(g_arr.as_mut_ptr() as *mut __m128i, g_lo128);
            _mm_storeu_si128(b_arr.as_mut_ptr() as *mut __m128i, b_lo128);

            let mut rgb_buf = [0u8; 48];
            for i in 0..16 {
                rgb_buf[i * 3] = r_arr[i];
                rgb_buf[i * 3 + 1] = g_arr[i];
                rgb_buf[i * 3 + 2] = b_arr[i];
            }
            std::ptr::copy_nonoverlapping(rgb_buf.as_ptr(), rgb_row_ptr.add(col * 3), 48);

            col += 16;
        }

        // Process 8 pixels using 128-bit subset
        while col + 8 <= width {
            let y8 = _mm_loadl_epi64(y_row_ptr.add(col) as *const __m128i);
            let zero128 = _mm_setzero_si128();
            let y_i16 = _mm_unpacklo_epi8(y8, zero128);

            let c_179_128 = _mm_set1_epi16(179);
            let c_44_128 = _mm_set1_epi16(44);
            let c_91_128 = _mm_set1_epi16(91);
            let c_227_128 = _mm_set1_epi16(227);
            let c_128_128 = _mm_set1_epi16(128);

            let mut u_buf = [0u8; 8];
            let mut v_buf = [0u8; 8];
            for i in 0..4 {
                u_buf[i * 2] = *u_row_ptr.add(col / 2 + i);
                u_buf[i * 2 + 1] = *u_row_ptr.add(col / 2 + i);
                v_buf[i * 2] = *v_row_ptr.add(col / 2 + i);
                v_buf[i * 2 + 1] = *v_row_ptr.add(col / 2 + i);
            }
            let u8_dup = _mm_loadl_epi64(u_buf.as_ptr() as *const __m128i);
            let v8_dup = _mm_loadl_epi64(v_buf.as_ptr() as *const __m128i);

            let u_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(u8_dup, zero128), c_128_128);
            let v_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(v8_dup, zero128), c_128_128);

            let r = _mm_add_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_mullo_epi16(v_i16, c_179_128)),
            );
            let g = _mm_sub_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_mullo_epi16(u_i16, c_44_128),
                    _mm_mullo_epi16(v_i16, c_91_128),
                )),
            );
            let b = _mm_add_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_mullo_epi16(u_i16, c_227_128)),
            );

            let r_u8 = _mm_packus_epi16(r, zero128);
            let g_u8 = _mm_packus_epi16(g, zero128);
            let b_u8 = _mm_packus_epi16(b, zero128);

            let mut r_arr = [0u8; 8];
            let mut g_arr = [0u8; 8];
            let mut b_arr = [0u8; 8];
            _mm_storel_epi64(r_arr.as_mut_ptr() as *mut __m128i, r_u8);
            _mm_storel_epi64(g_arr.as_mut_ptr() as *mut __m128i, g_u8);
            _mm_storel_epi64(b_arr.as_mut_ptr() as *mut __m128i, b_u8);

            let mut rgb_buf = [0u8; 24];
            for i in 0..8 {
                rgb_buf[i * 3] = r_arr[i];
                rgb_buf[i * 3 + 1] = g_arr[i];
                rgb_buf[i * 3 + 2] = b_arr[i];
            }
            std::ptr::copy_nonoverlapping(rgb_buf.as_ptr(), rgb_row_ptr.add(col * 3), 24);

            col += 8;
        }

        // Scalar tail
        while col < width {
            let y_val = *y_row_ptr.add(col) as i16;
            let u_val = *u_row_ptr.add(col / 2) as i16 - 128;
            let v_val = *v_row_ptr.add(col / 2) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - (((u_val * 44) + (v_val * 91)) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = col * 3;
            *rgb_row_ptr.add(idx) = r.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 1) = g.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 2) = b.clamp(0, 255) as u8;

            col += 1;
        }
    }
}

/// SSE2-accelerated YUV420→RGB8 conversion (x86_64).
/// Processes 8 pixels per iteration using i16 fixed-point arithmetic.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn yuv420_to_rgb8_rows_sse2(
    y_plane: &[u8],
    u_plane: &[u8],
    v_plane: &[u8],
    rgb_out: &mut [u8],
    width: usize,
    uv_stride: usize,
    start_row: usize,
    end_row: usize,
) {
    use std::arch::x86_64::*;

    // BT.601 fixed-point Q7 constants (fit in i16 without overflow)
    let c_179 = _mm_set1_epi16(179); // 1.402 * 128
    let c_44 = _mm_set1_epi16(44); // 0.344 * 128
    let c_91 = _mm_set1_epi16(91); // 0.714 * 128
    let c_227 = _mm_set1_epi16(227); // 1.772 * 128
    let c_128 = _mm_set1_epi16(128);
    let zero = _mm_setzero_si128();

    for row in start_row..end_row {
        let out_row = row - start_row;
        let y_row_ptr = y_plane.as_ptr().add(row * width);
        let uv_row = (row / 2) * uv_stride;
        let u_row_ptr = u_plane.as_ptr().add(uv_row);
        let v_row_ptr = v_plane.as_ptr().add(uv_row);
        let rgb_row_ptr = rgb_out.as_mut_ptr().add(out_row * width * 3);

        let mut col = 0usize;

        // Process 8 pixels per iteration
        while col + 8 <= width {
            // Load 8 Y values, widen to i16
            let y8 = _mm_loadl_epi64(y_row_ptr.add(col) as *const __m128i);
            let y_i16 = _mm_unpacklo_epi8(y8, zero);

            // Load 4 U/V values, duplicate each for 2 horizontal pixels
            let mut u_buf = [0u8; 8];
            let mut v_buf = [0u8; 8];
            for i in 0..4 {
                u_buf[i * 2] = *u_row_ptr.add(col / 2 + i);
                u_buf[i * 2 + 1] = *u_row_ptr.add(col / 2 + i);
                v_buf[i * 2] = *v_row_ptr.add(col / 2 + i);
                v_buf[i * 2 + 1] = *v_row_ptr.add(col / 2 + i);
            }
            let u8_dup = _mm_loadl_epi64(u_buf.as_ptr() as *const __m128i);
            let v8_dup = _mm_loadl_epi64(v_buf.as_ptr() as *const __m128i);

            let u_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(u8_dup, zero), c_128);
            let v_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(v8_dup, zero), c_128);

            // R = Y + (V * 359) >> 8
            let r = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(v_i16, c_179)));
            // G = Y - ((U * 44 + V * 91) >> 7)
            let g = _mm_sub_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_mullo_epi16(u_i16, c_44),
                    _mm_mullo_epi16(v_i16, c_91),
                )),
            );
            // B = Y + (U * 227) >> 7
            let b = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(u_i16, c_227)));

            // Saturating pack i16 → u8
            let r_u8 = _mm_packus_epi16(r, zero); // low 8 bytes valid
            let g_u8 = _mm_packus_epi16(g, zero);
            let b_u8 = _mm_packus_epi16(b, zero);

            // Interleave and store RGB (no vst3 on SSE, do it manually)
            let mut rgb_buf = [0u8; 24];
            let mut r_arr = [0u8; 8];
            let mut g_arr = [0u8; 8];
            let mut b_arr = [0u8; 8];
            _mm_storel_epi64(r_arr.as_mut_ptr() as *mut __m128i, r_u8);
            _mm_storel_epi64(g_arr.as_mut_ptr() as *mut __m128i, g_u8);
            _mm_storel_epi64(b_arr.as_mut_ptr() as *mut __m128i, b_u8);
            for i in 0..8 {
                rgb_buf[i * 3] = r_arr[i];
                rgb_buf[i * 3 + 1] = g_arr[i];
                rgb_buf[i * 3 + 2] = b_arr[i];
            }
            std::ptr::copy_nonoverlapping(rgb_buf.as_ptr(), rgb_row_ptr.add(col * 3), 24);

            col += 8;
        }

        // Scalar tail
        while col < width {
            let y_val = *y_row_ptr.add(col) as i16;
            let u_val = *u_row_ptr.add(col / 2) as i16 - 128;
            let v_val = *v_row_ptr.add(col / 2) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - (((u_val * 44) + (v_val * 91)) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = col * 3;
            *rgb_row_ptr.add(idx) = r.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 1) = g.clamp(0, 255) as u8;
            *rgb_row_ptr.add(idx + 2) = b.clamp(0, 255) as u8;

            col += 1;
        }
    }
}

// ---------------------------------------------------------------------------
// NV12 → RGB8 (interleaved UV plane)
// ---------------------------------------------------------------------------

/// Converts NV12 (Y plane + interleaved UV plane) to RGB8.
///
/// `y` is the luma plane (`w * h` bytes), `uv` is the interleaved chroma plane
/// (`w * (h/2)` bytes with U,V pairs). Output is `w * h * 3` bytes RGB8.
///
/// Uses BT.601 full-range coefficients with NEON acceleration on aarch64,
/// SSE2 on x86_64, and a scalar fallback.
#[allow(unsafe_code)]
pub fn nv12_to_rgb8(
    y: &[u8],
    uv: &[u8],
    w: usize,
    h: usize,
    out: &mut [u8],
) -> Result<(), VideoError> {
    let expected_y = w * h;
    let expected_uv = w * (h / 2);
    let expected_out = w * h * 3;

    if y.len() < expected_y {
        return Err(VideoError::Codec(format!(
            "NV12: Y plane too small: expected {expected_y}, got {}",
            y.len()
        )));
    }
    if uv.len() < expected_uv {
        return Err(VideoError::Codec(format!(
            "NV12: UV plane too small: expected {expected_uv}, got {}",
            uv.len()
        )));
    }
    if out.len() < expected_out {
        return Err(VideoError::Codec(format!(
            "NV12: output buffer too small: expected {expected_out}, got {}",
            out.len()
        )));
    }

    #[cfg(target_arch = "aarch64")]
    {
        if std::arch::is_aarch64_feature_detected!("neon") {
            unsafe {
                nv12_to_rgb8_neon(y, uv, w, h, out);
            }
            return Ok(());
        }
    }

    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("sse2") {
            unsafe {
                nv12_to_rgb8_sse2(y, uv, w, h, out);
            }
            return Ok(());
        }
    }

    nv12_to_rgb8_scalar(y, uv, w, h, out);
    Ok(())
}

/// Scalar NV12 → RGB8 fallback.
fn nv12_to_rgb8_scalar(y: &[u8], uv: &[u8], w: usize, h: usize, out: &mut [u8]) {
    for row in 0..h {
        let y_off = row * w;
        let uv_off = (row / 2) * w; // UV plane has same width, half height
        let dst_off = row * w * 3;

        for col in 0..w {
            let y_val = y[y_off + col] as i16;
            let u_val = uv[uv_off + (col & !1)] as i16 - 128;
            let v_val = uv[uv_off + (col | 1)] as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = dst_off + col * 3;
            out[idx] = r.clamp(0, 255) as u8;
            out[idx + 1] = g.clamp(0, 255) as u8;
            out[idx + 2] = b.clamp(0, 255) as u8;
        }
    }
}

/// NEON-accelerated NV12 → RGB8 (aarch64). Processes 16 pixels per iteration.
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn nv12_to_rgb8_neon(y: &[u8], uv: &[u8], w: usize, h: usize, out: &mut [u8]) {
    use std::arch::aarch64::*;

    let c_179 = vdupq_n_s16(179);
    let c_44 = vdupq_n_s16(44);
    let c_91 = vdupq_n_s16(91);
    let c_227 = vdupq_n_s16(227);
    let c_128 = vdupq_n_s16(128);

    for row in 0..h {
        let y_row = y.as_ptr().add(row * w);
        let uv_row = uv.as_ptr().add((row / 2) * w);
        let dst_row = out.as_mut_ptr().add(row * w * 3);

        let mut col = 0usize;

        // Process 16 luma pixels at a time (8 UV pairs)
        while col + 16 <= w {
            let y16 = vld1q_u8(y_row.add(col));

            // Load 16 bytes of interleaved UV (8 U-V pairs)
            let uv16 = vld2_u8(uv_row.add(col));
            let u8_vals = uv16.0; // 8 U values
            let v8_vals = uv16.1; // 8 V values

            // Duplicate each U/V value for 2 horizontal pixels
            let u_dup = vcombine_u8(vzip1_u8(u8_vals, u8_vals), vzip2_u8(u8_vals, u8_vals));
            let v_dup = vcombine_u8(vzip1_u8(v8_vals, v8_vals), vzip2_u8(v8_vals, v8_vals));

            // Low 8 pixels
            let y_lo = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(y16)));
            let u_lo = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(u_dup))), c_128);
            let v_lo = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(v_dup))), c_128);

            let r_lo = vaddq_s16(y_lo, vshrq_n_s16::<7>(vmulq_s16(v_lo, c_179)));
            let g_lo = vsubq_s16(
                y_lo,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_lo, c_44), vmulq_s16(v_lo, c_91))),
            );
            let b_lo = vaddq_s16(y_lo, vshrq_n_s16::<7>(vmulq_s16(u_lo, c_227)));

            let rgb_lo = uint8x8x3_t(vqmovun_s16(r_lo), vqmovun_s16(g_lo), vqmovun_s16(b_lo));
            vst3_u8(dst_row.add(col * 3), rgb_lo);

            // High 8 pixels
            let y_hi = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(y16)));
            let u_hi = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(u_dup))), c_128);
            let v_hi = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(v_dup))), c_128);

            let r_hi = vaddq_s16(y_hi, vshrq_n_s16::<7>(vmulq_s16(v_hi, c_179)));
            let g_hi = vsubq_s16(
                y_hi,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_hi, c_44), vmulq_s16(v_hi, c_91))),
            );
            let b_hi = vaddq_s16(y_hi, vshrq_n_s16::<7>(vmulq_s16(u_hi, c_227)));

            let rgb_hi = uint8x8x3_t(vqmovun_s16(r_hi), vqmovun_s16(g_hi), vqmovun_s16(b_hi));
            vst3_u8(dst_row.add((col + 8) * 3), rgb_hi);

            col += 16;
        }

        // Scalar tail
        while col < w {
            let y_val = *y_row.add(col) as i16;
            let u_val = *uv_row.add(col & !1) as i16 - 128;
            let v_val = *uv_row.add(col | 1) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = col * 3;
            *dst_row.add(idx) = r.clamp(0, 255) as u8;
            *dst_row.add(idx + 1) = g.clamp(0, 255) as u8;
            *dst_row.add(idx + 2) = b.clamp(0, 255) as u8;

            col += 1;
        }
    }
}

/// SSE2-accelerated NV12 → RGB8 (x86_64). Processes 8 pixels per iteration.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn nv12_to_rgb8_sse2(y: &[u8], uv: &[u8], w: usize, h: usize, out: &mut [u8]) {
    use std::arch::x86_64::*;

    let c_179 = _mm_set1_epi16(179);
    let c_44 = _mm_set1_epi16(44);
    let c_91 = _mm_set1_epi16(91);
    let c_227 = _mm_set1_epi16(227);
    let c_128 = _mm_set1_epi16(128);
    let zero = _mm_setzero_si128();

    for row in 0..h {
        let y_row = y.as_ptr().add(row * w);
        let uv_row = uv.as_ptr().add((row / 2) * w);
        let dst_row = out.as_mut_ptr().add(row * w * 3);

        let mut col = 0usize;

        while col + 8 <= w {
            let y8 = _mm_loadl_epi64(y_row.add(col) as *const __m128i);
            let y_i16 = _mm_unpacklo_epi8(y8, zero);

            // Load 8 bytes of UV (4 pairs), deinterleave manually
            let mut u_buf = [0u8; 8];
            let mut v_buf = [0u8; 8];
            for i in 0..4 {
                let u_val = *uv_row.add(col + i * 2);
                let v_val = *uv_row.add(col + i * 2 + 1);
                u_buf[i * 2] = u_val;
                u_buf[i * 2 + 1] = u_val;
                v_buf[i * 2] = v_val;
                v_buf[i * 2 + 1] = v_val;
            }

            let u8_dup = _mm_loadl_epi64(u_buf.as_ptr() as *const __m128i);
            let v8_dup = _mm_loadl_epi64(v_buf.as_ptr() as *const __m128i);

            let u_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(u8_dup, zero), c_128);
            let v_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(v8_dup, zero), c_128);

            let r = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(v_i16, c_179)));
            let g = _mm_sub_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_mullo_epi16(u_i16, c_44),
                    _mm_mullo_epi16(v_i16, c_91),
                )),
            );
            let b = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(u_i16, c_227)));

            let r_u8 = _mm_packus_epi16(r, zero);
            let g_u8 = _mm_packus_epi16(g, zero);
            let b_u8 = _mm_packus_epi16(b, zero);

            let mut r_arr = [0u8; 8];
            let mut g_arr = [0u8; 8];
            let mut b_arr = [0u8; 8];
            _mm_storel_epi64(r_arr.as_mut_ptr() as *mut __m128i, r_u8);
            _mm_storel_epi64(g_arr.as_mut_ptr() as *mut __m128i, g_u8);
            _mm_storel_epi64(b_arr.as_mut_ptr() as *mut __m128i, b_u8);

            let mut rgb_buf = [0u8; 24];
            for i in 0..8 {
                rgb_buf[i * 3] = r_arr[i];
                rgb_buf[i * 3 + 1] = g_arr[i];
                rgb_buf[i * 3 + 2] = b_arr[i];
            }
            std::ptr::copy_nonoverlapping(rgb_buf.as_ptr(), dst_row.add(col * 3), 24);

            col += 8;
        }

        // Scalar tail
        while col < w {
            let y_val = *y_row.add(col) as i16;
            let u_val = *uv_row.add(col & !1) as i16 - 128;
            let v_val = *uv_row.add(col | 1) as i16 - 128;

            let r = y_val + ((v_val * 179) >> 7);
            let g = y_val - ((u_val * 44 + v_val * 91) >> 7);
            let b = y_val + ((u_val * 227) >> 7);

            let idx = col * 3;
            *dst_row.add(idx) = r.clamp(0, 255) as u8;
            *dst_row.add(idx + 1) = g.clamp(0, 255) as u8;
            *dst_row.add(idx + 2) = b.clamp(0, 255) as u8;

            col += 1;
        }
    }
}

// ---------------------------------------------------------------------------
// YUYV (4:2:2 packed) → RGB8
// ---------------------------------------------------------------------------

/// Converts YUYV (YUY2) packed 4:2:2 to RGB8.
///
/// Each 4 bytes encode 2 pixels: `[Y0, U, Y1, V]`.
/// `data` is `w * h * 2` bytes, `out` must be at least `w * h * 3` bytes.
///
/// Uses BT.601 full-range coefficients with NEON acceleration on aarch64,
/// SSE2 on x86_64, and a scalar fallback.
#[allow(unsafe_code)]
pub fn yuyv_to_rgb8(data: &[u8], w: usize, h: usize, out: &mut [u8]) -> Result<(), VideoError> {
    let expected_in = w * h * 2;
    let expected_out = w * h * 3;

    if data.len() < expected_in {
        return Err(VideoError::Codec(format!(
            "YUYV: input too small: expected {expected_in}, got {}",
            data.len()
        )));
    }
    if out.len() < expected_out {
        return Err(VideoError::Codec(format!(
            "YUYV: output too small: expected {expected_out}, got {}",
            out.len()
        )));
    }
    if !w.is_multiple_of(2) {
        return Err(VideoError::Codec("YUYV: width must be even".into()));
    }

    #[cfg(target_arch = "aarch64")]
    {
        if std::arch::is_aarch64_feature_detected!("neon") {
            unsafe {
                yuyv_to_rgb8_neon(data, w, h, out);
            }
            return Ok(());
        }
    }

    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("sse2") {
            unsafe {
                yuyv_to_rgb8_sse2(data, w, h, out);
            }
            return Ok(());
        }
    }

    yuyv_to_rgb8_scalar(data, w, h, out);
    Ok(())
}

/// Scalar YUYV → RGB8 fallback.
fn yuyv_to_rgb8_scalar(data: &[u8], w: usize, h: usize, out: &mut [u8]) {
    let pairs = w / 2;
    for row in 0..h {
        let src_off = row * w * 2;
        let dst_off = row * w * 3;

        for pair in 0..pairs {
            let si = src_off + pair * 4;
            let y0 = data[si] as i16;
            let u_val = data[si + 1] as i16 - 128;
            let y1 = data[si + 2] as i16;
            let v_val = data[si + 3] as i16 - 128;

            let r0 = y0 + ((v_val * 179) >> 7);
            let g0 = y0 - ((u_val * 44 + v_val * 91) >> 7);
            let b0 = y0 + ((u_val * 227) >> 7);

            let r1 = y1 + ((v_val * 179) >> 7);
            let g1 = y1 - ((u_val * 44 + v_val * 91) >> 7);
            let b1 = y1 + ((u_val * 227) >> 7);

            let di = dst_off + pair * 6;
            out[di] = r0.clamp(0, 255) as u8;
            out[di + 1] = g0.clamp(0, 255) as u8;
            out[di + 2] = b0.clamp(0, 255) as u8;
            out[di + 3] = r1.clamp(0, 255) as u8;
            out[di + 4] = g1.clamp(0, 255) as u8;
            out[di + 5] = b1.clamp(0, 255) as u8;
        }
    }
}

/// NEON-accelerated YUYV → RGB8 (aarch64). Processes 16 pixels (32 YUYV bytes) per iteration.
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn yuyv_to_rgb8_neon(data: &[u8], w: usize, h: usize, out: &mut [u8]) {
    use std::arch::aarch64::*;

    let c_179 = vdupq_n_s16(179);
    let c_44 = vdupq_n_s16(44);
    let c_91 = vdupq_n_s16(91);
    let c_227 = vdupq_n_s16(227);
    let c_128 = vdupq_n_s16(128);

    for row in 0..h {
        let src_row = data.as_ptr().add(row * w * 2);
        let dst_row = out.as_mut_ptr().add(row * w * 3);

        let mut col = 0usize;

        // 16 pixels = 32 YUYV bytes = 8 macro-pixels (each Y0,U,Y1,V)
        while col + 16 <= w {
            // Load 32 bytes, deinterleave as 4 channels of 8 bytes each
            let yuyv = vld4_u8(src_row.add(col * 2));
            // yuyv.0 = Y0 (8 values), yuyv.1 = U (8 values)
            // yuyv.2 = Y1 (8 values), yuyv.3 = V (8 values)
            let y0_8 = yuyv.0;
            let u_8 = yuyv.1;
            let y1_8 = yuyv.2;
            let v_8 = yuyv.3;

            // Process first 8 pixels (Y0 values with their U/V)
            let y0_i16 = vreinterpretq_s16_u16(vmovl_u8(y0_8));
            let u_i16 = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(u_8)), c_128);
            let v_i16 = vsubq_s16(vreinterpretq_s16_u16(vmovl_u8(v_8)), c_128);

            let r0 = vaddq_s16(y0_i16, vshrq_n_s16::<7>(vmulq_s16(v_i16, c_179)));
            let g0 = vsubq_s16(
                y0_i16,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_i16, c_44), vmulq_s16(v_i16, c_91))),
            );
            let b0 = vaddq_s16(y0_i16, vshrq_n_s16::<7>(vmulq_s16(u_i16, c_227)));

            // Process second 8 pixels (Y1 values with same U/V)
            let y1_i16 = vreinterpretq_s16_u16(vmovl_u8(y1_8));

            let r1 = vaddq_s16(y1_i16, vshrq_n_s16::<7>(vmulq_s16(v_i16, c_179)));
            let g1 = vsubq_s16(
                y1_i16,
                vshrq_n_s16::<7>(vaddq_s16(vmulq_s16(u_i16, c_44), vmulq_s16(v_i16, c_91))),
            );
            let b1 = vaddq_s16(y1_i16, vshrq_n_s16::<7>(vmulq_s16(u_i16, c_227)));

            // Interleave: pixel order is Y0[0], Y1[0], Y0[1], Y1[1], ...
            // So we need to zip the R/G/B pairs together.
            let r_lo = vqmovun_s16(r0);
            let r_hi = vqmovun_s16(r1);
            let g_lo = vqmovun_s16(g0);
            let g_hi = vqmovun_s16(g1);
            let b_lo = vqmovun_s16(b0);
            let b_hi = vqmovun_s16(b1);

            // Zip Y0 and Y1 results: R = [r0_0, r1_0, r0_1, r1_1, ...]
            let r_zip = vzip1_u8(r_lo, r_hi);
            let r_zip2 = vzip2_u8(r_lo, r_hi);
            let g_zip = vzip1_u8(g_lo, g_hi);
            let g_zip2 = vzip2_u8(g_lo, g_hi);
            let b_zip = vzip1_u8(b_lo, b_hi);
            let b_zip2 = vzip2_u8(b_lo, b_hi);

            // Store first 8 pixels
            let rgb_first = uint8x8x3_t(r_zip, g_zip, b_zip);
            vst3_u8(dst_row.add(col * 3), rgb_first);

            // Store second 8 pixels
            let rgb_second = uint8x8x3_t(r_zip2, g_zip2, b_zip2);
            vst3_u8(dst_row.add((col + 8) * 3), rgb_second);

            col += 16;
        }

        // Scalar tail (always an even number remaining since w is even)
        while col + 2 <= w {
            let si = col * 2;
            let y0 = *src_row.add(si) as i16;
            let u_val = *src_row.add(si + 1) as i16 - 128;
            let y1 = *src_row.add(si + 2) as i16;
            let v_val = *src_row.add(si + 3) as i16 - 128;

            let r0 = y0 + ((v_val * 179) >> 7);
            let g0 = y0 - ((u_val * 44 + v_val * 91) >> 7);
            let b0 = y0 + ((u_val * 227) >> 7);
            let r1 = y1 + ((v_val * 179) >> 7);
            let g1 = y1 - ((u_val * 44 + v_val * 91) >> 7);
            let b1 = y1 + ((u_val * 227) >> 7);

            let di = col * 3;
            *dst_row.add(di) = r0.clamp(0, 255) as u8;
            *dst_row.add(di + 1) = g0.clamp(0, 255) as u8;
            *dst_row.add(di + 2) = b0.clamp(0, 255) as u8;
            *dst_row.add(di + 3) = r1.clamp(0, 255) as u8;
            *dst_row.add(di + 4) = g1.clamp(0, 255) as u8;
            *dst_row.add(di + 5) = b1.clamp(0, 255) as u8;

            col += 2;
        }
    }
}

/// SSE2-accelerated YUYV → RGB8 (x86_64). Processes 8 pixels (16 YUYV bytes) per iteration.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
#[allow(unsafe_code, unsafe_op_in_unsafe_fn)]
unsafe fn yuyv_to_rgb8_sse2(data: &[u8], w: usize, h: usize, out: &mut [u8]) {
    use std::arch::x86_64::*;

    let c_179 = _mm_set1_epi16(179);
    let c_44 = _mm_set1_epi16(44);
    let c_91 = _mm_set1_epi16(91);
    let c_227 = _mm_set1_epi16(227);
    let c_128_16 = _mm_set1_epi16(128);
    let zero = _mm_setzero_si128();

    for row in 0..h {
        let src_row = data.as_ptr().add(row * w * 2);
        let dst_row = out.as_mut_ptr().add(row * w * 3);

        let mut col = 0usize;

        // 8 pixels = 16 bytes YUYV = 4 macro-pixels
        while col + 8 <= w {
            // Load 16 bytes of YUYV, manually deinterleave
            let mut y_buf = [0u8; 8];
            let mut u_buf = [0u8; 8];
            let mut v_buf = [0u8; 8];
            for i in 0..4 {
                let si = col * 2 + i * 4;
                y_buf[i * 2] = *src_row.add(si);
                y_buf[i * 2 + 1] = *src_row.add(si + 2);
                let u = *src_row.add(si + 1);
                let v = *src_row.add(si + 3);
                u_buf[i * 2] = u;
                u_buf[i * 2 + 1] = u;
                v_buf[i * 2] = v;
                v_buf[i * 2 + 1] = v;
            }

            let y8 = _mm_loadl_epi64(y_buf.as_ptr() as *const __m128i);
            let u8_dup = _mm_loadl_epi64(u_buf.as_ptr() as *const __m128i);
            let v8_dup = _mm_loadl_epi64(v_buf.as_ptr() as *const __m128i);

            let y_i16 = _mm_unpacklo_epi8(y8, zero);
            let u_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(u8_dup, zero), c_128_16);
            let v_i16 = _mm_sub_epi16(_mm_unpacklo_epi8(v8_dup, zero), c_128_16);

            let r = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(v_i16, c_179)));
            let g = _mm_sub_epi16(
                y_i16,
                _mm_srai_epi16::<7>(_mm_add_epi16(
                    _mm_mullo_epi16(u_i16, c_44),
                    _mm_mullo_epi16(v_i16, c_91),
                )),
            );
            let b = _mm_add_epi16(y_i16, _mm_srai_epi16::<7>(_mm_mullo_epi16(u_i16, c_227)));

            let r_u8 = _mm_packus_epi16(r, zero);
            let g_u8 = _mm_packus_epi16(g, zero);
            let b_u8 = _mm_packus_epi16(b, zero);

            let mut r_arr = [0u8; 8];
            let mut g_arr = [0u8; 8];
            let mut b_arr = [0u8; 8];
            _mm_storel_epi64(r_arr.as_mut_ptr() as *mut __m128i, r_u8);
            _mm_storel_epi64(g_arr.as_mut_ptr() as *mut __m128i, g_u8);
            _mm_storel_epi64(b_arr.as_mut_ptr() as *mut __m128i, b_u8);

            let mut rgb_buf = [0u8; 24];
            for i in 0..8 {
                rgb_buf[i * 3] = r_arr[i];
                rgb_buf[i * 3 + 1] = g_arr[i];
                rgb_buf[i * 3 + 2] = b_arr[i];
            }
            std::ptr::copy_nonoverlapping(rgb_buf.as_ptr(), dst_row.add(col * 3), 24);

            col += 8;
        }

        // Scalar tail
        while col + 2 <= w {
            let si = col * 2;
            let y0 = *src_row.add(si) as i16;
            let u_val = *src_row.add(si + 1) as i16 - 128;
            let y1 = *src_row.add(si + 2) as i16;
            let v_val = *src_row.add(si + 3) as i16 - 128;

            let r0 = y0 + ((v_val * 179) >> 7);
            let g0 = y0 - ((u_val * 44 + v_val * 91) >> 7);
            let b0 = y0 + ((u_val * 227) >> 7);
            let r1 = y1 + ((v_val * 179) >> 7);
            let g1 = y1 - ((u_val * 44 + v_val * 91) >> 7);
            let b1 = y1 + ((u_val * 227) >> 7);

            let di = col * 3;
            *dst_row.add(di) = r0.clamp(0, 255) as u8;
            *dst_row.add(di + 1) = g0.clamp(0, 255) as u8;
            *dst_row.add(di + 2) = b0.clamp(0, 255) as u8;
            *dst_row.add(di + 3) = r1.clamp(0, 255) as u8;
            *dst_row.add(di + 4) = g1.clamp(0, 255) as u8;
            *dst_row.add(di + 5) = b1.clamp(0, 255) as u8;

            col += 2;
        }
    }
}