quercus-core 0.5.2

Rust value types mirroring quercuscore (Rational, TimeRange, format enums) (internal; do not depend directly)
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
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
// Quercus Video Editor - Non-Linear Video Editor
// Copyright (C) 2026 Quercus Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

//! Color processing: OCIO processors and the process-wide default config
//! (C++ `ColorProcessor` + `ColorManager` statics).
//!
//! Implemented over the `ocio-rs` crate (safe Rust bindings for
//! OpenColorIO v2.5.2, bundled real-OCIO build). OCIO is never rewritten —
//! this module maps the C++ call surface onto ocio-rs.

use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};

use crate::PixelFormat;

use crate::error::{Error, Result};
use crate::texture::Frame;

/// A color processor (wraps an OCIO processor). A processor whose OCIO
/// lookup failed holds `None` — conversions then pass through, mirroring
/// the C++ non-fatal creation behavior.
pub struct ColorProcessor {
	/// The OCIO processor (None = pass-through).
	inner: Option<ocio_rs::Processor>,
	/// The cached CPU processor used for pixel conversions (C++
	/// `cpu_processor_`).
	cpu: Option<ocio_rs::CPUProcessor>,
}

/// The R/B channel swap as a 4x4 matrix transform (baked around the
/// display chain so BGRA buffers can be transformed through OCIO's RGBA
/// entry points).
fn rb_swap_matrix() -> Option<ocio_rs::transform::MatrixTransform> {
	let m = ocio_rs::transform::MatrixTransform::create().ok()?;
	m.set_matrix(&[
		0.0, 0.0, 1.0, 0.0, //
		0.0, 1.0, 0.0, 0.0, //
		1.0, 0.0, 0.0, 0.0, //
		0.0, 0.0, 0.0, 1.0,
	])
	.ok()?;
	Some(m)
}

/// Processor direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {
	/// src -> dst.
	Normal,
	/// dst -> src.
	Inverse,
}

impl Direction {
	/// The ocio-rs transform direction for the swap already applied at the
	/// call site.
	fn to_ocio(self) -> ocio_rs::TransformDirection {
		match self {
			Direction::Normal => ocio_rs::TransformDirection::Forward,
			Direction::Inverse => ocio_rs::TransformDirection::Inverse,
		}
	}
}

// OCIO Config/Processor are refcounted handles over C++ objects that are
// thread-safe for CPU processing (the C++ ColorProcessor is shared across
// render threads the same way); the safe wrapper is Send+Sync.
unsafe impl Send for ColorProcessor {}
unsafe impl Sync for ColorProcessor {}

impl ColorProcessor {
	/// Create from two colorspace names on the default config
	/// (C++ `ColorProcessor::create(config, input, dest)`).
	///
	/// Role names (e.g. "scene_linear") are resolved to canonical names.
	/// OCIO failures are non-fatal: a processor with `inner == None` is
	/// returned and conversions pass through.
	pub fn create(src_space: &str, dst_transform: &str, dir: Direction) -> Option<Self> {
		let config = default_config()?;
		let src = if config.has_role(src_space) {
			config
				.canonical_name(src_space)
				.unwrap_or_else(|| src_space.to_string())
		} else {
			src_space.to_string()
		};

		let processor = match dir {
			Direction::Normal => config.processor(&src, dst_transform),
			Direction::Inverse => config.processor(dst_transform, &src),
		}
		.ok();
		let cpu = processor
			.as_ref()
			.and_then(|p| p.default_cpu_processor().ok());

		Some(Self {
			inner: processor,
			cpu,
		})
	}

	/// Create from a LUT file (C++ `create_lut` semantics): an OCIO
	/// FileTransform with linear interpolation on the default config.
	pub fn create_lut(path: &str, dir: Direction) -> Option<Self> {
		let config = default_config()?;
		let transform = ocio_rs::transform::FileTransform::create().ok()?;
		transform.set_src(path).ok()?;
		transform.set_interpolation(ocio_rs::Interpolation::Linear);
		transform.set_direction(dir.to_ocio());
		let processor = config
			.processor_from_transform(&transform, dir.to_ocio())
			.ok();
		let cpu = processor
			.as_ref()
			.and_then(|p| p.default_cpu_processor().ok());
		Some(Self {
			inner: processor,
			cpu,
		})
	}

	/// Create from a LUT file on a specific config (C++
	/// `ColorProcessor::create_lut` family with a ColorManager config).
	pub fn create_lut_on(config: &ocio_rs::Config, path: &str, dir: Direction) -> Option<Self> {
		let transform = ocio_rs::transform::FileTransform::create().ok()?;
		transform.set_src(path).ok()?;
		transform.set_interpolation(ocio_rs::Interpolation::Linear);
		transform.set_direction(dir.to_ocio());
		let processor = config
			.processor_from_transform(&transform, dir.to_ocio())
			.ok();
		let cpu = processor
			.as_ref()
			.and_then(|p| p.default_cpu_processor().ok());
		Some(Self {
			inner: processor,
			cpu,
		})
	}

	/// Create a dynamic grading-primary processor on the default config
	/// (C++ `ColorProcessor` grading-primary family).
	pub fn create_grading_primary(style: GradingStyle) -> Option<Self> {
		let config = default_config()?;
		let transform =
			ocio_rs::transform::GradingPrimaryTransform::create(style.to_ocio()).ok()?;
		transform.make_dynamic();
		transform.set_direction(ocio_rs::TransformDirection::Forward);
		let processor = config
			.processor_from_transform(&transform, ocio_rs::TransformDirection::Forward)
			.ok();
		let cpu = processor
			.as_ref()
			.and_then(|p| p.default_cpu_processor().ok());
		Some(Self {
			inner: processor,
			cpu,
		})
	}

	/// Create the display-output processor from a display ICC profile
	/// (macOS ColorSync / Windows ICM / Linux colord or `_ICC_PROFILE`).
	///
	/// OCIO's ICC reader (FileFormatICC, display-class profiles) builds the
	/// FileTransform's forward direction as "CIE XYZ (D65-adapted PCS) →
	/// device code values", so the chain is `<src_space> → linear Rec.709 →
	/// CIE XYZ D65 → ICC forward`. `src_space` is a colorspace or role of
	/// the default config (the pipeline reference, e.g. "scene_linear").
	pub fn create_display_icc(src_space: &str, icc_path: &str) -> Option<Self> {
		Self::create_display_icc_impl(src_space, icc_path, false)
	}

	/// Create the display-output processor for BGRA8 buffers (the viewer's
	/// wire format): the [`create_display_icc`](Self::create_display_icc)
	/// chain with R/B-swapping matrices baked around it, so BGRA bytes are
	/// transformed in place through OCIO's RGBA entry points (swap∘chain∘swap
	/// is the identity-wrapped chain evaluated on swapped channels).
	pub fn create_display_icc_bgra8(src_space: &str, icc_path: &str) -> Option<Self> {
		Self::create_display_icc_impl(src_space, icc_path, true)
	}

	/// Create the display-output processor for content the caller has already
	/// converted to CIE XYZ (D65, unit luminance) — the non-sRGB project
	/// output gamut path. [`create_display_icc`](Self::create_display_icc)
	/// starts from an OCIO named space (sRGB and friends); P3/BT.2020
	/// targets have no named space in the builtin configs, so the caller
	/// linearizes and gamut-maps to XYZ itself
	/// (`crate::colormath::output_spec_to_xyz_d65`) and this chain only
	/// needs the ICC half: it runs the existing builder with the config's
	/// `cie_xyz_d65_interchange` role as the source space (XYZ → linear
	/// Rec.709, whose inverse the builder's leg 2 immediately undoes — a
	/// no-op round trip, leaving the ICC FileTransform to map the XYZ PCS
	/// to device values).
	///
	/// Returns `None` (not a pass-through) when the chain cannot build — e.g.
	/// the config rejects the interchange role — so callers can fall back to
	/// the sRGB chain instead of silently mapping wrong content.
	pub fn create_display_icc_xyz(icc_path: &str) -> Option<Self> {
		Self::create_display_icc_xyz_impl(icc_path, false)
	}

	/// The [`create_display_icc_xyz`](Self::create_display_icc_xyz) chain
	/// with R/B-swapping matrices baked around it for BGRA8 buffers (see
	/// [`create_display_icc_bgra8`](Self::create_display_icc_bgra8)).
	pub fn create_display_icc_xyz_bgra8(icc_path: &str) -> Option<Self> {
		Self::create_display_icc_xyz_impl(icc_path, true)
	}

	fn create_display_icc_xyz_impl(icc_path: &str, bgra: bool) -> Option<Self> {
		let p = Self::create_display_icc_impl("cie_xyz_d65_interchange", icc_path, bgra)?;
		// A failed OCIO lookup yields a pass-through processor (the
		// non-fatal convention above); for the XYZ chain that must surface as
		// `None` so the caller can fall back to the sRGB degradation instead
		// of feeding XYZ values through a no-op.
		p.is_valid().then_some(p)
	}

	/// Shared builder: `bgra` wraps the chain in R/B swap matrices.
	fn create_display_icc_impl(src_space: &str, icc_path: &str, bgra: bool) -> Option<Self> {
		let config = default_config()?;
		// Leg 1: pipeline space -> linear Rec.709 (sRGB primaries, D65).
		let to_lin709 = ocio_rs::transform::ColorSpaceTransform::create().ok()?;
		to_lin709.set_src(src_space).ok()?;
		to_lin709.set_dst("Linear Rec.709 (sRGB)").ok()?;
		// Leg 2: linear Rec.709 -> CIE XYZ D65 (the ICC connection space as
		// OCIO's ICC reader adapts it, D50->D65 Bradford baked in). The
		// builtin configs carry no XYZ colorspace, so the conversion is an
		// explicit matrix (sRGB/Rec.709 primaries -> XYZ D65).
		let to_xyz = ocio_rs::transform::MatrixTransform::create().ok()?;
		to_xyz
			.set_matrix(&[
				0.4123908, 0.3575843, 0.1804808, 0.0, //
				0.2126390, 0.7151687, 0.0721923, 0.0, //
				0.0193308, 0.1191948, 0.9505322, 0.0, //
				0.0, 0.0, 0.0, 1.0,
			])
			.ok()?;
		// Leg 3: XYZ D65 -> device, per the ICC profile (OCIO's
		// FileFormatICC forward direction).
		let icc = ocio_rs::transform::FileTransform::create().ok()?;
		icc.set_src(icc_path).ok()?;
		icc.set_interpolation(ocio_rs::Interpolation::Linear);
		icc.set_direction(ocio_rs::TransformDirection::Forward);
		let group = ocio_rs::transform::GroupTransform::create().ok()?;
		if bgra {
			group.append_transform(&rb_swap_matrix()?).ok()?;
		}
		group.append_transform(&to_lin709).ok()?;
		group.append_transform(&to_xyz).ok()?;
		group.append_transform(&icc).ok()?;
		if bgra {
			group.append_transform(&rb_swap_matrix()?).ok()?;
		}
		let processor = config
			.processor_from_transform(&group, ocio_rs::TransformDirection::Forward)
			.ok();
		let cpu = processor
			.as_ref()
			.and_then(|p| p.default_cpu_processor().ok());
		Some(Self {
			inner: processor,
			cpu,
		})
	}

	/// Create from an explicit OCIO processor (C++
	/// `ColorProcessor::create(ConstProcessorRcPtr)`).
	pub fn from_processor(processor: ocio_rs::Processor) -> Self {
		let cpu = processor.default_cpu_processor().ok();
		Self {
			inner: Some(processor),
			cpu,
		}
	}

	/// Create a pass-through processor (invalid OCIO processor).
	pub fn pass_through() -> Self {
		Self {
			inner: None,
			cpu: None,
		}
	}

	/// The underlying OCIO processor handle, when valid.
	pub fn processor(&self) -> Option<&ocio_rs::Processor> {
		self.inner.as_ref()
	}

	/// Convert one RGBA color (C++ `convert_color`).
	pub fn convert_color(&self, rgba: [f64; 4]) -> [f64; 4] {
		match &self.cpu {
			Some(cpu) => {
				let mut c = [
					rgba[0] as f32,
					rgba[1] as f32,
					rgba[2] as f32,
					rgba[3] as f32,
				];
				cpu.apply_rgba(&mut c);
				[c[0] as f64, c[1] as f64, c[2] as f64, c[3] as f64]
			}
			None => rgba,
		}
	}

	/// Convert a whole F32 frame in place (row-major RGBA).
	pub fn convert_frame(&self, frame: &mut Frame) -> Result<()> {
		let Some(cpu) = &self.cpu else {
			return Ok(()); // pass-through
		};
		if frame.format != PixelFormat::F32 {
			return Err(Error::Invalid);
		}
		// Tightly packed RGBA: stride is 4 f32 elements per pixel
		// (ocio-rs counts elements, not bytes).
		let pixels = frame.pixel_count() as i64;
		let buf: &mut [f32] = bytemuck_f32_slice(&mut frame.data)
			.ok_or_else(|| Error::Failed("pixel buffer not f32 aligned".to_string()))?;
		cpu.apply_rgba_pixels(buf, pixels, 4);
		Ok(())
	}

	/// True when the underlying OCIO processor is valid (C++
	/// `get_processor() != null`).
	pub fn is_valid(&self) -> bool {
		self.inner.is_some()
	}

	/// The OCIO processor cache id (C++ `ColorProcessor::id()`), or the
	/// empty string for a pass-through processor.
	pub fn cache_id(&self) -> String {
		match &self.inner {
			Some(p) => p.cache_id().unwrap_or_default(),
			None => String::new(),
		}
	}

	/// Convert a packed BGRA8 buffer in place (the viewer wire format).
	/// The processor must have been built with
	/// [`create_display_icc_bgra8`](Self::create_display_icc_bgra8) — the
	/// R/B swizzle is baked into the chain, so the bytes go through OCIO's
	/// RGBA entry point unchanged. A pass-through processor is a no-op.
	///
	/// The conversion detours through F32: the default CPU processor is
	/// F32-finalized and rejects packed u8 buffers with a bit-depth
	/// mismatch, and the ocio-rs binding exposes no Uint8-finalized CPU
	/// processor. The round-trip cost is one small staging buffer.
	pub fn convert_bgra8(&self, data: &mut [u8], pixels: i64) -> Result<()> {
		let Some(cpu) = &self.cpu else {
			return Ok(());
		};
		let count = (pixels.max(0) as usize) * 4;
		if data.len() < count {
			return Err(Error::Invalid);
		}
		let mut f32s: Vec<f32> = data[..count].iter().map(|&v| v as f32 / 255.0).collect();
		cpu.try_apply_rgba_pixels(&mut f32s, pixels, 4)
			.map_err(|e| Error::Failed(format!("OCIO f32 apply (bgra8 detour): {e}")))?;
		for (dst, v) in data[..count].iter_mut().zip(f32s) {
			*dst = (v.clamp(0.0, 1.0) * 255.0).round() as u8;
		}
		Ok(())
	}

	/// Convert an F32 RGBA buffer in place (tightly packed, 4 floats per
	/// pixel). A pass-through processor is a no-op.
	pub fn convert_f32_rgba(&self, samples: &mut [f32], pixels: i64) -> Result<()> {
		let Some(cpu) = &self.cpu else {
			return Ok(());
		};
		cpu.try_apply_rgba_pixels(samples, pixels, 4)
			.map_err(|e| Error::Failed(format!("OCIO f32 apply: {e}")))
	}
}

/// Grading-primary transform style (mirrors the C++ enum values: LIN=0,
/// LOG=1 in `include/render/color.h`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradingStyle {
	/// OCIO GRADING_LIN.
	Lin,
	/// OCIO GRADING_LOG.
	Log,
}

impl GradingStyle {
	fn to_ocio(self) -> ocio_rs::GradingStyle {
		match self {
			GradingStyle::Lin => ocio_rs::GradingStyle::Lin,
			GradingStyle::Log => ocio_rs::GradingStyle::Log,
		}
	}
}

/// Reinterpret a byte buffer as f32 when its length is a multiple of 4
/// (the pipeline guarantees F32 RGBA frames, so alignment is exact).
fn bytemuck_f32_slice(data: &mut [u8]) -> Option<&mut [f32]> {
	if !data.len().is_multiple_of(4) {
		return None;
	}
	// SAFETY: length is a multiple of 4 and `data` is byte-aligned; the
	// cast is valid for any alignment (f32 has no stricter requirement
	// than u8 for mutable slice casts at this length).
	Some(unsafe { std::slice::from_raw_parts_mut(data.as_mut_ptr() as *mut f32, data.len() / 4) })
}

// ---- process-wide default config (C++ ColorManager statics) ----------------

/// The process-wide pipeline color settings (the project properties that
/// drive the ACEScg + F32 pipeline): the working colorspace and the
/// output/delivery spec. Defaults to ACEScg working + sRGB output; the app
/// updates this from the open project's properties (and again on every
/// project-properties commit). Render and export paths read it — a single
/// project is open at a time, so a process global is the same shape as the
/// OCIO default config above.
static PIPELINE_COLOR: LazyLock<
	Mutex<(
		crate::colormath::WorkingColorSpace,
		crate::colormath::OutputColorSpec,
	)>,
> = LazyLock::new(|| {
	Mutex::new((
		crate::colormath::WorkingColorSpace::default(),
		crate::colormath::OutputColorSpec::default(),
	))
});

/// Set the pipeline color settings (working space + output spec).
pub fn set_pipeline_color_settings(
	working: crate::colormath::WorkingColorSpace,
	output: crate::colormath::OutputColorSpec,
) {
	*PIPELINE_COLOR.lock().unwrap_or_else(|e| e.into_inner()) = (working, output);
}

/// The pipeline working colorspace.
pub fn pipeline_working_space() -> crate::colormath::WorkingColorSpace {
	PIPELINE_COLOR.lock().unwrap_or_else(|e| e.into_inner()).0
}

/// The pipeline output/delivery spec.
pub fn pipeline_output_spec() -> crate::colormath::OutputColorSpec {
	PIPELINE_COLOR.lock().unwrap_or_else(|e| e.into_inner()).1
}

/// The pipeline working colorspace as an OFX colorspace name (the value
/// written to `kOfxImageClipPropColourspace` so plugins are told the
/// true space of the pixels they receive — ACEScg in the default pipeline,
/// sRGB in the legacy pass-through mode).
pub fn pipeline_working_ofx_name() -> &'static str {
	match pipeline_working_space() {
		crate::colormath::WorkingColorSpace::AcesCg => "ACEScg",
		crate::colormath::WorkingColorSpace::SrgbLegacy => "sRGB",
	}
}

/// Send+Sync wrapper around `ocio_rs::Config` (a `NonNull`-based handle;
/// the underlying OCIO config is a shared pointer safe for concurrent
/// reads).
pub struct SafeConfig(ocio_rs::Config);
unsafe impl Send for SafeConfig {}
unsafe impl Sync for SafeConfig {}

impl std::ops::Deref for SafeConfig {
	type Target = ocio_rs::Config;
	fn deref(&self) -> &ocio_rs::Config {
		&self.0
	}
}

static DEFAULT_CONFIG: LazyLock<Mutex<Option<std::sync::Arc<SafeConfig>>>> =
	LazyLock::new(|| Mutex::new(None));

/// Borrow the default config (C++ `ColorManager::get_default_config()`).
/// The `Arc` keeps the config alive across threads.
pub fn default_config() -> Option<std::sync::Arc<SafeConfig>> {
	DEFAULT_CONFIG
		.lock()
		.unwrap_or_else(|e| e.into_inner())
		.clone()
}

/// Load the process-wide default config from $OCIO or the bundled config
/// (C++ `ColorManager::SetUpDefaultConfig`).
pub fn set_up_default_config() -> Result<()> {
	let env = std::env::var("OCIO").ok().filter(|p| !p.is_empty());
	set_up_default_config_from(env.as_deref())
}

/// Load the process-wide default config from an explicit path (`None` =
/// the bundled default config). The project-properties OCIO override and
/// the `$OCIO` startup path both land here.
pub fn set_up_default_config_from(path: Option<&str>) -> Result<()> {
	let config = match path {
		Some(path) => ocio_rs::Config::from_file(path)
			.map_err(|e| Error::Failed(format!("load OCIO config \"{path}\": {e}")))?,
		None => ocio_rs::Config::create_from_builtin_config("default")
			.or_else(|_| ocio_rs::Config::create_from_builtin_config("ocio-2.2-default"))
			.map_err(|e| Error::Failed(format!("load bundled config: {e}")))?,
	};
	*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) =
		Some(std::sync::Arc::new(SafeConfig(config)));
	Ok(())
}

/// The active default config's display transform cache id for
/// (display, view) — computed from the config's reference colorspace
/// (C++ `ColorManager::display_transform` cache-id semantics).
///
/// `Err(Error::State)` when no default config exists; `Ok(None)` when the
/// display or view is unknown.
pub fn display_transform_result(
	display: &str,
	view: &str,
) -> std::result::Result<Option<String>, Error> {
	let config = default_config().ok_or(Error::State)?;

	let mut display_found = false;
	for i in 0..config.num_displays_all() {
		if config.display_all(i).as_deref() == Some(display) {
			display_found = true;
			break;
		}
	}
	if !display_found {
		return Ok(None);
	}

	let mut view_found = false;
	let views =
		config.num_views_by_reference_space(ocio_rs::SearchReferenceSpaceType::Scene, display);
	for i in 0..views {
		if config
			.view_by_reference_space(ocio_rs::SearchReferenceSpaceType::Scene, display, i)
			.as_deref()
			== Some(view)
		{
			view_found = true;
			break;
		}
	}
	if !view_found {
		return Ok(None);
	}

	// OCIO's ROLE_REFERENCE role name ("reference"): `color_space`
	// resolves name-or-role (C++ `getColorSpace(ROLE_REFERENCE)`); the
	// role-name lookups are the fallback for configs that do not bind it.
	let src = config
		.color_space("reference")
		.and_then(|cs| cs.name())
		.filter(|s| !s.is_empty())
		.or_else(|| {
			config
				.role_color_space("reference")
				.filter(|s| !s.is_empty())
		})
		.or_else(|| {
			config
				.role_color_space("aces_interchange")
				.filter(|s| !s.is_empty())
		})
		.or_else(|| {
			config
				.role_color_space("scene_linear")
				.filter(|s| !s.is_empty())
		})
		.ok_or(Error::State)?;
	let processor = config
		.processor_display(src, display, view, ocio_rs::TransformDirection::Forward)
		.map_err(|_| Error::NotFound)?;
	Ok(processor.cache_id())
}

/// [`display_transform_result`] as a plain option (unknown → None).
pub fn display_transform(display: &str, view: &str) -> Option<String> {
	display_transform_result(display, view).ok().flatten()
}

/// The $OCIO path when set, otherwise the extracted default config path
/// (C++ `ColorManager::get_config_path`; the actual file extraction is
/// deferred to the app layer — the Rust default config stays in memory).
pub fn config_path() -> Option<String> {
	if let Ok(path) = std::env::var("OCIO") {
		if !path.is_empty() {
			return Some(path);
		}
	}
	default_config()?;
	Some(format!(
		"{}/ocioconf/config.ocio",
		crate::commonutil::configuration_location()
	))
}

// ---- OCIO GPU function shaders (C++ colormanagement.cpp GetColorContext) --

/// Cache of generated GLSL stubs, keyed by function name + color spaces +
/// config cache id (so a swapped test config re-generates). `None` entries
/// are cached too — the lookup result is deterministic per key.
static OCIO_STUB_CACHE: LazyLock<Mutex<HashMap<String, Option<String>>>> =
	LazyLock::new(|| Mutex::new(HashMap::new()));

/// The GLSL ES 3.0 shader text implementing the OCIO function `fn_name`
/// between `from_space` and `to_space` (both resolved as color-space names
/// or roles, exactly like the C++ `getProcessor(src, dst)` calls).
///
/// This mirrors the C++ OCIO-node shader path: the node's
/// `GenerateProcessor` builds a `ColorTransform` between two spaces and
/// `GetShaderCode` receives the auto-generated stub from
/// `Renderer::GetColorContext` (colormanagement.cpp), which the node then
/// splices into its fragment shader at the `%1` marker.
///
/// `None` when no default config exists or the processor is LUT-based:
/// `extractGpuShaderInfo` reports lookup textures that the C++ renderer
/// uploads per LUT (the loops right after `GetColorContext`), but the Rust
/// renderer has no such upload path, so those transforms are skipped and
/// the node passes through.
pub fn ocio_function_shader(fn_name: &str, from_space: &str, to_space: &str) -> Option<String> {
	let config = default_config()?;
	let cache_key = format!(
		"{}:{}:{}:{}",
		fn_name,
		from_space,
		to_space,
		config.cache_id().unwrap_or_default()
	);
	if let Some(hit) = OCIO_STUB_CACHE
		.lock()
		.unwrap_or_else(|e| e.into_inner())
		.get(&cache_key)
	{
		return hit.clone();
	}
	let stub = build_ocio_function_shader(&config, fn_name, from_space, to_space);
	OCIO_STUB_CACHE
		.lock()
		.unwrap_or_else(|e| e.into_inner())
		.insert(cache_key, stub.clone());
	stub
}

/// Build (but do not cache) the GLSL stub for `fn_name` between the two
/// spaces (C++ `GpuShaderDesc::CreateShaderDesc` + `setLanguage` +
/// `extractGpuShaderInfo`, colormanagement.cpp `GetColorContext`).
fn build_ocio_function_shader(
	config: &SafeConfig,
	fn_name: &str,
	from_space: &str,
	to_space: &str,
) -> Option<String> {
	let processor = config.processor(from_space, to_space).ok()?;
	let gpu = processor.default_gpu_processor().ok()?;
	let mut desc = ocio_rs::GpuShaderDesc::create().ok()?;
	desc.set_language(ocio_rs::GpuLanguage::GlslEs3_0).ok()?;
	desc.set_function_name(fn_name).ok()?;
	desc.set_resource_prefix("ocio_").ok()?;
	gpu.try_extract_shader_info(&mut desc).ok()?;
	// LUT-based processors need their 1D/3D textures uploaded (the C++
	// `GetColorContext` caller loops over `getNum3DTextures`/`getNumTextures`
	// right after extraction); without a LUT upload path these cannot render.
	if desc.num_textures() > 0 || desc.num_3d_textures() > 0 {
		return None;
	}
	desc.shader_text()
}

/// Cache of generated grading GLSL stubs, keyed by style + config cache id
/// (same shape as [`OCIO_STUB_CACHE`]; grading is analytic so the result is
/// deterministic per key).
static OCIO_GRADING_CACHE: LazyLock<Mutex<HashMap<String, Option<String>>>> =
	LazyLock::new(|| Mutex::new(HashMap::new()));

/// The GLSL text of the dynamic grading-primary processor for `style`
/// (C++ quercusrender creates the same processor via
/// `quercusrender_color_processor_create_grading_primary` and the renderer
/// applies it between passes; the Rust equivalent generates the OCIO GPU
/// shader the node splices at its `%1` marker). `None` when no default
/// config exists or the processor is LUT-based (the same guard as
/// [`ocio_function_shader`] — grading is analytic, so this is purely a
/// config-availability check).
pub fn grading_primary_function_shader(style: GradingStyle) -> Option<String> {
	let config = default_config()?;
	let style_id = match style {
		GradingStyle::Lin => "lin",
		GradingStyle::Log => "log",
	};
	let cache_key = format!("{style_id}:{}", config.cache_id().unwrap_or_default());
	if let Some(hit) = OCIO_GRADING_CACHE
		.lock()
		.unwrap_or_else(|e| e.into_inner())
		.get(&cache_key)
	{
		return hit.clone();
	}
	let stub = build_ocio_grading_shader(&config, style);
	OCIO_GRADING_CACHE
		.lock()
		.unwrap_or_else(|e| e.into_inner())
		.insert(cache_key, stub.clone());
	stub
}

/// Build (but do not cache) the grading GLSL stub: a dynamic
/// grading-primary transform on `config`, extracted exactly like
/// [`build_ocio_function_shader`].
fn build_ocio_grading_shader(config: &SafeConfig, style: GradingStyle) -> Option<String> {
	let transform = ocio_rs::transform::GradingPrimaryTransform::create(style.to_ocio()).ok()?;
	transform.make_dynamic();
	transform.set_direction(ocio_rs::TransformDirection::Forward);
	let processor = config
		.processor_from_transform(&transform, ocio_rs::TransformDirection::Forward)
		.ok()?;
	let gpu = processor.default_gpu_processor().ok()?;
	let mut desc = ocio_rs::GpuShaderDesc::create().ok()?;
	desc.set_language(ocio_rs::GpuLanguage::GlslEs3_0).ok()?;
	desc.set_function_name("ove_grading_primary").ok()?;
	desc.set_resource_prefix("ocio_").ok()?;
	gpu.try_extract_shader_info(&mut desc).ok()?;
	if desc.num_textures() > 0 || desc.num_3d_textures() > 0 {
		return None;
	}
	desc.shader_text()
}

// ---- LUT library (C++ LUTLibrary) ------------------------------------------

/// Supported LUT extensions (C++ `LUTLibrary::supported_extensions()`).
pub const SUPPORTED_LUT_EXTENSIONS: [&str; 9] = [
	"cube", "3dl", "spi1d", "spi3d", "spimtx", "csp", "clf", "ctf", "cub",
];

/// 1 when `extension` (dot optional, case-insensitive) is supported.
pub fn is_supported_lut_extension(extension: &str) -> bool {
	let ext = extension.strip_prefix('.').unwrap_or(extension);
	SUPPORTED_LUT_EXTENSIONS
		.iter()
		.any(|e| e.eq_ignore_ascii_case(ext))
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::sync::{Mutex, MutexGuard};

	/// Serializes config-dependent color tests (the process-wide default
	/// config is global).
	static CONFIG_TEST_LOCK: Mutex<()> = Mutex::new(());

	fn config_lock() -> MutexGuard<'static, ()> {
		CONFIG_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
	}

	/// A display-class ICC profile from the usual system locations, if any
	/// (macOS ColorSync, Linux colord/ghostscript, Debian/Ubuntu
	/// `icc-profiles-free` — the CI runner installs the latter).
	fn system_icc() -> Option<&'static str> {
		[
			"/System/Library/ColorSync/Profiles/sRGB Profile.icc",
			"/System/Library/ColorSync/Profiles/Display P3.icc",
			"/usr/share/color/icc/colord/sRGB.icc",
			"/usr/share/color/icc/ghostscript/srgb.icc",
			"/usr/share/color/icc/sRGB.icc",
			"/usr/local/share/color/icc/colord/sRGB.icc",
		]
		.into_iter()
		.find(|p| std::path::Path::new(p).exists())
	}

	#[test]
	fn lut_extensions_case_insensitive_and_dot_optional() {
		assert!(is_supported_lut_extension("cube"));
		assert!(is_supported_lut_extension(".CUBE"));
		assert!(is_supported_lut_extension("clf"));
		assert!(!is_supported_lut_extension("exr"));
		assert!(!is_supported_lut_extension(""));
		assert_eq!(SUPPORTED_LUT_EXTENSIONS.len(), 9);
	}

	#[test]
	fn pass_through_processor_identity() {
		let p = ColorProcessor::pass_through();
		assert!(!p.is_valid());
		assert_eq!(
			p.convert_color([0.25, 0.5, 0.75, 1.0]),
			[0.25, 0.5, 0.75, 1.0]
		);
		let mut f = Frame::dummy();
		assert!(p.convert_frame(&mut f).is_ok());
	}

	#[test]
	fn convert_frame_rejects_non_f32() {
		// A pass-through processor accepts anything (no conversion needed).
		let p = ColorProcessor::pass_through();
		let mut f = Frame::new();
		f.format = PixelFormat::U8;
		assert!(
			p.convert_frame(&mut f).is_ok(),
			"pass-through converts nothing"
		);
		// A *valid* processor requires the F32 pipeline format.
		if set_up_default_config().is_err() {
			return;
		}
		let valid = ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal)
			.and_then(|p| p.is_valid().then_some(p));
		if let Some(valid) = valid {
			let mut f = Frame::new();
			f.format = PixelFormat::U8;
			assert_eq!(
				valid.convert_frame(&mut f).unwrap_err().code(),
				crate::error::QUERCUSCORE_E_INVALID
			);
		}
	}

	#[test]
	fn create_without_config_yields_none() {
		let _lock = config_lock();
		// When no default config has been set up, creation is None.
		let saved = default_config();
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) = None;
		assert!(ColorProcessor::create("scene_linear", "sdr-video", Direction::Normal).is_none());
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) = saved;
	}

	#[test]
	fn default_config_setup_and_role_resolution() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			// Bundled OCIO missing (e.g. stub build): skip.
			return;
		}
		let config = default_config().expect("config set up");
		// The built-in default config carries a scene_linear role.
		assert!(config.has_role("scene_linear") || config.has_role("aces_interchange"));
	}

	#[test]
	fn processor_from_builtin_converts() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		} // Create via the built-in config; a valid processor must exist for
	// the ACES scene→display-encoded pairing and must preserve alpha.
		let p = ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal);
		let p = p.expect("processor handle always returned");
		assert!(
			p.is_valid(),
			"ACEScg→sRGB Encoded must be a valid processor"
		);
		let out = p.convert_color([0.18, 0.18, 0.18, 1.0]);
		assert!((out[3] - 1.0).abs() < 1e-6, "alpha passes through");
		assert!(out[0].is_finite() && out[1].is_finite() && out[2].is_finite());
		assert!(
			(out[0] - 0.18).abs() > 1e-3,
			"the transform must change the value"
		);
	}

	#[test]
	fn unknown_colorspaces_yield_invalid_processor() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let p = ColorProcessor::create("not_a_real_colorspace", "also_not_real", Direction::Normal)
			.unwrap();
		assert!(!p.is_valid(), "lookup failure is non-fatal (pass-through)");
		assert_eq!(
			p.convert_color([1.0, 0.5, 0.25, 0.0]),
			[1.0, 0.5, 0.25, 0.0]
		);
	}

	#[test]
	fn display_transform_queries() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let config = default_config().unwrap();
		if config.num_displays_all() <= 0 {
			return;
		}
		let display = config.display_all(0).unwrap();
		let n =
			config.num_views_by_reference_space(ocio_rs::SearchReferenceSpaceType::Scene, &display);
		assert!(n >= 0);
		if n > 0 {
			let view = config
				.view_by_reference_space(ocio_rs::SearchReferenceSpaceType::Scene, &display, 0)
				.unwrap();
			let id = display_transform(&display, &view);
			assert!(id.is_some());
			assert!(!id.unwrap().is_empty());
			// Querying a later view iterates past the non-matching ones
			// (the loop's pass-through arm); an unknown view is Ok(None).
			let last = config
				.view_by_reference_space(
					ocio_rs::SearchReferenceSpaceType::Scene,
					&display,
					n - 1,
				)
				.unwrap();
			assert!(display_transform_result(&display, &last).is_ok());
			assert_eq!(display_transform_result(&display, "no-such-view").unwrap(), None);
		}
		assert!(display_transform("no-such-display", "x").is_none());
	}

	#[test]
	fn convert_frame_with_valid_processor_changes_pixels() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let p = ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal)
			.expect("handle always returned");
		if !p.is_valid() {
			return;
		}
		let mut f = Frame::new();
		let mut pod = crate::frame::VideoParamsPod::default();
		pod.width = 4;
		pod.height = 2;
		f.set_video_params(pod);
		f.allocate();
		// Fill with 0.18 grey via f32 view.
		let f32s: &mut [f32] = unsafe {
			std::slice::from_raw_parts_mut(f.data.as_mut_ptr() as *mut f32, f.pixel_count() * 4)
		};
		for px in f32s.as_chunks_mut::<4>().0 {
			px[0] = 0.18;
			px[1] = 0.18;
			px[2] = 0.18;
			px[3] = 1.0;
		}
		p.convert_frame(&mut f).unwrap();
		let out: &[f32] = unsafe {
			std::slice::from_raw_parts(f.data.as_ptr() as *const f32, f.pixel_count() * 4)
		};
		assert!(
			(out[0] - 0.18).abs() > 1e-4,
			"scene_linear→sdr-video must change 0.18 grey (got {})",
			out[0]
		);
		assert!((out[3] - 1.0).abs() < 1e-5, "alpha preserved");
	}

	#[test]
	fn display_icc_processor_applies_srgb_profile() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		// A display-class ICC is required; the usual system profile
		// locations are probed (CI runners may have none — skip then).
		let Some(icc) = system_icc() else {
			eprintln!("no system ICC profile; skipping");
			return;
		};
		let p = ColorProcessor::create_display_icc("scene_linear", icc)
			.expect("handle always returned");
		assert!(p.is_valid(), "ICC processor builds from {icc}");
		// 0.18 scene-linear grey -> ~0.5 sRGB device grey (the sRGB system
		// profile's device space is sRGB-encoded).
		let out = p.convert_color([0.18, 0.18, 0.18, 1.0]);
		assert!(
			(out[0] - 0.5).abs() < 0.08,
			"0.18 linear grey should land near 0.5 sRGB (got {})",
			out[0]
		);
		assert!(
			(out[0] - out[1]).abs() < 1e-3 && (out[1] - out[2]).abs() < 1e-3,
			"grey stays grey: {out:?}"
		);
		assert!((out[3] - 1.0).abs() < 1e-5, "alpha preserved");
	}

	/// The non-sRGB project output gamut display path: content converted to
	/// CIE XYZ (D65, unit luminance) by
	/// `crate::colormath::output_spec_to_xyz_d65` must flow through the
	/// display ICC. Builds by running the classic builder with the config's
	/// `cie_xyz_d65_interchange` role as the source space — the feasibility
	/// question this test answers is whether OCIO accepts the role name as a
	/// `ColorSpaceTransform` source (it is a role, not a bare colorspace, in
	/// the OCIO 2.2+ builtin configs).
	#[test]
	fn display_icc_xyz_accepts_interchange_role() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		// Any display-class ICC (CI runners may have none — skip then).
		let Some(icc) = system_icc() else {
			eprintln!("no system ICC profile; skipping");
			return;
		};
		let p = ColorProcessor::create_display_icc_xyz(icc)
			.expect("handle always returned or explicit None");
		assert!(
			p.is_valid(),
			"the cie_xyz_d65_interchange role must build the XYZ→ICC chain from {icc}"
		);
		// Numeric sanity: the XYZ chain fed with `output_spec_to_xyz_d65` of
		// an sRGB-encoded mid-grey must match the classic chain applied to
		// the same encoded values — legs 1+2 (XYZ→lin709→XYZ) are the inverse
		// round trip of the classic chain's lin709→XYZ leg, so both must land
		// on the same device values.
		let spec = crate::colormath::OutputColorSpec::default();
		let encoded = [0.5f32, 0.5, 0.5, 1.0];
		let mut xyz_in = encoded;
		crate::colormath::output_spec_to_xyz_d65(&mut xyz_in, spec);
		let mut via_xyz = xyz_in;
		let _ = p.convert_f32_rgba(&mut via_xyz, 1);
		let srgb = ColorProcessor::create_display_icc("sRGB Encoded Rec.709 (sRGB)", icc)
			.expect("handle always returned");
		let mut via_srgb = encoded;
		let _ = srgb.convert_f32_rgba(&mut via_srgb, 1);
		for c in 0..3 {
			assert!(
				(via_xyz[c] - via_srgb[c]).abs() < 0.02,
				"channel {c}: XYZ chain {} vs sRGB chain {} (round trip must be identity)",
				via_xyz[c],
				via_srgb[c]
			);
		}
		// Grey stays grey; alpha preserved.
		assert!(
			(via_xyz[0] - via_xyz[1]).abs() < 1e-3 && (via_xyz[1] - via_xyz[2]).abs() < 1e-3,
			"grey stays grey: {via_xyz:?}"
		);
		assert!((via_xyz[3] - 1.0).abs() < 1e-5, "alpha preserved");
	}

	/// The exact chain the viewers use (BGRA8, display-class ICC from
	/// `QUERCUS_DISPLAY_ICC`): a mid-grey frame must NOT collapse to black —
	/// the viewer-black-screen regression guard. Falls back to a system
	/// profile when the env var is unset (point it at the display profile
	/// under investigation to override); skipped only when neither exists.
	/// An empty env value is treated as unset, same as
	/// `displayicc::env_override_icc`.
	#[test]
	fn display_icc_bgra8_never_outputs_black() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let env_icc = std::env::var("QUERCUS_DISPLAY_ICC").unwrap_or_default();
		let icc = if env_icc.is_empty() {
			let Some(system) = system_icc() else {
				eprintln!("QUERCUS_DISPLAY_ICC unset and no system ICC profile; skipping");
				return;
			};
			system.to_string()
		} else {
			env_icc
		};
		let p = ColorProcessor::create_display_icc_bgra8("sRGB Encoded Rec.709 (sRGB)", &icc)
			.expect("handle always returned");
		assert!(p.is_valid(), "BGRA8 ICC processor builds from {icc}");
		// BGRA bytes: 0.5 grey, 0.75 red, 0.25 green, 0.6 blue.
		let mut data: Vec<u8> = vec![
			128, 128, 128, 255, // grey
			0, 0, 191, 255, // red
			0, 64, 0, 255, // green
			153, 0, 0, 255, // blue
		];
		let bgra_result = p.convert_bgra8(&mut data, 4);
		eprintln!("bgra8 convert: {bgra_result:?} -> {data:?}");
		// The F32 RGBA leg (the CpuF32 display path) must not crush to
		// black either — and unlike the u8 leg it must not even fail.
		let p32 = ColorProcessor::create_display_icc("sRGB Encoded Rec.709 (sRGB)", &icc)
			.expect("handle always returned");
		assert!(p32.is_valid(), "F32 ICC processor builds from {icc}");
		let mut f32s: Vec<f32> = vec![
			0.5, 0.5, 0.5, 1.0, // grey
			0.75, 0.0, 0.0, 1.0, // red
			0.0, 0.25, 0.0, 1.0, // green
			0.0, 0.0, 0.6, 1.0, // blue
		];
		let f32_result = p32.convert_f32_rgba(&mut f32s, 4);
		eprintln!("f32 convert: {f32_result:?} -> {f32s:?}");
		bgra_result.expect("convert");
		for (i, px) in data.as_chunks::<4>().0.iter().enumerate() {
			assert_eq!(px[3], 255, "pixel {i}: alpha preserved");
			let rgb: u32 = px[0] as u32 + px[1] as u32 + px[2] as u32;
			assert!(rgb > 0, "pixel {i} must not be crushed to black: {px:?}");
		}
		// Grey stays greyish (a display profile must not tint wildly).
		let (b, g, r) = (data[0] as i32, data[1] as i32, data[2] as i32);
		assert!(
			(b - g).abs() < 24 && (g - r).abs() < 24,
			"grey stays grey through the display ICC: {b} {g} {r}"
		);
		f32_result.expect("convert f32");
		for (i, px) in f32s.as_chunks::<4>().0.iter().enumerate() {
			assert!((px[3] - 1.0).abs() < 1e-3, "pixel {i}: alpha preserved");
			let rgb = px[0] + px[1] + px[2];
			assert!(rgb > 0.0, "pixel {i} must not be crushed to black: {px:?}");
		}
	}

	#[test]
	fn inverse_direction_reverses() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let fwd =
			ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal)
				.expect("handle");
		let inv =
			ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Inverse)
				.expect("handle");
		if !fwd.is_valid() || !inv.is_valid() {
			return;
		}
		let x = fwd.convert_color([0.18, 0.18, 0.18, 1.0]);
		let back = inv.convert_color(x);
		assert!(
			(back[0] - 0.18).abs() < 0.05,
			"inverse undoes forward ({} -> {})",
			x[0],
			back[0]
		);
	}

	#[test]
	fn create_lut_from_real_file() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		// A tiny 1D .cube LUT (identity-ish with a slight lift).
		let lut = "TITLE quercusrender test\nLUT_1D_SIZE 2\n0.0 0.0 0.0\n1.0 1.0 1.0\n";
		let path = std::env::temp_dir().join("quercusrender-test-lut.cube");
		std::fs::write(&path, lut).unwrap();
		let p = ColorProcessor::create_lut(path.to_string_lossy().as_ref(), Direction::Normal)
			.expect("processor handle always returned");
		assert!(
			p.is_valid(),
			"a readable .cube must produce a valid processor"
		);
		let _ = std::fs::remove_file(&path);
	}

	#[test]
	fn grading_primary_and_from_processor() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping grading-primary/from-processor assertions");
			return;
		}
		// A grading-primary processor is valid and converts on the live
		// config (the shader test below relies on the same construction).
		let p = ColorProcessor::create_grading_primary(GradingStyle::Log)
			.expect("grading-primary processor on a live config");
		assert!(p.is_valid(), "grading-primary processor must be valid");
		let out = p.convert_color([0.18, 0.5, 0.7, 1.0]);
		assert!(out.iter().all(|v| v.is_finite()));

		let config = default_config().expect("config set up");
		let proc = config
			.processor("ACEScg", "sRGB Encoded Rec.709 (sRGB)")
			.expect("ACEScg→sRGB Encoded processor on the default config");
		let p = ColorProcessor::from_processor(proc);
		assert!(p.is_valid());
		assert!(!p.cache_id().is_empty(), "OCIO cache id present");
	}

	#[test]
	fn grading_primary_shader_generates_analytic_glsl() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return; // Bundled OCIO missing (e.g. stub build): skip.
		}
		for style in [GradingStyle::Lin, GradingStyle::Log] {
			let stub = grading_primary_function_shader(style)
				.expect("default config generates an analytic grading shader");
			assert!(
				stub.contains("ove_grading_primary"),
				"function name present"
			);
			assert!(
				!stub.contains("sampler"),
				"no LUT upload expected for grading"
			);
			// Cache hit: a repeated call returns the same text.
			let again = grading_primary_function_shader(style).unwrap();
			assert_eq!(stub, again);
		}
	}

	#[test]
	fn create_lut_missing_file_is_invalid() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let p = ColorProcessor::create_lut("/nonexistent/never.cube", Direction::Normal).unwrap();
		assert!(!p.is_valid(), "unreadable LUT → pass-through processor");
	}

	#[test]
	fn ocio_function_shader_generates_glsl_for_chromakey() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return; // Bundled OCIO missing (e.g. stub build): skip.
		}
		let stub = ocio_function_shader(
			"SceneLinearToCIEXYZ_d65",
			"scene_linear",
			"cie_xyz_d65_interchange",
		)
		.expect("default config generates an analytic shader");
		assert!(
			stub.contains("SceneLinearToCIEXYZ_d65"),
			"function name present"
		);
		assert!(
			!stub.contains("sampler"),
			"no LUT upload expected in the default config"
		);
		// Cache hit: a repeated call returns the same text.
		let again = ocio_function_shader(
			"SceneLinearToCIEXYZ_d65",
			"scene_linear",
			"cie_xyz_d65_interchange",
		)
		.unwrap();
		assert_eq!(stub, again);
	}

	#[test]
	fn ocio_function_shader_rejects_lut_processors() {
		let _lock = config_lock();
		// studio-config's Rec.709 display is a CLF LUT chain (unlike the
		// analytic sRGB one); without a LUT upload path it must be refused.
		let Ok(cfg) =
			ocio_rs::Config::create_from_builtin_config("studio-config-v2.1.0_aces-v1.3_ocio-v2.3")
		else {
			return;
		};
		let cfg = SafeConfig(cfg);
		assert!(
			build_ocio_function_shader(&cfg, "probe", "ACEScg", "Rec.709 - Display").is_none(),
			"LUT-based processor must be refused"
		);
		// A pure-matrix pairing on the same config still generates.
		assert!(
			build_ocio_function_shader(&cfg, "probe", "ACEScg", "ACES2065-1").is_some(),
			"analytic processor still generates"
		);
	}

	// ---- Branch-coverage fill-ins ------------------------------------------

	#[test]
	fn rb_swap_matrix_builds_from_ocio() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		assert!(rb_swap_matrix().is_some(), "matrix transform available");
	}

	#[test]
	fn pass_through_processor_accessors_and_conversions() {
		let p = ColorProcessor::pass_through();
		assert!(p.processor().is_none());
		assert_eq!(p.cache_id(), "", "pass-through has no cache id");
		// BGRA8 and F32 conversions are no-ops without a CPU processor.
		let mut data = [1u8, 2, 3, 4];
		p.convert_bgra8(&mut data, 1).unwrap();
		assert_eq!(data, [1, 2, 3, 4]);
		let mut samples = [0.25f32, 0.5, 0.75, 1.0];
		p.convert_f32_rgba(&mut samples, 1).unwrap();
		assert_eq!(samples, [0.25, 0.5, 0.75, 1.0]);
		// Negative/zero pixel counts stay harmless on the no-op path too.
		p.convert_bgra8(&mut data, -3).unwrap();
	}

	#[test]
	fn create_lut_on_config_and_inverse_direction() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		let config = default_config().expect("config set up");
		let lut = "TITLE quercus create_lut_on test\nLUT_1D_SIZE 2\n0.0 0.0 0.0\n1.0 1.0 1.0\n";
		let path = std::env::temp_dir().join(format!("quercus-color-lut-on-{}.cube", std::process::id()));
		std::fs::write(&path, lut).unwrap();
		let path = path.to_string_lossy().into_owned();

		let fwd = ColorProcessor::create_lut_on(&config, &path, Direction::Normal)
			.expect("processor handle always returned");
		assert!(fwd.is_valid(), "readable LUT on a specific config");
		// Direction::Inverse exercises the inverse mapping (`to_ocio`) on
		// the transform and the processor.
		let inv = ColorProcessor::create_lut_on(&config, &path, Direction::Inverse)
			.expect("processor handle always returned");
		assert!(inv.is_valid(), "inverse LUT processor");
		// create_lut (default config) with the inverse direction too.
		let inv_default = ColorProcessor::create_lut(&path, Direction::Inverse)
			.expect("processor handle always returned");
		assert!(inv_default.is_valid());

		// An unreadable LUT yields a pass-through handle, not None.
		let missing = ColorProcessor::create_lut_on(&config, "/nonexistent/quercus.cube", Direction::Normal)
			.expect("processor handle always returned");
		assert!(!missing.is_valid(), "unreadable LUT → pass-through");
		let _ = std::fs::remove_file(&path);
	}

	#[test]
	fn valid_processor_accessor_and_cache_id() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping processor accessor assertions");
			return;
		}
		let config = default_config().expect("config set up");
		let proc = config
			.processor("ACEScg", "sRGB Encoded Rec.709 (sRGB)")
			.expect("ACEScg→sRGB Encoded processor on the default config");
		let p = ColorProcessor::from_processor(proc);
		assert!(p.processor().is_some(), "valid processor exposes its handle");
		assert!(!p.cache_id().is_empty());
	}

	#[test]
	fn convert_frame_rejects_non_f32_and_unaligned_buffers() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		let p = ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal)
			.expect("handle always returned");
		if !p.is_valid() {
			eprintln!("processor unavailable in this config; skipping");
			return;
		}
		// A valid processor only accepts the F32 pipeline format.
		let mut f = Frame::new();
		f.format = PixelFormat::U8;
		assert_eq!(
			p.convert_frame(&mut f).unwrap_err().code(),
			crate::error::QUERCUSCORE_E_INVALID
		);
		// F32 but a byte length that is not a multiple of 4.
		let mut f = Frame::new();
		f.format = PixelFormat::F32;
		f.data = vec![0u8; 3];
		assert!(p.convert_frame(&mut f).is_err(), "unaligned buffer rejected");
		// A well-formed F32 buffer converts.
		let mut f = Frame::new();
		f.width = 1;
		f.height = 1;
		f.channels = 4;
		f.format = PixelFormat::F32;
		f.data = vec![0u8; 16];
		p.convert_frame(&mut f).unwrap();
	}

	#[test]
	fn display_icc_bgra8_and_xyz_bgra8_chains() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		let Some(icc) = system_icc() else {
			eprintln!("no system ICC profile; skipping");
			return;
		};
		let p = ColorProcessor::create_display_icc_bgra8("sRGB Encoded Rec.709 (sRGB)", icc)
			.expect("handle always returned");
		assert!(p.is_valid(), "BGRA8 ICC chain builds from {icc}");
		let mut data: Vec<u8> = vec![128, 128, 128, 255, 0, 0, 191, 255];
		assert!(p.convert_bgra8(&mut data, 2).is_ok());
		assert_eq!(data[3], 255, "alpha preserved");
		assert!(data[..3].iter().any(|&b| b != 0), "grey survives");
		// A short buffer is rejected before converting anything.
		let mut short = vec![0u8; 3];
		assert_eq!(
			p.convert_bgra8(&mut short, 2).unwrap_err().code(),
			crate::error::QUERCUSCORE_E_INVALID
		);
		// Zero/negative counts clamp to nothing to convert.
		let mut unchanged = vec![7u8; 4];
		let _ = p.convert_bgra8(&mut unchanged, 0);
		let _ = p.convert_bgra8(&mut unchanged, -3);
		// The F32 entry point on the same chain.
		let mut samples: Vec<f32> = vec![0.5, 0.5, 0.5, 1.0];
		assert!(p.convert_f32_rgba(&mut samples, 1).is_ok());
		assert!((samples[3] - 1.0).abs() < 1e-3, "alpha preserved");
		// The XYZ BGRA8 wrapper (both R/B swizzles baked in).
		let xyz = ColorProcessor::create_display_icc_xyz_bgra8(icc).expect("handle");
		assert!(xyz.is_valid(), "XYZ BGRA8 ICC chain builds from {icc}");
	}

	/// Captures the process-wide pipeline color settings and restores them
	/// on drop, so a panicking assertion cannot leak the legacy setting
	/// into the tests that run after it.
	struct PipelineColorGuard {
		working: crate::colormath::WorkingColorSpace,
		output: crate::colormath::OutputColorSpec,
	}

	impl PipelineColorGuard {
		fn capture() -> Self {
			Self {
				working: pipeline_working_space(),
				output: pipeline_output_spec(),
			}
		}

		fn restore(&mut self) {
			set_pipeline_color_settings(self.working, self.output);
		}
	}

	impl Drop for PipelineColorGuard {
		fn drop(&mut self) {
			self.restore();
		}
	}

	#[test]
	fn pipeline_working_ofx_name_legacy_mode() {
		use crate::colormath::WorkingColorSpace;
		// The pipeline settings are process-global: take the config lock
		// like the other tests that touch global color state.
		let _lock = config_lock();
		let mut restore = PipelineColorGuard::capture();
		set_pipeline_color_settings(WorkingColorSpace::SrgbLegacy, restore.output);
		assert_eq!(pipeline_working_ofx_name(), "sRGB");
		restore.restore();
		let expected = match restore.working {
			WorkingColorSpace::AcesCg => "ACEScg",
			WorkingColorSpace::SrgbLegacy => "sRGB",
		};
		assert_eq!(pipeline_working_ofx_name(), expected, "settings restored");
	}

	#[test]
	fn config_path_env_and_bundled_fallback() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		let saved = std::env::var_os("OCIO");
		struct EnvGuard(Option<std::ffi::OsString>);
		impl Drop for EnvGuard {
			fn drop(&mut self) {
				match self.0.take() {
					Some(v) => std::env::set_var("OCIO", v),
					None => std::env::remove_var("OCIO"),
				}
			}
		}
		let _env_guard = EnvGuard(saved);

		std::env::set_var("OCIO", "/tmp/quercus-config-path-test.ocio");
		assert_eq!(
			config_path().as_deref(),
			Some("/tmp/quercus-config-path-test.ocio"),
			"a non-empty $OCIO wins"
		);
		// An empty $OCIO is treated as unset and falls back to the bundled
		// extraction location (a config must exist for that branch).
		std::env::set_var("OCIO", "");
		let fallback = config_path().expect("bundled fallback when a config exists");
		assert!(fallback.ends_with("ocioconf/config.ocio"), "got {fallback}");
	}

	#[test]
	fn set_up_default_config_from_bad_path_errors_and_keeps_config() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			return;
		}
		let before = default_config();
		let err = set_up_default_config_from(Some("/nonexistent/quercus-config.ocio"));
		assert!(err.is_err(), "a bad config path is a load error");
		assert!(
			default_config().is_some(),
			"the previous default config survives a failed load"
		);
		assert_eq!(
			default_config().map(|c| c.cache_id()),
			before.map(|c| c.cache_id())
		);
	}

	#[test]
	fn display_transform_scene_linear_role_fallback() {
		let _lock = config_lock();
		// A minimal config with a scene_linear role but no reference /
		// aces_interchange bindings: the last-resort fallback chain.
		let cfg_text = r#"
ocio_profile_version: 2
name: quercus-fallback-test
search_path: ""
roles:
  scene_linear: Raw
displays:
  quercusdisplay:
    - !<View> {name: quercusview, colorspace: Raw}
colorspaces:
  - !<ColorSpace>
    name: Raw
    family: ""
    isdata: false
    allocation: uniform
"#;
		let Ok(cfg) = ocio_rs::Config::from_stream(cfg_text) else {
			eprintln!("OCIO config-from-stream unavailable; skipping");
			return;
		};
		// The fallback chain only runs when the first three lookups fail.
		assert!(cfg
			.color_space("reference")
			.and_then(|cs| cs.name())
			.filter(|s| !s.is_empty())
			.is_none());
		assert!(cfg
			.role_color_space("reference")
			.filter(|s| !s.is_empty())
			.is_none());
		assert!(cfg
			.role_color_space("aces_interchange")
			.filter(|s| !s.is_empty())
			.is_none());
		assert_eq!(cfg.role_color_space("scene_linear").as_deref(), Some("Raw"));
		let saved = default_config();
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) =
			Some(std::sync::Arc::new(SafeConfig(cfg)));
		let found = display_transform_result("quercusdisplay", "quercusview");
		let unknown_view = display_transform_result("quercusdisplay", "nope");
		let unknown_display = display_transform_result("nope", "quercusview");
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) = saved;

		assert!(
			found.is_ok(),
			"scene_linear fallback resolves the reference space: {found:?}"
		);
		assert_eq!(unknown_view.unwrap(), None);
		assert_eq!(unknown_display.unwrap(), None);
	}

	// ---- Additional branch coverage: no-config and explicit-config paths ----

	/// Temporarily clear the process-wide default config and restore it on
	/// drop (used by the no-config tests below; the caller must hold
	/// `config_lock`).
	struct DefaultConfigGuard(Option<std::sync::Arc<SafeConfig>>);

	impl DefaultConfigGuard {
		fn clear() -> Self {
			let saved = default_config();
			*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) = None;
			Self(saved)
		}
	}

	impl Drop for DefaultConfigGuard {
		fn drop(&mut self) {
			*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) = self.0.take();
		}
	}

	/// Temporarily set `$OCIO`, restoring the previous value on drop.
	struct OcioEnvGuard(Option<std::ffi::OsString>);

	impl OcioEnvGuard {
		fn set(value: &str) -> Self {
			let saved = std::env::var_os("OCIO");
			std::env::set_var("OCIO", value);
			Self(saved)
		}
	}

	impl Drop for OcioEnvGuard {
		fn drop(&mut self) {
			match self.0.take() {
				Some(v) => std::env::set_var("OCIO", v),
				None => std::env::remove_var("OCIO"),
			}
		}
	}

	/// Every `default_config()?` guard's `None` arm: without a process
	/// default config each factory returns `None` instead of panicking,
	/// and `display_transform_result` reports the missing-config state.
	#[test]
	fn factories_without_a_default_config_return_none() {
		let _lock = config_lock();
		let _env = OcioEnvGuard::set("");
		let _guard = DefaultConfigGuard::clear();

		assert!(ColorProcessor::create("scene_linear", "sdr-video", Direction::Normal).is_none());
		assert!(ColorProcessor::create_lut("/tmp/quercus-none.cube", Direction::Normal).is_none());
		assert!(ColorProcessor::create_grading_primary(GradingStyle::Lin).is_none());
		assert!(ColorProcessor::create_grading_primary(GradingStyle::Log).is_none());
		assert!(ColorProcessor::create_display_icc("scene_linear", "/tmp/quercus-none.icc").is_none());
		assert!(
			ColorProcessor::create_display_icc_bgra8("scene_linear", "/tmp/quercus-none.icc").is_none()
		);
		assert!(ColorProcessor::create_display_icc_xyz("/tmp/quercus-none.icc").is_none());
		assert!(ColorProcessor::create_display_icc_xyz_bgra8("/tmp/quercus-none.icc").is_none());
		assert!(ocio_function_shader("quercus_fn", "a", "b").is_none());
		assert!(grading_primary_function_shader(GradingStyle::Lin).is_none());
		assert!(grading_primary_function_shader(GradingStyle::Log).is_none());
		assert_eq!(
			display_transform_result("display", "view")
				.unwrap_err()
				.code(),
			crate::error::QUERCUSCORE_E_STATE
		);
		assert!(display_transform("display", "view").is_none());
		assert!(config_path().is_none(), "no config and empty $OCIO");
	}

	/// `set_up_default_config_from(Some(path))` loads an explicit config
	/// file and installs it as the process default (the project-properties
	/// OCIO override path), replacing the previous default.
	#[test]
	fn set_up_default_config_from_explicit_file_replaces_default() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no bundled OCIO config; skipping");
			return;
		}
		let path =
			std::env::temp_dir().join(format!("quercus-color-explicit-{}.ocio", std::process::id()));
		let cfg_text = r#"
ocio_profile_version: 2
name: quercus-explicit-test
search_path: ""
roles:
  scene_linear: Raw
  default: Raw
displays:
  quercusdisplay:
    - !<View> {name: quercusview, colorspace: Raw}
colorspaces:
  - !<ColorSpace>
    name: Raw
    family: ""
    isdata: false
    allocation: uniform
"#;
		std::fs::write(&path, cfg_text).unwrap();
		let result = set_up_default_config_from(Some(path.to_string_lossy().as_ref()));
		let installed_name = default_config().and_then(|c| c.name());
		let _ = std::fs::remove_file(&path);
		// Restore the bundled default config installed above.
		let restored = set_up_default_config_from(None);

		assert!(result.is_ok(), "an explicit valid config loads: {result:?}");
		assert_eq!(installed_name.as_deref(), Some("quercus-explicit-test"));
		assert!(
			restored.is_ok(),
			"the bundled config restores: {restored:?}"
		);
	}

	/// The XYZ display chain's build failure surfaces as `None` (not a
	/// pass-through), so the caller can fall back to the sRGB chain: a
	/// config that cannot produce the processor (unreadable ICC file)
	/// yields `Some(invalid)` from the classic builder but `None` from
	/// the XYZ wrapper.
	#[test]
	fn display_icc_xyz_returns_none_when_chain_is_invalid() {
		let _lock = config_lock();
		let cfg_text = r#"
ocio_profile_version: 2
name: quercus-xyz-test
search_path: ""
roles:
  scene_linear: Raw
  cie_xyz_d65_interchange: Raw
displays:
  quercusdisplay:
    - !<View> {name: quercusview, colorspace: Raw}
colorspaces:
  - !<ColorSpace>
    name: Raw
    family: ""
    isdata: false
    allocation: uniform
  - !<ColorSpace>
    name: Linear Rec.709 (sRGB)
    family: ""
    isdata: false
    allocation: uniform
"#;
		let Ok(cfg) = ocio_rs::Config::from_stream(cfg_text) else {
			eprintln!("OCIO config-from-stream unavailable; skipping");
			return;
		};
		// An unreadable ICC file must fail processor creation but not the
		// transform-chain assembly.
		let icc = std::env::temp_dir().join(format!("quercus-xyz-junk-{}.icc", std::process::id()));
		std::fs::write(&icc, b"this is not an ICC profile").unwrap();
		let icc = icc.to_string_lossy().into_owned();

		let _guard = DefaultConfigGuard::clear();
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) =
			Some(std::sync::Arc::new(SafeConfig(cfg)));

		let classic =
			ColorProcessor::create_display_icc("cie_xyz_d65_interchange", &icc).expect("handle");
		let classic_bgra8 =
			ColorProcessor::create_display_icc_bgra8("cie_xyz_d65_interchange", &icc)
				.expect("handle");
		let xyz = ColorProcessor::create_display_icc_xyz(&icc);
		let xyz_bgra8 = ColorProcessor::create_display_icc_xyz_bgra8(&icc);

		assert!(
			!classic.is_valid(),
			"the ICC leg fails against a junk profile (non-fatal pass-through)"
		);
		assert!(!classic_bgra8.is_valid());
		assert!(
			xyz.is_none(),
			"an invalid chain must surface as None for the XYZ wrapper"
		);
		assert!(xyz_bgra8.is_none());
		let _ = std::fs::remove_file(&icc);
	}

	/// A config whose display/view exist but whose roles do not resolve
	/// makes `display_transform_result` report `Error::State` (the
	/// `ok_or` arm of the role fallback chain).
	#[test]
	fn display_transform_result_errors_when_no_reference_role_resolves() {
		let _lock = config_lock();
		let cfg_text = r#"
ocio_profile_version: 2
name: quercus-no-roles-test
search_path: ""
displays:
  quercusdisplay:
    - !<View> {name: quercusview, colorspace: Raw}
colorspaces:
  - !<ColorSpace>
    name: Raw
    family: ""
    isdata: false
    allocation: uniform
"#;
		let Ok(cfg) = ocio_rs::Config::from_stream(cfg_text) else {
			eprintln!("OCIO config-from-stream unavailable; skipping");
			return;
		};
		let _guard = DefaultConfigGuard::clear();
		*DEFAULT_CONFIG.lock().unwrap_or_else(|e| e.into_inner()) =
			Some(std::sync::Arc::new(SafeConfig(cfg)));

		let err = display_transform_result("quercusdisplay", "quercusview")
			.expect_err("no reference role resolves to a source space");
		assert_eq!(err.code(), crate::error::QUERCUSCORE_E_STATE);
		assert!(display_transform("quercusdisplay", "quercusview").is_none());
	}

	/// `set_up_default_config` honours `$OCIO` (non-empty → that file;
	/// empty → the bundled config) and swaps the process default.
	#[test]
	fn set_up_default_config_honours_the_ocio_environment() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no bundled OCIO config; skipping");
			return;
		}
		let path = std::env::temp_dir().join(format!("quercus-color-env-{}.ocio", std::process::id()));
		let cfg_text = r#"
ocio_profile_version: 2
name: quercus-env-test
search_path: ""
roles:
  scene_linear: Raw
  default: Raw
displays:
  quercusdisplay:
    - !<View> {name: quercusview, colorspace: Raw}
colorspaces:
  - !<ColorSpace>
    name: Raw
    family: ""
    isdata: false
    allocation: uniform
"#;
		std::fs::write(&path, cfg_text).unwrap();
		let path_str = path.to_string_lossy().into_owned();

		let loaded = {
			let _env = OcioEnvGuard::set(&path_str);
			set_up_default_config()
		};
		let installed_name = default_config().and_then(|c| c.name());
		// An empty $OCIO is treated as unset: the bundled config loads.
		let bundled = {
			let _env = OcioEnvGuard::set("");
			set_up_default_config()
		};
		let _ = std::fs::remove_file(&path);

		assert!(loaded.is_ok(), "a non-empty $OCIO loads: {loaded:?}");
		assert_eq!(installed_name.as_deref(), Some("quercus-env-test"));
		assert!(bundled.is_ok(), "an empty $OCIO falls back: {bundled:?}");
	}

	/// A valid processor rejects a short F32 buffer (the `try_apply`
	/// error mapping) and the `convert_bgra8` entry point guards its
	/// staging buffer length.
	#[test]
	fn conversion_error_arms_from_buffer_size_mismatches() {
		let _lock = config_lock();
		if set_up_default_config().is_err() {
			eprintln!("no default OCIO config; skipping");
			return;
		}
		let p = ColorProcessor::create("ACEScg", "sRGB Encoded Rec.709 (sRGB)", Direction::Normal)
			.expect("handle always returned");
		if !p.is_valid() {
			eprintln!("processor unavailable in this config; skipping");
			return;
		}
		// Fewer samples than pixels * 4: the OCIO apply fails and is
		// mapped to a named error.
		let mut short = [0f32; 4];
		let err = p.convert_f32_rgba(&mut short, 2).unwrap_err();
		assert!(
			err.to_string().contains("OCIO f32 apply"),
			"the apply error is named: {err}"
		);
		// BGRA8: the staging buffer must cover pixels * 4 bytes.
		let mut bytes = [9u8; 4];
		assert_eq!(
			p.convert_bgra8(&mut bytes, 2).unwrap_err().code(),
			crate::error::QUERCUSCORE_E_INVALID
		);
	}
}