zenpixels-convert 0.2.9

Transfer-function-aware pixel conversion, gamut mapping, and codec format negotiation for zenpixels
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
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
//! Pre-computed row converter.
//!
//! [`RowConverter`] wraps a [`ConvertPlan`] with pre-allocated scratch
//! buffers for zero-allocation-per-row streaming conversion.

use alloc::boxed::Box;

use crate::convert::{ConvertPlan, ConvertScratch, convert_row_buffered};
use crate::{ChannelLayout, ConvertError, PixelDescriptor};
use whereat::{At, ResultAtExt};

/// Pre-computed pixel format converter with pre-allocated scratch buffers.
///
/// Create once, then call [`convert_row`](Self::convert_row) for each row.
/// Multi-step conversions reuse internal scratch buffers, eliminating
/// per-row heap allocation.
///
/// # Example
///
/// ```rust,ignore
/// use zenpixels::{RowConverter, PixelDescriptor};
///
/// let mut conv = RowConverter::new(
///     PixelDescriptor::RGB8_SRGB,
///     PixelDescriptor::RGBA8_SRGB,
/// )?;
///
/// for y in 0..height {
///     conv.convert_row(&src_row, &mut dst_row, width);
/// }
/// ```
pub struct RowConverter {
    plan: ConvertPlan,
    scratch: ConvertScratch,
    /// External CMS transform that bypasses the plan entirely.
    /// Set by `new_explicit_with_cms` when a plugin accepts the conversion.
    external: Option<ExternalTransform>,
}

/// External CMS transform variant.
enum ExternalTransform {
    /// Stateless, shareable. Supports cheap clone and parallel use.
    Shared(alloc::sync::Arc<dyn crate::cms::RowTransform>),
    /// Owned, stateful. Unique per `RowConverter`.
    Owned(Box<dyn crate::cms::RowTransformMut>),
}

impl RowConverter {
    /// Create a converter from `from` to `to`.
    ///
    /// Cross-profile conversions (different primaries or transfer) go
    /// through the default CMS dispatch chain — see
    /// [`new_explicit_with_cms`](Self::new_explicit_with_cms) for details.
    /// Returns `Err` if no conversion path exists between the formats.
    #[track_caller]
    pub fn new(from: PixelDescriptor, to: PixelDescriptor) -> Result<Self, At<ConvertError>> {
        Self::new_explicit_with_cms(from, to, &crate::policy::ConvertOptions::permissive(), None)
    }

    /// Create a converter with explicit policy options.
    ///
    /// Like [`new`](Self::new) but validates [`ConvertOptions`] policies
    /// (alpha removal, depth reduction, RGB→Gray). Cross-profile
    /// conversions go through the default CMS dispatch chain.
    ///
    /// [`ConvertOptions`]: crate::policy::ConvertOptions
    #[track_caller]
    pub fn new_explicit(
        from: PixelDescriptor,
        to: PixelDescriptor,
        options: &crate::policy::ConvertOptions,
    ) -> Result<Self, At<ConvertError>> {
        Self::new_explicit_with_cms(from, to, options, None)
    }

    /// Create a converter that may delegate the color conversion to a
    /// [`PluggableCms`].
    ///
    /// When `cms` is `Some` and the source and destination have different
    /// primaries or transfer functions, the plugin is asked to supply a
    /// row transform for the full `(from, to)` pair. If it accepts, the
    /// plan becomes a single external-transform step; the built-in gamut
    /// matrix and matlut fast paths are bypassed for that conversion.
    /// If the plugin declines or there is no color work to do, behavior
    /// matches [`new_explicit`](Self::new_explicit).
    ///
    /// [`PluggableCms`]: crate::cms::PluggableCms
    #[track_caller]
    pub fn new_explicit_with_cms(
        from: PixelDescriptor,
        to: PixelDescriptor,
        options: &crate::policy::ConvertOptions,
        cms: Option<&dyn crate::cms::PluggableCms>,
    ) -> Result<Self, At<ConvertError>> {
        use crate::policy::{AlphaPolicy, DepthPolicy};

        // CMS dispatch chain (runs only when primaries differ — transfer-only
        // changes stay on the built-in plan path so `compose` can peephole
        // them and options like `clip_out_of_gamut` propagate through):
        //   1. user-supplied plugin (if Some)
        //   2. ZenCmsLite (default) — named-profile matlut fast path
        //
        // Per-plugin semantics:
        //   - None → declined, try next plugin
        //   - Some(Ok(t)) → accepted, stop the chain
        //   - Some(Err(e)) → tried-and-failed, propagate the error and stop.
        //     Falling through to another backend could silently produce
        //     different output — surface the failure instead.
        let primaries_differ = from.primaries != to.primaries;
        if primaries_differ {
            let src_src = from.color_profile_source();
            let dst_src = to.color_profile_source();
            let src_fmt = from.pixel_format();
            let dst_fmt = to.pixel_format();

            // Helper: ask one plugin for a transform, preferring shared.
            // Returns:
            //   Ok(Some(t)) → plugin accepted
            //   Ok(None)    → plugin declined
            //   Err(e)      → plugin tried and failed (At<CmsPluginError>
            //                 carries the plugin's internal failure point
            //                 plus a zenpixels-convert crate boundary stamp
            //                 added via `whereat::at_crate!`).
            let try_cms = |plugin: &dyn crate::cms::PluggableCms| -> Result<
                Option<ExternalTransform>,
                whereat::At<crate::cms::CmsPluginError>,
            > {
                if let Some(result) = plugin.build_shared_source_transform(
                    src_src.clone(),
                    dst_src.clone(),
                    src_fmt,
                    dst_fmt,
                    options,
                ) {
                    return whereat::at_crate!(result).map(|t| Some(ExternalTransform::Shared(t)));
                }
                if let Some(result) = plugin.build_source_transform(
                    src_src.clone(),
                    dst_src.clone(),
                    src_fmt,
                    dst_fmt,
                    options,
                ) {
                    return whereat::at_crate!(result).map(|t| Some(ExternalTransform::Owned(t)));
                }
                Ok(None)
            };

            // Convert a plugin failure into ConvertError::CmsError. The
            // `At<CmsPluginError>` Display impl already renders the full
            // frame trace + crate info (plugin + crate boundary).
            let plugin_err = |e: whereat::At<crate::cms::CmsPluginError>| {
                whereat::at!(ConvertError::CmsError(alloc::format!("{e}")))
            };

            let mut external: Option<ExternalTransform> = None;
            if let Some(plugin) = cms {
                match try_cms(plugin) {
                    Ok(Some(t)) => external = Some(t),
                    Ok(None) => {}
                    Err(e) => return Err(plugin_err(e)),
                }
            }
            if external.is_none() {
                match try_cms(&crate::cms_lite::ZenCmsLite) {
                    Ok(Some(t)) => external = Some(t),
                    Ok(None) => {}
                    Err(e) => return Err(plugin_err(e)),
                }
            }

            if let Some(external) = external {
                // Policy checks still apply.
                let drops_alpha = from.alpha().is_some() && to.alpha().is_none();
                if drops_alpha && options.alpha_policy == AlphaPolicy::Forbid {
                    return Err(whereat::at!(ConvertError::AlphaRemovalForbidden));
                }
                let reduces_depth = from.channel_type().byte_size() > to.channel_type().byte_size();
                if reduces_depth && options.depth_policy == DepthPolicy::Forbid {
                    return Err(whereat::at!(ConvertError::DepthReductionForbidden));
                }
                let src_is_rgb = matches!(
                    from.layout(),
                    ChannelLayout::Rgb | ChannelLayout::Rgba | ChannelLayout::Bgra
                );
                let dst_is_gray =
                    matches!(to.layout(), ChannelLayout::Gray | ChannelLayout::GrayAlpha);
                if src_is_rgb && dst_is_gray && options.luma.is_none() {
                    return Err(whereat::at!(ConvertError::RgbToGray));
                }

                return Ok(Self {
                    plan: ConvertPlan::identity(from, to),
                    scratch: ConvertScratch::new(),
                    external: Some(external),
                });
            }
        }

        // Same profiles, or CMS chain declined — built-in plan.
        let plan = ConvertPlan::new_explicit(from, to, options).at()?;
        Ok(Self {
            plan,
            scratch: ConvertScratch::new(),
            external: None,
        })
    }

    /// Create a converter from a pre-computed plan.
    pub fn from_plan(plan: ConvertPlan) -> Self {
        Self {
            plan,
            scratch: ConvertScratch::new(),
            external: None,
        }
    }

    /// Convert one row of `width` pixels.
    ///
    /// `src` must contain at least `width * from.bytes_per_pixel()` bytes.
    /// `dst` must contain at least `width * to.bytes_per_pixel()` bytes.
    ///
    /// Multi-step conversions reuse internal scratch buffers — no heap
    /// allocation after the first call at a given width.
    #[inline]
    pub fn convert_row(&mut self, src: &[u8], dst: &mut [u8], width: u32) {
        match &mut self.external {
            Some(ExternalTransform::Shared(arc)) => arc.transform_row(src, dst, width),
            Some(ExternalTransform::Owned(b)) => b.transform_row(src, dst, width),
            None => convert_row_buffered(&self.plan, src, dst, width, &mut self.scratch),
        }
    }

    /// Convert multiple rows from a strided source buffer to a strided destination.
    ///
    /// The source and destination can have different strides.
    #[track_caller]
    pub fn convert_rows(
        &mut self,
        src: &[u8],
        src_stride: usize,
        dst: &mut [u8],
        dst_stride: usize,
        width: u32,
        rows: u32,
    ) -> Result<(), At<ConvertError>> {
        for y in 0..rows {
            let src_start = y as usize * src_stride;
            let src_end = src_start + (width as usize * self.plan.from().bytes_per_pixel());
            let dst_start = y as usize * dst_stride;
            let dst_end = dst_start + (width as usize * self.plan.to().bytes_per_pixel());

            if src_end > src.len() || dst_end > dst.len() {
                return Err(whereat::at!(ConvertError::BufferSize {
                    expected: dst_end,
                    actual: dst.len(),
                }));
            }

            self.convert_row(
                &src[src_start..src_end],
                &mut dst[dst_start..dst_end],
                width,
            );
        }
        Ok(())
    }

    /// True if the conversion is a no-op (formats are identical).
    #[inline]
    #[must_use]
    pub fn is_identity(&self) -> bool {
        // External transforms (CMS plugins, named-profile matlut) shadow
        // the plan with real conversion work — only identity when no
        // external is set and the plan itself is identity.
        self.external.is_none() && self.plan.is_identity()
    }

    /// Source pixel format.
    #[inline]
    pub fn from_descriptor(&self) -> PixelDescriptor {
        self.plan.from()
    }

    /// Target pixel format.
    #[inline]
    pub fn to_descriptor(&self) -> PixelDescriptor {
        self.plan.to()
    }

    /// Compose two converters: apply `self` then `other` in a single pass.
    ///
    /// Adjacent inverse steps cancel (e.g., sRGB→linear then linear→sRGB
    /// becomes identity). This eliminates intermediate buffers in zenpipe's
    /// TransformSource when chaining format conversions.
    ///
    /// Returns `None` if the converters are incompatible (self.to != other.from).
    pub fn compose(&self, other: &Self) -> Option<Self> {
        self.plan.compose(&other.plan).map(Self::from_plan)
    }

    /// Access the underlying conversion plan.
    pub fn plan(&self) -> &ConvertPlan {
        &self.plan
    }
}

impl Clone for RowConverter {
    fn clone(&self) -> Self {
        // Shared external transforms clone cheaply via Arc; owned ones
        // can't be cloned and are dropped (clone falls back to the
        // built-in plan for that case).
        let external = match &self.external {
            Some(ExternalTransform::Shared(arc)) => {
                Some(ExternalTransform::Shared(alloc::sync::Arc::clone(arc)))
            }
            Some(ExternalTransform::Owned(_)) | None => None,
        };
        Self {
            plan: self.plan.clone(),
            scratch: ConvertScratch::new(),
            external,
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec;

    use super::*;
    use crate::convert::ConvertPlan;
    use crate::policy::{AlphaPolicy, ConvertOptions, DepthPolicy};
    use crate::{AlphaMode, ChannelLayout, ChannelType, ConvertError, TransferFunction};

    /// Helper: build a RowConverter and convert a single pixel.
    fn convert_pixel(
        from: PixelDescriptor,
        to: PixelDescriptor,
        src: &[u8],
    ) -> alloc::vec::Vec<u8> {
        let mut conv = RowConverter::new(from, to).unwrap();
        let dst_bpp = to.bytes_per_pixel();
        let mut dst = vec![0u8; dst_bpp];
        conv.convert_row(src, &mut dst, 1);
        dst
    }

    // -----------------------------------------------------------------------
    // Identity / no-op
    // -----------------------------------------------------------------------

    #[test]
    fn identity_conversion() {
        let desc = PixelDescriptor::RGB8_SRGB;
        let mut conv = RowConverter::new(desc, desc).unwrap();
        assert!(conv.is_identity());
        assert_eq!(conv.from_descriptor(), desc);
        assert_eq!(conv.to_descriptor(), desc);

        let src = [10u8, 20, 30, 40, 50, 60];
        let mut dst = [0u8; 6];
        conv.convert_row(&src, &mut dst, 2);
        assert_eq!(dst, src);
    }

    // -----------------------------------------------------------------------
    // Layout conversions
    // -----------------------------------------------------------------------

    #[test]
    fn rgb8_to_rgba8() {
        let dst = convert_pixel(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::RGBA8_SRGB,
            &[100, 150, 200],
        );
        assert_eq!(dst, [100, 150, 200, 255]);
    }

    #[test]
    fn rgba8_to_rgb8() {
        let dst = convert_pixel(
            PixelDescriptor::RGBA8_SRGB,
            PixelDescriptor::RGB8_SRGB,
            &[100, 150, 200, 128],
        );
        assert_eq!(dst, [100, 150, 200]);
    }

    #[test]
    fn bgra8_to_rgba8() {
        let dst = convert_pixel(
            PixelDescriptor::BGRA8_SRGB,
            PixelDescriptor::RGBA8_SRGB,
            &[200, 150, 100, 255], // BGRA
        );
        assert_eq!(dst, [100, 150, 200, 255]); // RGBA
    }

    #[test]
    fn rgba8_to_bgra8() {
        let dst = convert_pixel(
            PixelDescriptor::RGBA8_SRGB,
            PixelDescriptor::BGRA8_SRGB,
            &[100, 150, 200, 255],
        );
        assert_eq!(dst, [200, 150, 100, 255]);
    }

    #[test]
    fn rgb8_to_bgra8() {
        // RGB → RGBA → BGRA (two-step).
        let dst = convert_pixel(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::BGRA8_SRGB,
            &[100, 150, 200],
        );
        assert_eq!(dst, [200, 150, 100, 255]);
    }

    #[test]
    fn bgra8_to_rgb8() {
        // BGRA → RGBA → RGB (two-step).
        let dst = convert_pixel(
            PixelDescriptor::BGRA8_SRGB,
            PixelDescriptor::RGB8_SRGB,
            &[200, 150, 100, 255],
        );
        assert_eq!(dst, [100, 150, 200]);
    }

    #[test]
    fn gray8_to_rgb8() {
        let dst = convert_pixel(
            PixelDescriptor::GRAY8_SRGB,
            PixelDescriptor::RGB8_SRGB,
            &[128],
        );
        assert_eq!(dst, [128, 128, 128]);
    }

    #[test]
    fn gray8_to_rgba8() {
        let dst = convert_pixel(
            PixelDescriptor::GRAY8_SRGB,
            PixelDescriptor::RGBA8_SRGB,
            &[200],
        );
        assert_eq!(dst, [200, 200, 200, 255]);
    }

    #[test]
    fn gray8_to_bgra8() {
        // Gray → RGBA → BGRA (two-step).
        let dst = convert_pixel(
            PixelDescriptor::GRAY8_SRGB,
            PixelDescriptor::BGRA8_SRGB,
            &[128],
        );
        // Gray broadcasts to (128,128,128) then swizzles — all same so still (128,128,128,255).
        assert_eq!(dst, [128, 128, 128, 255]);
    }

    #[test]
    fn rgb8_to_gray8() {
        // BT.709 luma: (54*R + 183*G + 19*B + 128) >> 8
        let dst = convert_pixel(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::GRAY8_SRGB,
            &[255, 0, 0],
        );
        // (54*255 + 0 + 0 + 128) >> 8 = (13770 + 128) >> 8 = 13898 >> 8 = 54
        assert_eq!(dst, [54]);
    }

    #[test]
    fn rgba8_to_gray8() {
        let dst = convert_pixel(
            PixelDescriptor::RGBA8_SRGB,
            PixelDescriptor::GRAY8_SRGB,
            &[0, 255, 0, 255],
        );
        // (0 + 183*255 + 0 + 128) >> 8 = (46665 + 128) >> 8 = 46793 >> 8 = 182
        assert_eq!(dst, [182]);
    }

    #[test]
    fn bgra8_to_gray8() {
        // BGRA → RGBA → Gray (two-step).
        let dst = convert_pixel(
            PixelDescriptor::BGRA8_SRGB,
            PixelDescriptor::GRAY8_SRGB,
            &[0, 255, 0, 255], // BGRA: B=0, G=255, R=0
        );
        // After swizzle: RGBA = [0, 255, 0, 255], then gray = 182.
        assert_eq!(dst, [182]);
    }

    // -----------------------------------------------------------------------
    // GrayAlpha conversions
    // -----------------------------------------------------------------------

    #[test]
    fn gray8_to_grayalpha8() {
        let from = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Gray,
            None,
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, to, &[100]);
        assert_eq!(dst, [100, 255]);
    }

    #[test]
    fn grayalpha8_to_gray8() {
        let from = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Gray,
            None,
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, to, &[100, 200]);
        assert_eq!(dst, [100]); // Alpha dropped.
    }

    #[test]
    fn grayalpha8_to_rgba8() {
        let from = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, PixelDescriptor::RGBA8_SRGB, &[128, 200]);
        assert_eq!(dst, [128, 128, 128, 200]);
    }

    #[test]
    fn grayalpha8_to_rgb8() {
        let from = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, PixelDescriptor::RGB8_SRGB, &[128, 200]);
        assert_eq!(dst, [128, 128, 128]);
    }

    #[test]
    fn grayalpha8_to_bgra8() {
        // GrayAlpha → RGBA → BGRA (two-step).
        let from = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, PixelDescriptor::BGRA8_SRGB, &[128, 200]);
        // Gray broadcasts to (128,128,128,200) then BGRA swizzle — all same so (128,128,128,200).
        assert_eq!(dst, [128, 128, 128, 200]);
    }

    // -----------------------------------------------------------------------
    // Depth conversions
    // -----------------------------------------------------------------------

    #[test]
    fn u8_to_u16_roundtrip() {
        let u8_desc = PixelDescriptor::RGB8_SRGB;
        let u16_desc = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let src = [0u8, 128, 255];
        let wide = convert_pixel(u8_desc, u16_desc, &src);
        let wide16: &[u16] = bytemuck::cast_slice(&wide);
        assert_eq!(wide16[0], 0); // 0 * 257 = 0
        assert_eq!(wide16[1], 128 * 257); // 32896
        assert_eq!(wide16[2], 255 * 257); // 65535

        // Narrow back to u8.
        let narrow = convert_pixel(u16_desc, u8_desc, &wide);
        assert_eq!(narrow, [0, 128, 255]);
    }

    #[test]
    fn naive_u8_to_f32() {
        // Non-sRGB transfer → naive path.
        let u8_desc = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let f32_desc = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let dst = convert_pixel(u8_desc, f32_desc, &[0, 128, 255]);
        let f: &[f32] = bytemuck::cast_slice(&dst);
        assert!((f[0] - 0.0).abs() < 1e-6);
        assert!((f[1] - 128.0 / 255.0).abs() < 1e-5);
        assert!((f[2] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn naive_f32_to_u8() {
        let f32_desc = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let u8_desc = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 3] = [0.0, 0.5, 1.0];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(f32_desc, u8_desc, src);
        assert_eq!(dst[0], 0);
        assert_eq!(dst[1], 128); // 0.5 * 255 + 0.5 = 128.0 → 128
        assert_eq!(dst[2], 255);
    }

    #[test]
    fn srgb_u8_to_linear_f32() {
        let dst = convert_pixel(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::new(
                ChannelType::F32,
                ChannelLayout::Rgb,
                None,
                TransferFunction::Linear,
            ),
            &[0, 128, 255],
        );
        let f: &[f32] = bytemuck::cast_slice(&dst);
        assert!((f[0] - 0.0).abs() < 1e-6);
        // sRGB 128/255 ≈ 0.2158 linear
        assert!((f[1] - 0.2158).abs() < 0.01);
        assert!((f[2] - 1.0).abs() < 1e-5);
    }

    #[test]
    fn linear_f32_to_srgb_u8() {
        let f32_lin = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 3] = [0.0, 0.5, 1.0];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(f32_lin, PixelDescriptor::RGB8_SRGB, src);
        assert_eq!(dst[0], 0);
        // linear 0.5 ≈ sRGB 188
        assert!((dst[1] as i32 - 188).abs() <= 1);
        assert_eq!(dst[2], 255);
    }

    #[test]
    fn u16_to_f32_and_back() {
        let u16_desc = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let f32_desc = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let src16: [u16; 3] = [0, 32768, 65535];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let mid = convert_pixel(u16_desc, f32_desc, src);
        let f: &[f32] = bytemuck::cast_slice(&mid);
        assert!((f[0] - 0.0).abs() < 1e-6);
        assert!((f[1] - 0.5000076).abs() < 1e-4);
        assert!((f[2] - 1.0).abs() < 1e-6);

        // Round-trip back.
        let back = convert_pixel(f32_desc, u16_desc, &mid);
        let back16: &[u16] = bytemuck::cast_slice(&back);
        assert_eq!(back16[0], 0);
        assert!((back16[1] as i32 - 32768).abs() <= 1);
        assert_eq!(back16[2], 65535);
    }

    // -----------------------------------------------------------------------
    // HDR transfer function conversions
    // -----------------------------------------------------------------------

    #[test]
    fn pq_u16_to_linear_f32_roundtrip() {
        let pq_u16 = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Pq,
        );
        let lin_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src16: [u16; 3] = [0, 32768, 65535];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let mid = convert_pixel(pq_u16, lin_f32, src);
        let f: &[f32] = bytemuck::cast_slice(&mid);
        assert_eq!(f[0], 0.0);
        assert!(f[1] > 0.0 && f[1] < 1.0);

        // Round-trip.
        let back = convert_pixel(lin_f32, pq_u16, &mid);
        let back16: &[u16] = bytemuck::cast_slice(&back);
        assert_eq!(back16[0], 0);
        assert!((back16[1] as i32 - 32768).abs() <= 2);
    }

    #[test]
    fn pq_f32_to_linear_f32_roundtrip() {
        let pq_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Pq,
        );
        let lin_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 3] = [0.0, 0.5, 1.0];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let mid = convert_pixel(pq_f32, lin_f32, src);
        let back = convert_pixel(lin_f32, pq_f32, &mid);
        let back_f: &[f32] = bytemuck::cast_slice(&back);
        for i in 0..3 {
            assert!(
                (back_f[i] - src_f[i]).abs() < 1e-4,
                "PQ F32 roundtrip ch{i}: {:.6} vs {:.6}",
                back_f[i],
                src_f[i]
            );
        }
    }

    #[test]
    fn hlg_u16_to_linear_f32_roundtrip() {
        let hlg_u16 = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Hlg,
        );
        let lin_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src16: [u16; 3] = [0, 32768, 65535];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let mid = convert_pixel(hlg_u16, lin_f32, src);
        let f: &[f32] = bytemuck::cast_slice(&mid);
        assert_eq!(f[0], 0.0);
        assert!(f[1] > 0.0);

        let back = convert_pixel(lin_f32, hlg_u16, &mid);
        let back16: &[u16] = bytemuck::cast_slice(&back);
        assert_eq!(back16[0], 0);
        assert!((back16[1] as i32 - 32768).abs() <= 2);
    }

    #[test]
    fn hlg_f32_to_linear_f32_roundtrip() {
        let hlg_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Hlg,
        );
        let lin_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 3] = [0.0, 0.5, 1.0];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let mid = convert_pixel(hlg_f32, lin_f32, src);
        let back = convert_pixel(lin_f32, hlg_f32, &mid);
        let back_f: &[f32] = bytemuck::cast_slice(&back);
        for i in 0..3 {
            assert!(
                (back_f[i] - src_f[i]).abs() < 1e-4,
                "HLG F32 roundtrip ch{i}: {:.6} vs {:.6}",
                back_f[i],
                src_f[i]
            );
        }
    }

    #[test]
    fn pq_to_hlg_via_linear_f32() {
        let pq = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Pq,
        );
        let hlg = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Hlg,
        );
        let src_f: [f32; 3] = [0.0, 0.5, 1.0];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(pq, hlg, src);
        let f: &[f32] = bytemuck::cast_slice(&dst);
        // PQ 0 → HLG 0.
        assert_eq!(f[0], 0.0);
        // PQ 0.5 → some HLG value.
        assert!(f[1] > 0.0 && f[1] <= 1.0);
    }

    #[test]
    fn hdr_u16_to_sdr_u8_pq() {
        // PQ U16 → sRGB U8 (two-step: EOTF + OETF).
        let pq_u16 = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Pq,
        );
        let src16: [u16; 3] = [32768, 32768, 32768];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(pq_u16, PixelDescriptor::RGB8_SRGB, src);
        // Should produce some valid sRGB value.
        assert!(dst[0] > 0 && dst[0] < 255);
    }

    #[test]
    fn hdr_u16_to_sdr_u8_hlg() {
        let hlg_u16 = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Hlg,
        );
        let src16: [u16; 3] = [32768, 32768, 32768];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(hlg_u16, PixelDescriptor::RGB8_SRGB, src);
        assert!(dst[0] > 0 && dst[0] < 255);
    }

    // -----------------------------------------------------------------------
    // Alpha premultiplication
    // -----------------------------------------------------------------------

    #[test]
    fn straight_to_premul_u8() {
        let straight = PixelDescriptor::RGBA8_SRGB;
        let premul = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Rgba,
            Some(AlphaMode::Premultiplied),
            TransferFunction::Srgb,
        );
        // 50% alpha: RGB channels halved.
        let dst = convert_pixel(straight, premul, &[200, 100, 50, 128]);
        // (200 * 128 + 128) / 255 = 100, (100 * 128 + 128) / 255 = 50, (50 * 128 + 128) / 255 = 25
        assert!((dst[0] as i32 - 100).abs() <= 1);
        assert!((dst[1] as i32 - 50).abs() <= 1);
        assert!((dst[2] as i32 - 25).abs() <= 1);
        assert_eq!(dst[3], 128);
    }

    #[test]
    fn premul_to_straight_u8() {
        let premul = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Rgba,
            Some(AlphaMode::Premultiplied),
            TransferFunction::Srgb,
        );
        let straight = PixelDescriptor::RGBA8_SRGB;
        // Premul with alpha=128: channels are already halved.
        let dst = convert_pixel(premul, straight, &[100, 50, 25, 128]);
        // Unpremultiply: (100 * 255 + 64) / 128 = 199, etc.
        assert!((dst[0] as i32 - 200).abs() <= 1);
        assert!((dst[1] as i32 - 100).abs() <= 1);
        assert!((dst[2] as i32 - 50).abs() <= 1);
        assert_eq!(dst[3], 128);
    }

    #[test]
    fn premul_to_straight_zero_alpha() {
        let premul = PixelDescriptor::new(
            ChannelType::U8,
            ChannelLayout::Rgba,
            Some(AlphaMode::Premultiplied),
            TransferFunction::Srgb,
        );
        let straight = PixelDescriptor::RGBA8_SRGB;
        let dst = convert_pixel(premul, straight, &[0, 0, 0, 0]);
        assert_eq!(dst, [0, 0, 0, 0]);
    }

    #[test]
    fn straight_to_premul_f32() {
        let straight = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let premul = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Premultiplied),
            TransferFunction::Linear,
        );
        let src_f: [f32; 4] = [1.0, 0.5, 0.25, 0.5];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(straight, premul, src);
        let f: &[f32] = bytemuck::cast_slice(&dst);
        assert!((f[0] - 0.5).abs() < 1e-6);
        assert!((f[1] - 0.25).abs() < 1e-6);
        assert!((f[2] - 0.125).abs() < 1e-6);
        assert!((f[3] - 0.5).abs() < 1e-6);
    }

    // -----------------------------------------------------------------------
    // Oklab conversions
    // -----------------------------------------------------------------------

    #[test]
    fn rgb8_to_oklabf32_does_not_panic() {
        let mut conv =
            RowConverter::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::OKLABF32).unwrap();
        assert!(!conv.is_identity());

        let src = [128u8, 64, 200];
        let mut dst = [0u8; 12];
        conv.convert_row(&src, &mut dst, 1);

        let oklab: [f32; 3] = bytemuck::cast(dst);
        assert!(
            oklab[0] >= 0.0 && oklab[0] <= 1.0,
            "L out of range: {}",
            oklab[0]
        );
    }

    #[test]
    fn oklabf32_roundtrip() {
        // Linear RGB F32 → Oklab F32 → Linear RGB F32.
        let lin = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let oklab = PixelDescriptor::OKLABF32;

        let src_f: [f32; 3] = [0.5, 0.3, 0.8];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let mid = convert_pixel(lin, oklab, src);
        let back = convert_pixel(oklab, lin, &mid);
        let back_f: &[f32] = bytemuck::cast_slice(&back);
        for i in 0..3 {
            assert!(
                (back_f[i] - src_f[i]).abs() < 1e-4,
                "Oklab roundtrip ch{i}: {:.6} vs {:.6}",
                back_f[i],
                src_f[i]
            );
        }
    }

    #[test]
    fn oklabaf32_preserves_alpha() {
        let lin_rgba = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let oklaba = PixelDescriptor::OKLABAF32;
        let src_f: [f32; 4] = [0.5, 0.3, 0.8, 0.7];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let mid = convert_pixel(lin_rgba, oklaba, src);
        let mid_f: &[f32] = bytemuck::cast_slice(&mid);
        assert!(
            (mid_f[3] - 0.7).abs() < 1e-6,
            "Alpha not preserved in Oklaba"
        );

        let back = convert_pixel(oklaba, lin_rgba, &mid);
        let back_f: &[f32] = bytemuck::cast_slice(&back);
        assert!(
            (back_f[3] - 0.7).abs() < 1e-6,
            "Alpha not preserved on round-trip"
        );
        for i in 0..3 {
            assert!(
                (back_f[i] - src_f[i]).abs() < 1e-4,
                "Oklaba roundtrip ch{i}: {:.6} vs {:.6}",
                back_f[i],
                src_f[i]
            );
        }
    }

    // -----------------------------------------------------------------------
    // Multi-row conversion
    // -----------------------------------------------------------------------

    #[test]
    fn convert_rows_basic() {
        let mut conv =
            RowConverter::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::RGBA8_SRGB).unwrap();

        let src = [10u8, 20, 30, 40, 50, 60];
        let src_stride = 3; // tight, 1 pixel per row
        let mut dst = [0u8; 8]; // 2 rows × 4 bytes
        let dst_stride = 4;

        conv.convert_rows(&src, src_stride, &mut dst, dst_stride, 1, 2)
            .unwrap();
        assert_eq!(&dst[0..4], &[10, 20, 30, 255]);
        assert_eq!(&dst[4..8], &[40, 50, 60, 255]);
    }

    #[test]
    fn convert_rows_buffer_too_small() {
        let mut conv =
            RowConverter::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::RGBA8_SRGB).unwrap();

        let src = [10u8, 20, 30];
        let mut dst = [0u8; 4];
        let err = conv.convert_rows(&src, 3, &mut dst, 4, 1, 2).unwrap_err();
        assert!(matches!(*err.error(), ConvertError::BufferSize { .. }));
    }

    // -----------------------------------------------------------------------
    // ConvertPlan::new_explicit policy checks
    // -----------------------------------------------------------------------

    #[test]
    fn new_explicit_alpha_forbid() {
        let from = PixelDescriptor::RGBA8_SRGB;
        let to = PixelDescriptor::RGB8_SRGB;
        let opts = ConvertOptions::forbid_lossy().with_depth_policy(DepthPolicy::Round);
        let err = ConvertPlan::new_explicit(from, to, &opts).unwrap_err();
        assert_eq!(*err.error(), ConvertError::AlphaRemovalForbidden);
    }

    #[test]
    fn new_explicit_depth_forbid() {
        let from = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::RGB8_SRGB;
        let opts = ConvertOptions::forbid_lossy().with_alpha_policy(AlphaPolicy::DiscardUnchecked);
        let err = ConvertPlan::new_explicit(from, to, &opts).unwrap_err();
        assert_eq!(*err.error(), ConvertError::DepthReductionForbidden);
    }

    #[test]
    fn new_explicit_rgb_to_gray_requires_luma() {
        let opts = ConvertOptions::forbid_lossy()
            .with_alpha_policy(AlphaPolicy::DiscardUnchecked)
            .with_depth_policy(DepthPolicy::Round);
        let err = ConvertPlan::new_explicit(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::GRAY8_SRGB,
            &opts,
        )
        .unwrap_err();
        assert_eq!(*err.error(), ConvertError::RgbToGray);
    }

    #[test]
    fn new_explicit_allows_when_policies_permit() {
        let opts = ConvertOptions::permissive().with_alpha_policy(AlphaPolicy::DiscardUnchecked);
        let plan = ConvertPlan::new_explicit(
            PixelDescriptor::RGBA8_SRGB,
            PixelDescriptor::GRAY8_SRGB,
            &opts,
        )
        .unwrap();
        assert!(!plan.is_identity());
    }

    #[test]
    fn clip_out_of_gamut_false_preserves_negatives() {
        // P3 pure green → sRGB produces negative red (out of sRGB gamut).
        // With clip_out_of_gamut=false, the extended-range transfer must
        // preserve those negatives instead of clamping to zero.
        let p3 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        )
        .with_primaries(zenpixels::ColorPrimaries::DisplayP3);
        let srgb = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );

        let opts = ConvertOptions::permissive().with_clip_out_of_gamut(false);
        let mut conv = crate::RowConverter::new_explicit(p3, srgb, &opts).unwrap();

        let src: [f32; 3] = [0.0, 1.0, 0.0];
        let mut dst = [0.0f32; 3];
        conv.convert_row(
            bytemuck::cast_slice(&src),
            bytemuck::cast_slice_mut(&mut dst),
            1,
        );
        assert!(
            dst[0] < 0.0,
            "extended range should preserve negative red, got {}",
            dst[0]
        );
    }

    #[test]
    fn clip_out_of_gamut_true_clamps_negatives() {
        // Default clip_out_of_gamut=true clamps sRGB transfer to [0, 1].
        let p3 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        )
        .with_primaries(zenpixels::ColorPrimaries::DisplayP3);
        let srgb = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );

        let opts = ConvertOptions::permissive();
        assert!(opts.clip_out_of_gamut);
        let mut conv = crate::RowConverter::new_explicit(p3, srgb, &opts).unwrap();

        let src: [f32; 3] = [0.0, 1.0, 0.0];
        let mut dst = [0.0f32; 3];
        conv.convert_row(
            bytemuck::cast_slice(&src),
            bytemuck::cast_slice_mut(&mut dst),
            1,
        );
        assert!(
            dst[0] >= 0.0,
            "clamped path should not produce negatives, got {}",
            dst[0]
        );
    }

    // -----------------------------------------------------------------------
    // Pluggable CMS
    // -----------------------------------------------------------------------

    /// Mock CMS that paints every output pixel red. Used to verify that the
    /// plugin gets hooked into the plan and actually drives the row.
    struct PaintRedCms {
        accepted: core::sync::atomic::AtomicUsize,
    }

    struct PaintRedTransform;

    impl crate::cms::RowTransformMut for PaintRedTransform {
        fn transform_row(&mut self, _src: &[u8], dst: &mut [u8], width: u32) {
            for px in dst.chunks_exact_mut(3).take(width as usize) {
                px[0] = 255;
                px[1] = 0;
                px[2] = 0;
            }
        }
    }

    impl crate::cms::PluggableCms for PaintRedCms {
        fn build_source_transform(
            &self,
            _src: zenpixels::ColorProfileSource<'_>,
            _dst: zenpixels::ColorProfileSource<'_>,
            _src_format: zenpixels::PixelFormat,
            _dst_format: zenpixels::PixelFormat,
            _options: &crate::policy::ConvertOptions,
        ) -> Option<
            Result<Box<dyn crate::cms::RowTransformMut>, whereat::At<crate::cms::CmsPluginError>>,
        > {
            self.accepted
                .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
            Some(Ok(Box::new(PaintRedTransform)))
        }
    }

    #[test]
    fn pluggable_cms_drives_row_when_profiles_differ() {
        // P3 RGB8 → sRGB RGB8: profiles differ, plugin must be asked and
        // its transform must be the one that runs.
        let p3 = PixelDescriptor::RGB8_SRGB.with_primaries(zenpixels::ColorPrimaries::DisplayP3);
        let srgb = PixelDescriptor::RGB8_SRGB;

        let cms = PaintRedCms {
            accepted: core::sync::atomic::AtomicUsize::new(0),
        };
        let opts = ConvertOptions::permissive();
        let mut conv =
            crate::RowConverter::new_explicit_with_cms(p3, srgb, &opts, Some(&cms)).unwrap();

        assert_eq!(cms.accepted.load(core::sync::atomic::Ordering::Relaxed), 1);

        let src = [10u8, 20, 30, 40, 50, 60];
        let mut dst = [0u8; 6];
        conv.convert_row(&src, &mut dst, 2);
        assert_eq!(dst, [255, 0, 0, 255, 0, 0]);
    }

    #[test]
    fn pluggable_cms_skipped_when_profiles_match() {
        // Same profile on both sides — plan is identity, plugin is never
        // consulted.
        let cms = PaintRedCms {
            accepted: core::sync::atomic::AtomicUsize::new(0),
        };
        let opts = ConvertOptions::permissive();
        let conv = crate::RowConverter::new_explicit_with_cms(
            PixelDescriptor::RGB8_SRGB,
            PixelDescriptor::RGB8_SRGB,
            &opts,
            Some(&cms),
        )
        .unwrap();
        assert!(conv.is_identity());
        assert_eq!(cms.accepted.load(core::sync::atomic::Ordering::Relaxed), 0);
    }

    #[test]
    fn pluggable_cms_shared_path_used_when_offered() {
        // Plugin offers a shareable stateless transform — RowConverter
        // must pick that path over the owned one.
        struct SharedPaintBlueCms;
        struct PaintBlueShared;

        impl crate::cms::RowTransform for PaintBlueShared {
            fn transform_row(&self, _src: &[u8], dst: &mut [u8], width: u32) {
                for px in dst.chunks_exact_mut(3).take(width as usize) {
                    px[0] = 0;
                    px[1] = 0;
                    px[2] = 255;
                }
            }
        }

        impl crate::cms::PluggableCms for SharedPaintBlueCms {
            fn build_source_transform(
                &self,
                _src: zenpixels::ColorProfileSource<'_>,
                _dst: zenpixels::ColorProfileSource<'_>,
                _src_format: zenpixels::PixelFormat,
                _dst_format: zenpixels::PixelFormat,
                _options: &crate::policy::ConvertOptions,
            ) -> Option<
                Result<
                    Box<dyn crate::cms::RowTransformMut>,
                    whereat::At<crate::cms::CmsPluginError>,
                >,
            > {
                panic!("owned path must not be used when shared is offered");
            }

            fn build_shared_source_transform(
                &self,
                _src: zenpixels::ColorProfileSource<'_>,
                _dst: zenpixels::ColorProfileSource<'_>,
                _src_format: zenpixels::PixelFormat,
                _dst_format: zenpixels::PixelFormat,
                _options: &crate::policy::ConvertOptions,
            ) -> Option<
                Result<
                    alloc::sync::Arc<dyn crate::cms::RowTransform>,
                    whereat::At<crate::cms::CmsPluginError>,
                >,
            > {
                Some(Ok(alloc::sync::Arc::new(PaintBlueShared)))
            }
        }

        let p3 = PixelDescriptor::RGB8_SRGB.with_primaries(zenpixels::ColorPrimaries::DisplayP3);
        let srgb = PixelDescriptor::RGB8_SRGB;
        let opts = ConvertOptions::permissive();
        let conv =
            crate::RowConverter::new_explicit_with_cms(p3, srgb, &opts, Some(&SharedPaintBlueCms))
                .unwrap();

        // Clone must carry the shared transform (via Arc).
        let mut conv2 = conv.clone();
        let mut dst = [0u8; 3];
        conv2.convert_row(&[1, 2, 3], &mut dst, 1);
        assert_eq!(
            dst,
            [0, 0, 255],
            "cloned converter should inherit shared transform"
        );
    }

    #[test]
    fn pluggable_cms_declines_falls_back_to_builtin() {
        // Plugin returns None — must fall back to the built-in gamut path.
        struct DeclineCms;
        impl crate::cms::PluggableCms for DeclineCms {
            fn build_source_transform(
                &self,
                _src: zenpixels::ColorProfileSource<'_>,
                _dst: zenpixels::ColorProfileSource<'_>,
                _src_format: zenpixels::PixelFormat,
                _dst_format: zenpixels::PixelFormat,
                _options: &crate::policy::ConvertOptions,
            ) -> Option<
                Result<
                    Box<dyn crate::cms::RowTransformMut>,
                    whereat::At<crate::cms::CmsPluginError>,
                >,
            > {
                None
            }
        }

        let p3 = PixelDescriptor::RGB8_SRGB.with_primaries(zenpixels::ColorPrimaries::DisplayP3);
        let srgb = PixelDescriptor::RGB8_SRGB;
        let opts = ConvertOptions::permissive();
        let mut conv =
            crate::RowConverter::new_explicit_with_cms(p3, srgb, &opts, Some(&DeclineCms)).unwrap();

        // Built-in path should produce non-red output from grey source.
        let src = [128u8, 128, 128];
        let mut dst = [0u8; 3];
        conv.convert_row(&src, &mut dst, 1);
        // P3 grey → sRGB grey: R ≈ G ≈ B. Not the all-red sentinel the
        // plugin would have written, proving we took the built-in path.
        assert_ne!(dst, [255, 0, 0]);
    }

    // -----------------------------------------------------------------------
    // Plan accessors
    // -----------------------------------------------------------------------

    #[test]
    fn plan_accessors() {
        let from = PixelDescriptor::RGB8_SRGB;
        let to = PixelDescriptor::RGBA8_SRGB;
        let conv = RowConverter::new(from, to).unwrap();
        let plan = conv.plan();
        assert_eq!(plan.from(), from);
        assert_eq!(plan.to(), to);
        assert!(!plan.is_identity());
    }

    #[test]
    fn from_plan() {
        let plan =
            ConvertPlan::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::RGBA8_SRGB).unwrap();
        let conv = RowConverter::from_plan(plan);
        assert!(!conv.is_identity());
    }

    // -----------------------------------------------------------------------
    // Multi-pixel conversion
    // -----------------------------------------------------------------------

    #[test]
    fn convert_multiple_pixels() {
        let mut conv =
            RowConverter::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::RGBA8_SRGB).unwrap();
        let src = [10, 20, 30, 40, 50, 60, 70, 80, 90];
        let mut dst = [0u8; 12];
        conv.convert_row(&src, &mut dst, 3);
        assert_eq!(dst, [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255]);
    }

    // -----------------------------------------------------------------------
    // Combined layout + depth conversions
    // -----------------------------------------------------------------------

    #[test]
    fn gray8_to_rgbaf32_linear() {
        // Gray U8 sRGB → RGBA F32 Linear: depth expands, then layout expands.
        let from = PixelDescriptor::GRAY8_SRGB;
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let dst = convert_pixel(from, to, &[128]);
        let f: &[f32] = bytemuck::cast_slice(&dst);
        // sRGB 128 ≈ linear 0.2158, broadcasted, alpha = 1.0.
        assert!((f[0] - 0.2158).abs() < 0.01);
        assert!((f[0] - f[1]).abs() < 1e-6);
        assert!((f[0] - f[2]).abs() < 1e-6);
        assert!((f[3] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn rgba8_to_rgb16() {
        // Layout contracts (drop alpha), then depth expands.
        let from = PixelDescriptor::RGBA8_SRGB;
        let to = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let dst = convert_pixel(from, to, &[100, 150, 200, 255]);
        let u16s: &[u16] = bytemuck::cast_slice(&dst);
        assert_eq!(u16s[0], 100 * 257);
        assert_eq!(u16s[1], 150 * 257);
        assert_eq!(u16s[2], 200 * 257);
    }

    // -----------------------------------------------------------------------
    // U16 and F32 layout conversion kernels
    // -----------------------------------------------------------------------

    #[test]
    fn gray_u16_to_rgb_u16() {
        let from = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Gray,
            None,
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let src16: [u16; 1] = [40000];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(from, to, src);
        let out: &[u16] = bytemuck::cast_slice(&dst);
        assert_eq!(out, [40000, 40000, 40000]);
    }

    #[test]
    fn gray_f32_to_rgba_f32() {
        let from = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Gray,
            None,
            TransferFunction::Linear,
        );
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let src_f: [f32; 1] = [0.6];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(from, to, src);
        let out: &[f32] = bytemuck::cast_slice(&dst);
        assert!((out[0] - 0.6).abs() < 1e-6);
        assert!((out[1] - 0.6).abs() < 1e-6);
        assert!((out[2] - 0.6).abs() < 1e-6);
        assert!((out[3] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn rgb_f32_to_rgba_f32() {
        let from = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let src_f: [f32; 3] = [0.2, 0.4, 0.8];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(from, to, src);
        let out: &[f32] = bytemuck::cast_slice(&dst);
        assert!((out[0] - 0.2).abs() < 1e-6);
        assert!((out[1] - 0.4).abs() < 1e-6);
        assert!((out[2] - 0.8).abs() < 1e-6);
        assert!((out[3] - 1.0).abs() < 1e-6);
    }

    #[test]
    fn rgba_u16_to_rgb_u16() {
        let from = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Srgb,
        );
        let src16: [u16; 4] = [10000, 20000, 30000, 65535];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(from, to, src);
        let out: &[u16] = bytemuck::cast_slice(&dst);
        assert_eq!(out, [10000, 20000, 30000]);
    }

    #[test]
    fn gray_alpha_u16_to_rgba_u16() {
        let from = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let src16: [u16; 2] = [50000, 32768];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(from, to, src);
        let out: &[u16] = bytemuck::cast_slice(&dst);
        assert_eq!(out, [50000, 50000, 50000, 32768]);
    }

    #[test]
    fn gray_alpha_f32_to_rgb_f32() {
        let from = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 2] = [0.75, 0.5];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(from, to, src);
        let out: &[f32] = bytemuck::cast_slice(&dst);
        assert!((out[0] - 0.75).abs() < 1e-6);
        assert!((out[1] - 0.75).abs() < 1e-6);
        assert!((out[2] - 0.75).abs() < 1e-6);
    }

    #[test]
    fn gray_u16_to_gray_alpha_u16() {
        let from = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::Gray,
            None,
            TransferFunction::Srgb,
        );
        let to = PixelDescriptor::new(
            ChannelType::U16,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let src16: [u16; 1] = [12345];
        let src: &[u8] = bytemuck::cast_slice(&src16);
        let dst = convert_pixel(from, to, src);
        let out: &[u16] = bytemuck::cast_slice(&dst);
        assert_eq!(out, [12345, 65535]);
    }

    #[test]
    fn gray_alpha_f32_to_gray_f32() {
        let from = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::GrayAlpha,
            Some(AlphaMode::Straight),
            TransferFunction::Linear,
        );
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Gray,
            None,
            TransferFunction::Linear,
        );
        let src_f: [f32; 2] = [0.33, 0.9];
        let src: &[u8] = bytemuck::cast_slice(&src_f);
        let dst = convert_pixel(from, to, src);
        let out: &[f32] = bytemuck::cast_slice(&dst);
        assert!((out[0] - 0.33).abs() < 1e-6);
    }

    // -----------------------------------------------------------------------
    // Transfer function roundtrips (ext.rs branches)
    // -----------------------------------------------------------------------

    #[test]
    fn bt709_linear_f32_roundtrip() {
        use crate::TransferFunctionExt;
        let tf = TransferFunction::Bt709;
        let values = [0.0f32, 0.1, 0.25, 0.5, 0.75, 1.0];
        for &v in &values {
            let linear = tf.linearize(v);
            let back = tf.delinearize(linear);
            assert!(
                (back - v).abs() < 1e-5,
                "Bt709 roundtrip failed for {v}: linearize={linear}, delinearize={back}"
            );
        }
    }

    #[test]
    fn unknown_transfer_roundtrip() {
        use crate::TransferFunctionExt;
        let tf = TransferFunction::Unknown;
        let values = [0.0f32, 0.1, 0.5, 0.99, 1.0];
        for &v in &values {
            let linear = tf.linearize(v);
            assert!(
                (linear - v).abs() < 1e-7,
                "Unknown linearize should be identity: {v} -> {linear}"
            );
            let back = tf.delinearize(linear);
            assert!(
                (back - v).abs() < 1e-7,
                "Unknown delinearize should be identity: {linear} -> {back}"
            );
        }
    }

    #[test]
    fn oklab_unknown_primaries_returns_error() {
        use crate::ColorPrimaries;
        let from = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgb,
            None,
            TransferFunction::Linear,
        )
        .with_primaries(ColorPrimaries::Unknown);
        let to = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Oklab,
            None,
            TransferFunction::Linear,
        )
        .with_primaries(ColorPrimaries::Unknown);
        let result = RowConverter::new(from, to);
        assert!(result.is_err(), "Oklab with Unknown primaries should fail");
    }

    // -----------------------------------------------------------------------
    // Compose
    // -----------------------------------------------------------------------

    #[test]
    fn compose_roundtrip_cancels_to_identity() {
        let a = RowConverter::new(PixelDescriptor::RGBA8_SRGB, PixelDescriptor::RGBAF32_LINEAR)
            .unwrap();
        let b = RowConverter::new(PixelDescriptor::RGBAF32_LINEAR, PixelDescriptor::RGBA8_SRGB)
            .unwrap();
        let composed = a.compose(&b).unwrap();
        assert!(composed.is_identity(), "sRGB→linear→sRGB should cancel");
    }

    #[test]
    fn compose_chain_reduces_steps() {
        // RGBA8 sRGB → RGBAF32 linear → RGBAF32 sRGB
        // Steps: SrgbU8ToLinearF32 then LinearF32ToSrgbF32
        // The sRGB→linear step from plan A and linear→sRGB from plan B
        // should NOT cancel (different depth target), but composing avoids
        // an intermediate allocation.
        let a = RowConverter::new(PixelDescriptor::RGBA8_SRGB, PixelDescriptor::RGBAF32_LINEAR)
            .unwrap();
        let srgb_f32 = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Straight),
            TransferFunction::Srgb,
        );
        let b = RowConverter::new(PixelDescriptor::RGBAF32_LINEAR, srgb_f32).unwrap();
        let composed = a.compose(&b).unwrap();
        assert!(!composed.is_identity());
        assert_eq!(composed.from_descriptor(), PixelDescriptor::RGBA8_SRGB);
        assert_eq!(composed.to_descriptor(), srgb_f32);
    }

    #[test]
    fn compose_incompatible_returns_none() {
        let a = RowConverter::new(PixelDescriptor::RGBA8_SRGB, PixelDescriptor::RGBAF32_LINEAR)
            .unwrap();
        let b = RowConverter::new(PixelDescriptor::RGB8_SRGB, PixelDescriptor::RGBA8_SRGB).unwrap();
        assert!(a.compose(&b).is_none(), "RGBAF32_LINEAR != RGB8_SRGB");
    }

    #[test]
    fn compose_premul_roundtrip_cancels() {
        let premul = PixelDescriptor::new(
            ChannelType::F32,
            ChannelLayout::Rgba,
            Some(AlphaMode::Premultiplied),
            TransferFunction::Linear,
        );
        let a = RowConverter::new(PixelDescriptor::RGBAF32_LINEAR, premul).unwrap();
        let b = RowConverter::new(premul, PixelDescriptor::RGBAF32_LINEAR).unwrap();
        let composed = a.compose(&b).unwrap();
        assert!(
            composed.is_identity(),
            "straight→premul→straight should cancel"
        );
    }

    // -----------------------------------------------------------------------
    // CMYK guard
    // -----------------------------------------------------------------------

    #[test]
    #[should_panic(expected = "CMYK pixel data cannot be processed")]
    fn cmyk_rejected_by_row_converter() {
        let _ = RowConverter::new(PixelDescriptor::CMYK8, PixelDescriptor::RGB8_SRGB);
    }
}