oiio 0.3.2

High-level OpenImageIO bindings over oiio-sys
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
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
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
//! Operations on [`ImageBuf`], mirroring OpenImageIO's `ImageBufAlgo`.
//!
//! Most operations write into a destination buffer and take an optional
//! region; `None` means the whole image, which is OpenImageIO's own default.
//! Because the destination is `&mut` and the sources are `&`, Rust rejects at
//! compile time the aliasing cases these functions are not written for.
//!
//! The measurements ([`pixel_stats`], [`histogram`], [`constant_color`],
//! [`is_constant_channel`], [`is_monochrome`], [`nonzero_region`],
//! [`pixel_hash_sha1`] and [`compare`]) return what they found rather than
//! filling a buffer, [`make_kernel`] and [`text_size`] return a new value, and
//! [`reorient`] takes no region because it always works on the whole image.
//!
//! # Which region, whose
//!
//! A region normally names part of the **destination**. Seven operations read
//! it as part of the **source** instead: [`paste`], the three right-angle
//! rotations, and [`flip`], [`flop`] and [`transpose`], each of which derives
//! where the result lands from where the region sat. This list is the
//! authority — the parameter is spelled `src_roi` on `paste` and the
//! rotations, while `flip`, `flop` and `transpose` inherited OpenImageIO's
//! plain `roi` name and read it as source all the same.
//!
//! ```
//! use oiio::{algo, ImageBuf, ImageSpec, PixelFormat};
//!
//! # fn main() -> oiio::Result<()> {
//! let spec = ImageSpec::new(64, 64, 3, PixelFormat::F32)?;
//! let mut background = ImageBuf::new(&spec)?;
//! algo::fill(&mut background, &[0.2, 0.4, 0.6], None)?;
//!
//! let foreground = ImageBuf::new(&spec)?;
//! let mut combined = ImageBuf::new(&spec)?;
//! algo::add(&mut combined, &background, &foreground, None)?;
//! # Ok(())
//! # }
//! ```

use crate::{sys, Error, ImageBuf, Result, Roi};

pub use sys::imagebufalgo::CompareSummary;
pub use sys::imagebufalgo::RangeCheckCounts;

/// Use every thread OpenImageIO is configured for.
const ALL_THREADS: i32 = 0;

// SAFETY, for every `unsafe` block in this module.
//
// The `imagebufalgo_*` shims are declared `unsafe fn` because they hand their
// arguments to OpenImageIO unchecked, and OpenImageIO trusts them: a region
// whose channel range starts past the destination's last channel comes back
// inverted out of `IBAprep`'s intersection and is then used as an unsigned
// length. See `region_in`, which is what makes these calls sound and which
// every one of them goes through. The other arguments are plain values, slices
// whose lengths the shims re-derive, and `ImageBuf` references that cannot be
// null because they come from `&`/`&mut` here.

fn region(roi: Option<Roi>) -> sys::imageio::ROI {
    // An undefined ROI is how OpenImageIO spells "the whole image".
    roi.map_or_else(sys::imageio::roi_default, Roi::to_sys)
}

/// A region validated against the image the operation will write into.
///
/// `IBAprep` starts every operation with
/// `roi = roi_intersection(roi, get_roi(dst->spec()))`, and `roi_intersection`
/// takes the larger begin and the smaller end. A channel range that starts past
/// the destination's last channel therefore comes back INVERTED -- 5..8 against
/// 0..3 gives chbegin 5, chend 3 -- and `ROI::nchannels()` is then -2. The
/// kernels turn that straight into an unsigned length: `zero` reaches
/// `memcpy(.., nchannels * sizeof(T))` with `(size_t)-8`, from an address
/// already five floats into a three float pixel.
///
/// The rule is the one that cannot invert: the channel range must exist in the
/// destination when the destination is already allocated, and must start at
/// channel zero when it is not, since `IBAprep` then builds the destination
/// from this very region and intersects against what it just built.
fn region_in(roi: Option<Roi>, dst: &ImageBuf) -> Result<sys::imageio::ROI> {
    if let Some(roi) = roi {
        let channels = roi.channels();
        let available = dst.channel_count();
        if dst.is_initialized() {
            if channels.start >= available {
                return Err(Error::InvalidRoi(format!(
                    "the region starts at channel {} and the destination has {available}",
                    channels.start
                )));
            }
        } else if channels.start != 0 {
            return Err(Error::InvalidRoi(format!(
                "the region starts at channel {}; a destination that is not                  allocated yet is built from the region itself, so the region                  must begin at channel zero",
                channels.start
            )));
        }
    }
    Ok(region(roi))
}

fn finish(dst: &mut ImageBuf, operation: &'static str, succeeded: bool) -> Result<()> {
    if succeeded {
        Ok(())
    } else {
        Err(Error::operation(operation, dst.take_error()))
    }
}

/// Set every channel in the region to zero.
pub fn zero(dst: &mut ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded =
        unsafe { sys::imagebufalgo::imagebufalgo_zero(dst.inner_mut(), &roi, ALL_THREADS) };
    finish(dst, "zero", succeeded)
}

/// Fill the region with one value per channel.
///
/// Fewer values than the image has channels repeats the last one across the
/// rest — so filling an RGBA image with three values sets alpha to the blue
/// value, not to nothing. Narrow the region's channel range to fill only some
/// channels.
pub fn fill(dst: &mut ImageBuf, values: &[f32], roi: Option<Roi>) -> Result<()> {
    if values.is_empty() {
        return Err(Error::InvalidImageSpec(
            "fill needs at least one channel value".to_owned(),
        ));
    }
    let roi = region_in(roi, dst)?;
    let succeeded =
        unsafe { sys::imagebufalgo::imagebufalgo_fill(dst.inner_mut(), values, &roi, ALL_THREADS) };
    finish(dst, "fill", succeeded)
}

macro_rules! binary_operation {
    ($name:ident, $constant_name:ident, $images:path, $constants:path, $label:literal) => {
        #[doc = concat!("Compute `a ", $label, " b` into `dst`.")]
        pub fn $name(
            dst: &mut ImageBuf,
            a: &ImageBuf,
            b: &ImageBuf,
            roi: Option<Roi>,
        ) -> Result<()> {
            let roi = region_in(roi, dst)?;
            let succeeded =
                unsafe { $images(dst.inner_mut(), a.inner(), b.inner(), &roi, ALL_THREADS) };
            finish(dst, $label, succeeded)
        }

        #[doc = concat!("Compute `a ", $label, " values` into `dst`, one value per channel.")]
        pub fn $constant_name(
            dst: &mut ImageBuf,
            a: &ImageBuf,
            values: &[f32],
            roi: Option<Roi>,
        ) -> Result<()> {
            if values.is_empty() {
                return Err(Error::InvalidImageSpec(
                    "this operation needs at least one channel value".to_owned(),
                ));
            }
            let roi = region_in(roi, dst)?;
            let succeeded =
                unsafe { $constants(dst.inner_mut(), a.inner(), values, &roi, ALL_THREADS) };
            finish(dst, $label, succeeded)
        }
    };
}

binary_operation!(
    add,
    add_constant,
    sys::imagebufalgo::imagebufalgo_add_images,
    sys::imagebufalgo::imagebufalgo_add_constant,
    "add"
);
binary_operation!(
    sub,
    sub_constant,
    sys::imagebufalgo::imagebufalgo_sub_images,
    sys::imagebufalgo::imagebufalgo_sub_constant,
    "subtract"
);
binary_operation!(
    mul,
    mul_constant,
    sys::imagebufalgo::imagebufalgo_mul_images,
    sys::imagebufalgo::imagebufalgo_mul_constant,
    "multiply"
);
binary_operation!(
    div,
    div_constant,
    sys::imagebufalgo::imagebufalgo_div_images,
    sys::imagebufalgo::imagebufalgo_div_constant,
    "divide"
);

/// Fill the region with a vertical gradient.
///
/// The ramp runs over the *region*, not the image, so filling part of an image
/// gives a complete gradient inside that part rather than a slice of a longer
/// one. A region one pixel tall is entirely `top`.
pub fn fill_gradient(
    dst: &mut ImageBuf,
    top: &[f32],
    bottom: &[f32],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fill_vertical(
            dst.inner_mut(),
            top,
            bottom,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "fill gradient", succeeded)
}

/// Fill the region by interpolating between four corner colours.
pub fn fill_corners(
    dst: &mut ImageBuf,
    top_left: &[f32],
    top_right: &[f32],
    bottom_left: &[f32],
    bottom_right: &[f32],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fill_corners(
            dst.inner_mut(),
            top_left,
            top_right,
            bottom_left,
            bottom_right,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "fill corners", succeeded)
}

/// Fill the region with a checkerboard.
///
/// `size` is one square's width, height and depth; each must be at least one,
/// because OpenImageIO divides the coordinate by them without checking.
/// `offset` shifts the pattern.
pub fn checker(
    dst: &mut ImageBuf,
    size: [u32; 3],
    color1: &[f32],
    color2: &[f32],
    offset: [i32; 3],
    roi: Option<Roi>,
) -> Result<()> {
    let dimension = |name: &'static str, value: u32| {
        i32::try_from(value)
            .map_err(|_| Error::InvalidImageSpec(format!("checker {name} exceeds i32::MAX")))
    };
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_checker(
            dst.inner_mut(),
            dimension("width", size[0])?,
            dimension("height", size[1])?,
            dimension("depth", size[2])?,
            color1,
            color2,
            offset[0],
            offset[1],
            offset[2],
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "checker", succeeded)
}

/// Which kind of noise [`noise`] should add, and its parameters.
///
/// Each variant names what OpenImageIO's two anonymous floats mean for it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Noise {
    /// Normally distributed, about a mean and by a standard deviation.
    Gaussian {
        /// The centre of the distribution.
        mean: f32,
        /// Its spread.
        standard_deviation: f32,
    },
    /// Evenly distributed between two values.
    Uniform {
        /// The smallest value.
        min: f32,
        /// The largest.
        max: f32,
    },
    /// Evenly distributed, but spread out in space so nearby pixels differ —
    /// which looks less clumpy than uniform noise at the same amplitude.
    Blue {
        /// The smallest value.
        min: f32,
        /// The largest.
        max: f32,
    },
    /// Set a portion of the pixels to one value, and leave the rest alone.
    ///
    /// This is the one kind that assigns rather than adds.
    Salt {
        /// The value written.
        value: f32,
        /// The fraction of pixels to write, from 0 to 1.
        portion: f32,
    },
}

impl Noise {
    fn parts(self) -> (&'static str, f32, f32) {
        match self {
            Self::Gaussian {
                mean,
                standard_deviation,
            } => ("gaussian", mean, standard_deviation),
            Self::Uniform { min, max } => ("uniform", min, max),
            Self::Blue { min, max } => ("blue", min, max),
            Self::Salt { value, portion } => ("salt", value, portion),
        }
    }
}

/// Add noise to the region.
///
/// This **adds** to what the destination already holds — every kind but
/// [`Noise::Salt`], which assigns. To generate noise rather than dirty an
/// existing image, start from [`zero`].
///
/// `mono` draws one value per pixel rather than one per channel, so the noise
/// is grey rather than coloured. `seed` makes the result repeatable.
pub fn noise(
    dst: &mut ImageBuf,
    kind: Noise,
    mono: bool,
    seed: i32,
    roi: Option<Roi>,
) -> Result<()> {
    let (name, a, b) = kind.parts();
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_noise(
            dst.inner_mut(),
            name,
            a,
            b,
            mono,
            seed,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "noise", succeeded)
}

/// Set one pixel.
///
/// A position outside the region is a silent no-op, which is OpenImageIO's
/// behaviour rather than an error. Drawing only happens on the `z = 0` plane.
pub fn render_point(
    dst: &mut ImageBuf,
    x: i32,
    y: i32,
    color: &[f32],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_render_point(
            dst.inner_mut(),
            x,
            y,
            color,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "render point", succeeded)
}

/// Draw a line between two points, both included.
///
/// `skip_first_point` leaves the starting pixel alone, which is what you want
/// when drawing a chain of lines so the joints are not blended twice.
///
/// The colour is blended by its alpha. A colour with fewer values than the
/// image has channels repeats its last value, so a three-value colour on an
/// RGBA image gives alpha the red value's neighbour rather than one — pass all
/// four to be sure.
pub fn render_line(
    dst: &mut ImageBuf,
    from: [i32; 2],
    to: [i32; 2],
    color: &[f32],
    skip_first_point: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_render_line(
            dst.inner_mut(),
            from[0],
            from[1],
            to[0],
            to[1],
            color,
            skip_first_point,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "render line", succeeded)
}

/// Draw a box, outlined or filled. Both corners are included.
///
/// A filled box needs its first corner above and to the left of its second;
/// OpenImageIO draws nothing for the other order and calls it success, so that
/// is refused here. An outline accepts either order.
pub fn render_box(
    dst: &mut ImageBuf,
    corner: [i32; 2],
    opposite: [i32; 2],
    color: &[f32],
    fill: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_render_box(
            dst.inner_mut(),
            corner[0],
            corner[1],
            opposite[0],
            opposite[1],
            color,
            fill,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "render box", succeeded)
}

/// Where text sits relative to the position given for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum TextAlignX {
    /// The position is the text's left edge.
    #[default]
    Left,
    /// The position is its right edge.
    Right,
    /// The position is its horizontal centre.
    Center,
}

/// Where text sits vertically relative to the position given for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum TextAlignY {
    /// The position is the baseline the letters stand on.
    #[default]
    Baseline,
    /// The position is the top of the text.
    Top,
    /// The position is the bottom, below any descenders.
    Bottom,
    /// The position is its vertical centre.
    Center,
}

/// How [`render_text`] should draw.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TextOptions<'a> {
    /// Height in pixels. Must be at least one.
    pub size: u32,
    /// The font's name or path. Empty asks OpenImageIO for its default, which
    /// it may not have; an unfindable font is an error.
    pub font: &'a str,
    /// One value per channel. Blended by its alpha, as [`render_line`] notes.
    pub color: &'a [f32],
    /// Horizontal placement relative to the position.
    pub align_x: TextAlignX,
    /// Vertical placement relative to the position.
    pub align_y: TextAlignY,
    /// Draw a dark halo this many pixels wide behind the text, so it stays
    /// legible over a busy image. Zero for none.
    pub shadow: u32,
}

impl Default for TextOptions<'_> {
    fn default() -> Self {
        Self {
            size: 16,
            font: "",
            color: &[1.0],
            align_x: TextAlignX::default(),
            align_y: TextAlignY::default(),
            shadow: 0,
        }
    }
}

/// Draw text into the image.
///
/// Text with nothing to draw — empty, or only line breaks — is refused.
/// OpenImageIO measures an inverted bounding box for it and then builds an
/// image from that box without checking, so its width underflows.
///
/// This needs a font. OpenImageIO looks in its own search path and in the
/// system's; if it was built without FreeType, or cannot find the font named,
/// the call fails.
pub fn render_text(
    dst: &mut ImageBuf,
    position: [i32; 2],
    text: &str,
    options: &TextOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let (size, shadow) = text_metrics(options.size, options.shadow)?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_render_text(
            dst.inner_mut(),
            position[0],
            position[1],
            text,
            size,
            options.font,
            options.color,
            options.align_x as i32,
            options.align_y as i32,
            shadow,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "render text", succeeded)
}

/// Measure what [`render_text`] would draw, without drawing it.
///
/// The region is where the text would land if drawn at the origin, so its width
/// and height are the text's size.
///
/// OpenImageIO reports failure here by returning nothing at all — no message,
/// on the buffer or anywhere else — so a missing font and unrenderable text
/// come back as the same error.
///
/// It also measures only x and y, leaving the region's depth and channel
/// ranges empty; `render_text` completes them for its own use and this does the
/// same, so the region that comes back is one you can actually pass on.
pub fn text_size(text: &str, size: u32, font: &str) -> Result<Roi> {
    let (size, _) = text_metrics(size, 0)?;
    let measured = unsafe { sys::imagebufalgo::imagebufalgo_text_size(text, size, font) };
    Roi::from_sys_optional(measured)?.ok_or_else(|| {
        Error::operation(
            "text size",
            "nothing could be measured; the text may be empty, or the font \
             missing, and OpenImageIO does not say which"
                .to_owned(),
        )
    })
}

fn text_metrics(size: u32, shadow: u32) -> Result<(i32, i32)> {
    let size = i32::try_from(size)
        .map_err(|_| Error::InvalidImageSpec("font size exceeds i32::MAX".to_owned()))?;
    if size < 1 {
        return Err(Error::InvalidImageSpec(
            "the font size must be at least 1".to_owned(),
        ));
    }
    let shadow = i32::try_from(shadow)
        .map_err(|_| Error::InvalidImageSpec("shadow width exceeds i32::MAX".to_owned()))?;
    Ok((size, shadow))
}

/// Composite each pixel's deep samples down into one flat pixel.
///
/// Samples are combined front to back, so the nearest opaque one hides what is
/// behind it. This is how a deep render becomes an ordinary image.
///
/// The source needs an alpha channel — OpenImageIO finds it by name, accepting
/// `A`, `Alpha`, the per-component `AR`/`AG`/`AB`, and any name ending in
/// `.A` — and fails without one. A pixel with no samples comes back with its
/// depth at 1e30 and its colours at zero.
///
/// The destination must not have more channels than the source, which is a
/// restriction of OpenImageIO's rather than of the operation: its per-pixel
/// accumulator is sized from the source and indexed up to the wider of the two.
///
/// A source that is already flat is copied wholesale, region and all, which is
/// OpenImageIO's documented behaviour.
///
/// The compositing assumes each pixel's samples are sorted and do not overlap.
/// OpenImageIO says so itself, in a comment on the code; a file that does not
/// satisfy that gives a wrong answer rather than an error.
pub fn flatten(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_flatten(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "flatten", succeeded)
}

/// Turn a flat image into a deep one, with at most one sample per pixel.
///
/// A pixel gets a sample when any channel other than depth — `Z` and `Zback`
/// both count as depth here — is non-zero. When the source has its own `Z`
/// channel, a pixel whose only non-zero channel is that depth also gets a
/// sample, provided the depth is below OpenImageIO's 1e30 "infinitely far"
/// cutoff; a source without a `Z` channel gets no such consideration. Depth
/// comes from the source's own `Z` channel if it has one — in which case
/// `z_value` is ignored — and from `z_value` otherwise, with a `Z` channel
/// appended to hold it.
///
/// The destination must be empty, so it can take the deep, floating-point
/// specification this builds. OpenImageIO would otherwise keep a pre-allocated
/// destination's shape and silently drop the writes that do not fit.
pub fn deepen(dst: &mut ImageBuf, src: &ImageBuf, z_value: f32, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_deepen(
            dst.inner_mut(),
            src.inner(),
            z_value,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "deepen", succeeded)
}

/// Merge two deep images, interleaving their samples by depth.
///
/// Overlapping samples are split at each other's depths so the result stays
/// sortable. `occlusion_cull` then drops samples hidden behind an opaque one,
/// which is usually what you want and is OpenImageIO's default.
///
/// All three images must be deep and must have the same channels, in the same
/// order and by the same names.
///
/// This is expensive: the pass that reserves room is quadratic in the number of
/// samples per pixel and runs on one thread, so a dense volumetric image is
/// slow in a way nothing in the signature suggests.
pub fn deep_merge(
    dst: &mut ImageBuf,
    a: &ImageBuf,
    b: &ImageBuf,
    occlusion_cull: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_deep_merge(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            occlusion_cull,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "deep merge", succeeded)
}

/// Keep only the samples of `src` in front of `holdout`'s opaque frontier.
///
/// This is the deep equivalent of masking one render against another: whatever
/// `holdout` hides is removed from `src`.
///
/// Only `holdout`'s depths and alpha matter; its other channels are not read,
/// and it need not share `src`'s channel layout. If `holdout` has no alpha,
/// OpenImageIO quietly uses its nearest sample instead of a real opacity
/// frontier, which is a different operation than the one asked for.
///
/// As with [`flatten`], the samples are assumed sorted by depth.
pub fn deep_holdout(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    holdout: &ImageBuf,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_deep_holdout(
            dst.inner_mut(),
            src.inner(),
            holdout.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "deep holdout", succeeded)
}

/// Build a convolution kernel by name.
///
/// The name is a reconstruction filter: `"gaussian"`, `"box"`, `"triangle"`,
/// `"catmull-rom"`, `"blackman-harris"`, `"sinc"`, `"lanczos3"`, `"mitchell"`,
/// `"b-spline"`, `"disk"`, `"binomial"`, `"laplacian"` and a few more. An
/// unknown name is an error rather than a silent fall back to a box, which is
/// what OpenImageIO does on its own.
///
/// The result is centred on the origin, which is what [`convolve`] expects. A
/// kernel read from a file has its origin at a corner instead, and convolving
/// with one shifts the image by half its size.
///
/// `normalize` scales the kernel to sum to one. Leave it off for a kernel that
/// is meant to sum to zero, such as `"laplacian"`.
pub fn make_kernel(name: &str, width: f32, height: f32, normalize: bool) -> Result<ImageBuf> {
    let mut kernel = ImageBuf::empty()?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_make_kernel(
            kernel.inner_mut(),
            name,
            width,
            height,
            1.0,
            normalize,
        )
    };
    if succeeded {
        Ok(kernel)
    } else {
        Err(Error::operation("make kernel", kernel.take_error()))
    }
}

/// Convolve with a kernel image.
///
/// The kernel's own origin is the filter's centre, so use [`make_kernel`],
/// which centres it. An empty kernel is refused: OpenImageIO would divide by
/// its zero sum and fill the result with `NaN` while reporting success.
pub fn convolve(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    kernel: &ImageBuf,
    normalize: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_convolve(
            dst.inner_mut(),
            src.inner(),
            kernel.inner(),
            normalize,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "convolve", succeeded)
}

/// Apply the 3x3 Laplacian, an edge detector.
///
/// The result is a signed second derivative and is not normalised, so it holds
/// negative values. Give it a floating-point destination; an integer one clamps
/// everything below zero away.
pub fn laplacian(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_laplacian(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "laplacian", succeeded)
}

/// Sharpen by subtracting a blurred copy.
///
/// `kernel` is the blur to subtract — `"gaussian"` by default, or the special
/// name `"median"` for a median blur, which sharpens without haloing an edge.
/// `contrast` scales the difference added back, and `threshold` leaves
/// differences smaller than itself alone, so grain is not amplified.
///
/// The destination must either be empty or hold the same pixel type as the
/// source. OpenImageIO reads the source through an iterator of the
/// *destination's* type without converting, so a mismatch would misread the
/// source and, for a wider destination type, read past its end.
pub fn unsharp_mask(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    kernel: &str,
    width: f32,
    contrast: f32,
    threshold: f32,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_unsharp_mask(
            dst.inner_mut(),
            src.inner(),
            kernel,
            width,
            contrast,
            threshold,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "unsharp mask", succeeded)
}

/// Replace each pixel with the median of its neighbourhood.
///
/// This removes salt-and-pepper noise without softening edges, which a blur
/// would. `height` of `None` matches the width.
///
/// The window must be at least two across. OpenImageIO accepts one and returns
/// the image translated by a pixel rather than unchanged, so that is refused
/// here.
pub fn median_filter(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    width: u32,
    height: Option<u32>,
    roi: Option<Roi>,
) -> Result<()> {
    let (width, height) = window("median filter", width, height)?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_median_filter(
            dst.inner_mut(),
            src.inner(),
            width,
            height,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "median filter", succeeded)
}

/// Grow the bright areas: each pixel becomes the maximum of its neighbourhood.
///
/// `height` of `None` matches the width, and the window must be at least two
/// across, as [`median_filter`] explains.
pub fn dilate(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    width: u32,
    height: Option<u32>,
    roi: Option<Roi>,
) -> Result<()> {
    let (width, height) = window("dilate", width, height)?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_dilate(
            dst.inner_mut(),
            src.inner(),
            width,
            height,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "dilate", succeeded)
}

/// Shrink the bright areas: each pixel becomes the minimum of its
/// neighbourhood.
///
/// `height` of `None` matches the width, and the window must be at least two
/// across, as [`median_filter`] explains.
pub fn erode(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    width: u32,
    height: Option<u32>,
    roi: Option<Roi>,
) -> Result<()> {
    let (width, height) = window("erode", width, height)?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_erode(
            dst.inner_mut(),
            src.inner(),
            width,
            height,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "erode", succeeded)
}

fn window(operation: &str, width: u32, height: Option<u32>) -> Result<(i32, i32)> {
    let to_i32 = |value: u32| {
        i32::try_from(value)
            .map_err(|_| Error::InvalidImageSpec(format!("{operation} window exceeds i32::MAX")))
    };
    Ok((
        to_i32(width)?,
        height.map(to_i32).transpose()?.unwrap_or(-1),
    ))
}

/// Transform one channel into the frequency domain.
///
/// The result is always a two-channel float image at the origin — real part
/// first, imaginary part second — whatever the destination held before.
///
/// Only one channel is transformed: the region's first, or channel zero. The
/// region also defaults to the union of the data and display windows rather
/// than to the data window alone, so an image whose pixels are smaller than its
/// display window is transformed with the difference zero-padded.
pub fn fft(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fft(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "fft", succeeded)
}

/// Transform back out of the frequency domain.
///
/// The source must be the two-channel complex image [`fft`] produces, and its
/// pixels must be in memory: a buffer still attached to a file has no pixel
/// address, and OpenImageIO would dereference the null it gets back. Call
/// [`ImageBuf::read`](crate::ImageBuf::read) first if in doubt.
pub fn ifft(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_ifft(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "ifft", succeeded)
}

/// Convert a two-channel magnitude-and-phase image into real and imaginary
/// parts.
///
/// Both images need exactly two channels. Phase is in radians.
///
/// (OpenImageIO's header describes this the other way round. The name is right
/// and the prose is wrong; this converts *from* polar.)
pub fn polar_to_complex(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_polar_to_complex(
            dst.inner_mut(),
            src.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "polar to complex", succeeded)
}

/// Convert a two-channel real-and-imaginary image into magnitude and phase.
///
/// Both images need exactly two channels. The phase comes back in `0..2Ï€`,
/// not `-Ï€..Ï€`.
pub fn complex_to_polar(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_complex_to_polar(
            dst.inner_mut(),
            src.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "complex to polar", succeeded)
}

/// Settings the OpenColorIO operations share.
///
/// [`Default`] matches OpenImageIO's own defaults, which means `unpremult` is
/// **on**: colour is divided by alpha before the transform and multiplied back
/// after, which is what a premultiplied image needs.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct OcioOptions<'a> {
    /// Divide colour by alpha before transforming and multiply back after.
    ///
    /// OpenImageIO ignores this when the region covers fewer than four
    /// channels, or when the source is marked as holding unassociated alpha.
    pub unpremult: bool,
    /// Apply the transform backwards.
    pub inverse: bool,
    /// An OpenColorIO context key, or several separated by commas.
    ///
    /// Keys and values are matched up pairwise. If the two lists are different
    /// lengths, or only one is given, OpenImageIO discards the context without
    /// saying so.
    pub context_key: &'a str,
    /// The value, or values, for [`context_key`](Self::context_key).
    pub context_value: &'a str,
}

impl Default for OcioOptions<'_> {
    fn default() -> Self {
        Self {
            unpremult: true,
            inverse: false,
            context_key: "",
            context_value: "",
        }
    }
}

/// Transform colours by a 4x4 matrix.
///
/// `matrix` is sixteen values in row order, applied as a row vector times the
/// matrix, so elements 12, 13 and 14 are the translation.
///
/// Two consequences of OpenImageIO applying this as a four-component transform
/// are worth knowing. The fourth component is the alpha channel when the image
/// has one and zero when it does not, so on an RGB image the translation row is
/// multiplied by zero and has no effect; and on an RGBA image, a matrix whose
/// fourth column is not `(0, 0, 0, 1)` changes alpha as well as colour.
///
/// This does not consult OpenColorIO, and does not update the image's recorded
/// colour space, which will go on claiming whatever the source said.
pub fn color_matrix_transform(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    matrix: &[f32; 16],
    unpremult: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_colormatrixtransform(
            dst.inner_mut(),
            src.inner(),
            matrix,
            unpremult,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "colour matrix transform", succeeded)
}

/// Apply one or more OpenColorIO looks.
///
/// `looks` is a comma- or colon-separated list, each optionally prefixed `+` or
/// `-` to apply it forwards or backwards. An empty list is allowed, and gives a
/// plain conversion from one space to the other.
///
/// `from_space` and `to_space` of `None` mean the source's own recorded colour
/// space, falling back to the configuration's `scene_linear` role.
pub fn ocio_look(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    looks: &str,
    from_space: Option<&str>,
    to_space: Option<&str>,
    options: &OcioOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_ociolook(
            dst.inner_mut(),
            src.inner(),
            looks,
            from_space.unwrap_or_default(),
            to_space.unwrap_or_default(),
            options.unpremult,
            options.inverse,
            options.context_key,
            options.context_value,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "OpenColorIO look", succeeded)
}

/// Apply an OpenColorIO display and view transform.
///
/// This is what turns a rendered image into one to put on a particular screen.
/// `from_space` of `None` means the source's own recorded colour space.
// Eight arguments, one past clippy's limit. The display, the view, the source
// space and the looks are four independent names with no natural grouping —
// inventing a struct to hold them would obscure the call rather than clarify
// it, and OpenImageIO's own signature has them separate for the same reason.
#[allow(clippy::too_many_arguments)]
pub fn ocio_display(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    display: &str,
    view: &str,
    from_space: Option<&str>,
    looks: &str,
    options: &OcioOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_ociodisplay(
            dst.inner_mut(),
            src.inner(),
            display,
            view,
            from_space.unwrap_or_default(),
            looks,
            options.unpremult,
            options.inverse,
            options.context_key,
            options.context_value,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "OpenColorIO display", succeeded)
}

/// Apply a transform read from a file: a LUT, a `.cube`, a `.clf`, or anything
/// else OpenColorIO's file transform accepts.
///
/// The file is the whole transform, so there are no colour spaces to name.
///
/// On success OpenColorIO may retag the result's colour space from the
/// transform file's own path, if that path matches one of the configuration's
/// file rules — so the name of your LUT can change what the image claims to be.
pub fn ocio_file_transform(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    transform_path: &std::path::Path,
    options: &OcioOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let name = crate::path_to_utf8(transform_path)?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_ociofiletransform(
            dst.inner_mut(),
            src.inner(),
            name,
            options.unpremult,
            options.inverse,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "OpenColorIO file transform", succeeded)
}

/// Apply a transform the OpenColorIO configuration defines by name.
pub fn ocio_named_transform(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    name: &str,
    options: &OcioOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_ocionamedtransform(
            dst.inner_mut(),
            src.inner(),
            name,
            options.unpremult,
            options.inverse,
            options.context_key,
            options.context_value,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "OpenColorIO named transform", succeeded)
}

/// What [`pixel_stats`] measured, one entry per channel of the source.
///
/// Every vector has the source's channel count, not the region's, so a region
/// that names fewer channels still reports every channel; those it did not
/// visit have a [`finite_count`](Self::finite_count) of zero.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PixelStats {
    /// The smallest finite value seen.
    pub min: Vec<f32>,
    /// The largest finite value seen.
    pub max: Vec<f32>,
    /// The mean of the finite values.
    pub average: Vec<f32>,
    /// The population standard deviation of the finite values.
    pub standard_deviation: Vec<f32>,
    /// How many values were `NaN`.
    pub nan_count: Vec<u64>,
    /// How many were infinite.
    pub infinite_count: Vec<u64>,
    /// How many were neither, and so contributed to the figures above.
    pub finite_count: Vec<u64>,
}

/// Measure each channel: range, mean, spread, and how many values were not
/// finite.
///
/// `NaN` and infinity are counted rather than folded into the average, so a
/// render with a handful of bad pixels still reports a usable range. A channel
/// with no finite values at all reports zeroes; its
/// [`finite_count`](PixelStats::finite_count) is what distinguishes that from
/// a channel that really is all zero.
///
/// Deep images are refused: their samples are not one value per pixel, so a
/// per-pixel mean would not mean anything.
pub fn pixel_stats(src: &ImageBuf, roi: Option<Roi>) -> Result<PixelStats> {
    let roi = region_in(roi, src)?;
    let stats =
        unsafe { sys::imagebufalgo::imagebufalgo_pixel_stats(src.inner(), &roi, ALL_THREADS) };
    if !stats.ok {
        return Err(Error::operation("pixel statistics", stats.error));
    }
    Ok(PixelStats {
        min: stats.min,
        max: stats.max,
        average: stats.average,
        standard_deviation: stats.standard_deviation,
        nan_count: stats.nan_count,
        infinite_count: stats.infinite_count,
        finite_count: stats.finite_count,
    })
}

/// Count how many pixels of one channel fall in each of `bins` equal buckets
/// spanning `range`.
///
/// Values outside `range` are counted in the nearest bucket rather than
/// discarded, so the totals always add up to the number of pixels examined.
///
/// `ignore_empty` skips pixels that are zero in every channel of the region,
/// which is how to exclude the transparent surround of a render.
pub fn histogram(
    src: &ImageBuf,
    channel: u32,
    bins: u32,
    range: std::ops::Range<f32>,
    ignore_empty: bool,
    roi: Option<Roi>,
) -> Result<Vec<u64>> {
    let channel = i32::try_from(channel)
        .map_err(|_| Error::InvalidImageSpec("channel exceeds i32::MAX".to_owned()))?;
    let bins = i32::try_from(bins)
        .map_err(|_| Error::InvalidImageSpec("bin count exceeds i32::MAX".to_owned()))?;
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let counts = unsafe {
        sys::imagebufalgo::imagebufalgo_histogram(
            src.inner(),
            channel,
            bins,
            range.start,
            range.end,
            ignore_empty,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if counts.is_empty() {
        return Err(Error::operation("histogram", message));
    }
    Ok(counts.into_iter().collect())
}

/// The colour every pixel shares, if they all share one.
///
/// `None` means the image varies. The colour is one value per channel of the
/// source, with channels outside the region zeroed.
///
/// A `threshold` of zero compares the stored values exactly, in the image's
/// own format, without converting each to `f32` first. For the formats
/// narrower than `f32` that conversion is exact, so the answer matches; for
/// a wider format — `f64`, `u32`, `i32` — the native comparison is the
/// stricter one, and distinguishes values a conversion to `f32` would
/// collapse, such as `u32` values past the 24-bit mantissa.
///
/// The region must begin at channel zero. OpenImageIO sizes its reference
/// buffer to the region's channel count but fills it by absolute channel
/// number, so a region starting higher writes past the end of that buffer.
pub fn constant_color(
    src: &ImageBuf,
    threshold: f32,
    roi: Option<Roi>,
) -> Result<Option<Vec<f32>>> {
    let channels = src.spec()?.channel_count() as usize;
    let mut color = vec![0.0_f32; channels];
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let constant = unsafe {
        sys::imagebufalgo::imagebufalgo_is_constant_color(
            src.inner(),
            threshold,
            &mut color,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if constant {
        return Ok(Some(color));
    }
    if message.is_empty() {
        // Not constant, which is an answer rather than a failure.
        Ok(None)
    } else {
        Err(Error::operation("constant colour", message))
    }
}

/// Whether one channel holds `value` everywhere in the region.
///
/// The channel must exist: OpenImageIO answers a bad channel index with the
/// same `false` it uses for "not constant", so this reports an error instead.
pub fn is_constant_channel(
    src: &ImageBuf,
    channel: u32,
    value: f32,
    threshold: f32,
    roi: Option<Roi>,
) -> Result<bool> {
    let channel = i32::try_from(channel)
        .map_err(|_| Error::InvalidImageSpec("channel exceeds i32::MAX".to_owned()))?;
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let constant = unsafe {
        sys::imagebufalgo::imagebufalgo_is_constant_channel(
            src.inner(),
            channel,
            value,
            threshold,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if !constant && !message.is_empty() {
        return Err(Error::operation("constant channel", message));
    }
    Ok(constant)
}

/// Whether every channel of each pixel holds that pixel's first channel.
///
/// This is a per-pixel test, so a greyscale gradient is monochrome. Alpha
/// counts, which is rarely what you want: narrow the region to the colour
/// channels, or an opaque grey image reports false because alpha is 1 where
/// the colours are not.
pub fn is_monochrome(src: &ImageBuf, threshold: f32, roi: Option<Roi>) -> Result<bool> {
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let monochrome = unsafe {
        sys::imagebufalgo::imagebufalgo_is_monochrome(
            src.inner(),
            threshold,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if !monochrome && !message.is_empty() {
        return Err(Error::operation("monochrome test", message));
    }
    Ok(monochrome)
}

/// The smallest region outside which every pixel is black.
///
/// `None` means there is nothing but black. This is how to trim the empty
/// surround from a render before writing it.
///
/// A pixel counts as black only when every channel of the region is exactly
/// zero, alpha included, so an image with alpha 1 over a black background does
/// not shrink at all. The search trims one row or column at a time, so it costs
/// a pass per edge rather than a single pass over the image.
///
/// The region must begin at channel zero, for the reason
/// [`constant_color`] gives: this is built on it.
pub fn nonzero_region(src: &ImageBuf, roi: Option<Roi>) -> Result<Option<Roi>> {
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let found = unsafe {
        sys::imagebufalgo::imagebufalgo_nonzero_region(src.inner(), &roi, ALL_THREADS, &mut message)
    };
    if !message.is_empty() {
        return Err(Error::operation("nonzero region", message));
    }
    Roi::from_sys_optional(found)
}

/// A SHA-1 digest of the region's pixels, as hexadecimal.
///
/// This hashes the bytes as the image stores them, not the values they mean, so
/// the same picture held as `half` and as `f32` gives different digests. It is
/// for asking "did this file's pixels change", not "do these two images look
/// the same"; [`compare`] answers that.
///
/// `extra_info` is mixed into the digest, so a caller can bind it to something
/// beyond the pixels.
///
/// A region narrower than the image gives an answer that depends on how the
/// buffer was loaded, so prefer a full-width region or none at all.
pub fn pixel_hash_sha1(src: &ImageBuf, extra_info: &str, roi: Option<Roi>) -> Result<String> {
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let digest = unsafe {
        sys::imagebufalgo::imagebufalgo_pixel_hash_sha1(
            src.inner(),
            extra_info,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if digest.is_empty() {
        return Err(Error::operation("pixel hash", message));
    }
    Ok(digest)
}

/// Rotate a quarter turn clockwise.
///
/// The region selects part of the **source**, not of the destination; the
/// module documentation lists the seven operations that do, `flip`, `flop` and
/// `transpose` among them. Prefer an empty destination: OpenImageIO installs the rotated
/// display window only when it allocates one itself, and reads a pre-allocated
/// destination's display window while writing, so one that disagrees with the
/// source's yields silently offset pixels.
pub fn rotate_90(dst: &mut ImageBuf, src: &ImageBuf, src_roi: Option<Roi>) -> Result<()> {
    let roi = region(src_roi);
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rotate90(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "rotate 90", succeeded)
}

/// Rotate a half turn. See [`rotate_90`] for how the region is read.
pub fn rotate_180(dst: &mut ImageBuf, src: &ImageBuf, src_roi: Option<Roi>) -> Result<()> {
    let roi = region(src_roi);
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rotate180(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "rotate 180", succeeded)
}

/// Rotate three quarters clockwise. See [`rotate_90`] for how the region is
/// read.
pub fn rotate_270(dst: &mut ImageBuf, src: &ImageBuf, src_roi: Option<Roi>) -> Result<()> {
    let roi = region(src_roi);
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rotate270(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "rotate 270", succeeded)
}

/// Undo the source's `Orientation` attribute, so the image is stored the way
/// it should be displayed.
///
/// This is the operation for a photograph a camera stored sideways with a tag
/// saying so. It has no region: it always works on the whole image.
///
/// An `Orientation` outside the eight EXIF values is an error.
pub fn reorient(dst: &mut ImageBuf, src: &ImageBuf) -> Result<()> {
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_reorient(dst.inner_mut(), src.inner(), ALL_THREADS)
    };
    finish(dst, "reorient", succeeded)
}

/// How [`warp`], [`rotate`] and [`st_warp`] should resample, and what to do at
/// the edges.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct WarpOptions<'a> {
    /// The reconstruction filter's name. `None` means `lanczos3`.
    pub filter: Option<&'a str>,
    /// The filter's width. `None` means that filter's own.
    pub filter_width: Option<f32>,
    /// What lies outside the source: `"black"`, `"clamp"`, `"periodic"` or
    /// `"mirror"`. `None` leaves OpenImageIO's default.
    ///
    /// [`rotate`] rejects anything but `None` here, because OpenImageIO fixes
    /// it at black and would ignore the request.
    pub wrap: Option<&'a str>,
    /// Extend the source's edge pixels outward before filtering, so a filter
    /// does not pull darkness in from beyond the data window.
    ///
    /// [`rotate`] rejects this for the same reason it rejects `wrap`.
    pub edge_clamp: bool,
    /// Grow the result to hold the whole transformed image. Without it the
    /// result keeps the source's dimensions and the corners are lost.
    pub recompute_region: bool,
}

/// Rotate by an arbitrary angle.
///
/// `angle` is in **radians**, and turns clockwise, because y points down.
///
/// `center` defaults to the middle of the display window, which is not the
/// middle of the data window when the image is cropped or has overscan.
///
/// Pixels outside the source read as black. OpenImageIO offers no choice about
/// that here, so rather than accept a wrap mode and drop it, this refuses
/// [`WarpOptions::wrap`] and [`WarpOptions::edge_clamp`]; [`warp`] with a
/// rotation matrix honours both.
pub fn rotate(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    angle: f32,
    center: Option<[f32; 2]>,
    options: &WarpOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    if options.wrap.is_some() || options.edge_clamp {
        return Err(Error::InvalidImageSpec(
            "rotate always leaves black outside the source; use warp with a rotation matrix to choose a wrap mode or edge clamping"
                .to_owned(),
        ));
    }
    let roi = region_in(roi, dst)?;
    let [center_x, center_y] = center.unwrap_or([0.0, 0.0]);
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rotate(
            dst.inner_mut(),
            src.inner(),
            angle,
            center.is_some(),
            center_x,
            center_y,
            options.filter.unwrap_or_default(),
            options.filter_width.unwrap_or(0.0),
            options.recompute_region,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "rotate", succeeded)
}

/// Apply a 3x3 transform to the image.
///
/// `matrix` is nine values in row order, mapping source coordinates to
/// destination ones. This is the general form of [`rotate`], and unlike it,
/// every edge behaviour is available.
pub fn warp(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    matrix: &[f32; 9],
    options: &WarpOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_warp(
            dst.inner_mut(),
            src.inner(),
            matrix,
            options.filter.unwrap_or_default(),
            options.filter_width.unwrap_or(0.0),
            options.wrap.unwrap_or_default(),
            options.edge_clamp,
            options.recompute_region,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "warp", succeeded)
}

/// Warp by a map that says, per pixel, where to read from.
///
/// `coordinates` holds source positions rather than offsets: the first named
/// channel gives the x coordinate and the second the y, both normalised to
/// `0..1` across the source's display window. This is how a lens distortion or
/// an optical flow is applied.
///
/// `channels` names those two channels of `coordinates`, and `flip` mirrors
/// each of them, for maps authored with the opposite convention.
///
/// [`WarpOptions::wrap`], [`WarpOptions::edge_clamp`] and
/// [`WarpOptions::recompute_region`] have no effect here; the map decides where
/// every pixel comes from, so there is nothing left for them to say.
pub fn st_warp(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    coordinates: &ImageBuf,
    channels: [u32; 2],
    flip: [bool; 2],
    options: &WarpOptions<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let index = |name: &'static str, value: u32| {
        i32::try_from(value)
            .map_err(|_| Error::InvalidImageSpec(format!("{name} exceeds i32::MAX")))
    };
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_st_warp(
            dst.inner_mut(),
            src.inner(),
            coordinates.inner(),
            options.filter.unwrap_or_default(),
            options.filter_width.unwrap_or(0.0),
            index("s channel", channels[0])?,
            index("t channel", channels[1])?,
            flip[0],
            flip[1],
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "st_warp", succeeded)
}

/// Either an image or one constant value per channel.
///
/// This is OpenImageIO's `Image_or_Const`, which several operations accept in
/// place of a second image. Where a constant is given, too few values repeats
/// the last one across the remaining channels, and an empty slice means zero —
/// except in [`clamp`] and [`ContrastRemap`], which say what empty means for
/// them.
#[derive(Debug, Clone, Copy)]
pub enum Operand<'a> {
    /// Take this operand's values from an image.
    Image(&'a ImageBuf),
    /// Use these constants, one per channel.
    Constant(&'a [f32]),
}

/// Multiply and add: `dst = a * b + c`, per pixel and per channel.
///
/// This is one operation rather than a multiply followed by an add, so it
/// rounds once. `a` is always an image, which satisfies OpenImageIO's rule
/// that at least one of the first two arguments must be one.
///
/// ```
/// use oiio::{algo, algo::Operand, ImageBuf, ImageSpec, PixelFormat};
///
/// # fn main() -> oiio::Result<()> {
/// # let spec = ImageSpec::new(64, 64, 3, PixelFormat::F32)?;
/// # let source = ImageBuf::new(&spec)?;
/// let mut result = ImageBuf::new(&spec)?;
/// // Scale by 2 and lift by 0.1, in one pass.
/// algo::mad(
///     &mut result,
///     &source,
///     Operand::Constant(&[2.0]),
///     Operand::Constant(&[0.1]),
///     None,
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn mad(
    dst: &mut ImageBuf,
    a: &ImageBuf,
    b: Operand<'_>,
    c: Operand<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = match (b, c) {
        (Operand::Image(b), Operand::Image(c)) => unsafe {
            sys::imagebufalgo::imagebufalgo_mad_iii(
                dst.inner_mut(),
                a.inner(),
                b.inner(),
                c.inner(),
                &roi,
                ALL_THREADS,
            )
        },
        (Operand::Image(b), Operand::Constant(c)) => unsafe {
            sys::imagebufalgo::imagebufalgo_mad_iic(
                dst.inner_mut(),
                a.inner(),
                b.inner(),
                c,
                &roi,
                ALL_THREADS,
            )
        },
        (Operand::Constant(b), Operand::Image(c)) => unsafe {
            sys::imagebufalgo::imagebufalgo_mad_ici(
                dst.inner_mut(),
                a.inner(),
                b,
                c.inner(),
                &roi,
                ALL_THREADS,
            )
        },
        (Operand::Constant(b), Operand::Constant(c)) => unsafe {
            sys::imagebufalgo::imagebufalgo_mad_icc(
                dst.inner_mut(),
                a.inner(),
                b,
                c,
                &roi,
                ALL_THREADS,
            )
        },
    };
    finish(dst, "multiply and add", succeeded)
}

/// Compute `1 - a`.
///
/// Every channel in the region is inverted, alpha included, so restrict the
/// region to the colour channels unless that is what you want. For
/// premultiplied images, [`unpremult`] then `invert` then [`premult`] is the
/// usual sequence.
pub fn invert(dst: &mut ImageBuf, a: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_invert(dst.inner_mut(), a.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "invert", succeeded)
}

/// Raise each channel to a per-channel power.
///
/// An empty `exponents` means an exponent of zero for every channel, and so a
/// result of one everywhere; that is OpenImageIO's padding rule rather than an
/// oversight. A negative value raised to a fractional power is `NaN`, not
/// zero.
pub fn pow(dst: &mut ImageBuf, a: &ImageBuf, exponents: &[f32], roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_pow(
            dst.inner_mut(),
            a.inner(),
            exponents,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "power", succeeded)
}

/// Clamp each channel into a per-channel range.
///
/// An empty `min` or `max` means "do not clamp on that side" — unlike most of
/// the per-channel slices here, where empty means zero. Too few values repeats
/// the last. No check is made that `min <= max`: an inverted range silently
/// yields `max`.
///
/// `clamp_alpha_to_unit` additionally holds the source's alpha channel in
/// `0..=1`, and does nothing if the source does not designate one.
pub fn clamp(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    min: &[f32],
    max: &[f32],
    clamp_alpha_to_unit: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_clamp(
            dst.inner_mut(),
            src.inner(),
            min,
            max,
            clamp_alpha_to_unit,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "clamp", succeeded)
}

/// Take the smaller of two operands, per pixel and per channel.
///
/// Channels present in only one of two images are copied through unchanged.
pub fn min(dst: &mut ImageBuf, a: &ImageBuf, b: Operand<'_>, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = match b {
        Operand::Image(b) => unsafe {
            sys::imagebufalgo::imagebufalgo_min_images(
                dst.inner_mut(),
                a.inner(),
                b.inner(),
                &roi,
                ALL_THREADS,
            )
        },
        Operand::Constant(values) => unsafe {
            sys::imagebufalgo::imagebufalgo_min_constant(
                dst.inner_mut(),
                a.inner(),
                values,
                &roi,
                ALL_THREADS,
            )
        },
    };
    finish(dst, "minimum", succeeded)
}

/// Take the larger of two operands, per pixel and per channel.
///
/// Two images must have the same number of channels, and the destination must
/// have at least as many. [`min`] has no such restriction; the difference is
/// not by design. OpenImageIO's image-against-image `max` widens its channel
/// range where `min` narrows it, which makes it read past the shorter input
/// and write past a narrower destination — its own assertion, in code the
/// widening makes unreachable, says the range was meant to narrow. Rather than
/// pass that on, this refuses the shapes that would run off the end. The
/// bug is in OpenImageIO 3.1 and still in 3.2, so the restriction stands until
/// it is fixed there.
pub fn max(dst: &mut ImageBuf, a: &ImageBuf, b: Operand<'_>, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = match b {
        Operand::Image(b) => unsafe {
            sys::imagebufalgo::imagebufalgo_max_images(
                dst.inner_mut(),
                a.inner(),
                b.inner(),
                &roi,
                ALL_THREADS,
            )
        },
        Operand::Constant(values) => unsafe {
            sys::imagebufalgo::imagebufalgo_max_constant(
                dst.inner_mut(),
                a.inner(),
                values,
                &roi,
                ALL_THREADS,
            )
        },
    };
    finish(dst, "maximum", succeeded)
}

/// How [`contrast_remap`] should reshape the tone curve.
///
/// Every field is one value per channel. An empty slice takes that field's
/// default, which is the value named below rather than zero; too few values
/// repeats the last one.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct ContrastRemap<'a> {
    /// The input level that becomes [`min`](Self::min). Default 0.
    pub black: &'a [f32],
    /// The input level that becomes [`max`](Self::max). Default 1.
    pub white: &'a [f32],
    /// The output level [`black`](Self::black) maps to. Default 0.
    pub min: &'a [f32],
    /// The output level [`white`](Self::white) maps to. Default 1.
    pub max: &'a [f32],
    /// Steepness of an S-curve applied between the two remappings. Default 1,
    /// which is no curve at all; larger values increase contrast.
    pub sigmoid_contrast: &'a [f32],
    /// Where that S-curve pivots. Default 0.5.
    pub sigmoid_threshold: &'a [f32],
}

/// Remap levels, optionally through an S-curve.
///
/// The result is not clamped, so follow it with [`clamp`] if the output has to
/// stay in range.
///
/// Setting a channel's `black` equal to its `white` is a division by zero. When
/// *every* channel has them equal, OpenImageIO takes that as a deliberate
/// binary threshold and produces `min` below the level and `max` at or above
/// it; when only some channels do, those channels produce infinities instead.
pub fn contrast_remap(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    remap: &ContrastRemap<'_>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_contrast_remap(
            dst.inner_mut(),
            src.inner(),
            remap.black,
            remap.white,
            remap.min,
            remap.max,
            remap.sigmoid_contrast,
            remap.sigmoid_threshold,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "contrast remap", succeeded)
}

/// Move three consecutive channels toward or away from their luminance.
///
/// `scale` is 0 for fully desaturated, 1 for unchanged, and more than 1 to
/// oversaturate. Channels outside `first_channel..first_channel + 3` are
/// copied unaltered. The luminance weights are fixed at linear sRGB's, whatever
/// the image's actual colour space.
///
/// The source must have three channels at `first_channel`, and neither its
/// alpha nor its depth channel may be among them.
pub fn saturate(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    scale: f32,
    first_channel: u32,
    roi: Option<Roi>,
) -> Result<()> {
    let first_channel = i32::try_from(first_channel)
        .map_err(|_| Error::InvalidImageSpec("first channel exceeds i32::MAX".to_owned()))?;
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_saturate(
            dst.inner_mut(),
            src.inner(),
            scale,
            first_channel,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "saturate", succeeded)
}

/// Copy part of one image into another at a given position.
///
/// `src_roi` selects part of the **source**, not of the destination; the
/// module documentation lists the six operations that do. The destination
/// position is an offset applied to the source's own coordinates, so a source
/// whose data window begins at x=100 pasted at `x = 0` lands at x=100, not at
/// the origin.
///
/// Pixels and channels that fall outside the destination are dropped silently,
/// so a paste can be partial without reporting anything.
///
/// `first_channel` may be negative, which lands a later source channel on the
/// destination's first. It may not be negative enough to put every source
/// channel outside the destination: OpenImageIO would size the destination
/// from a negative channel count and terminate the process.
pub fn paste(
    dst: &mut ImageBuf,
    position: [i32; 3],
    first_channel: i32,
    src: &ImageBuf,
    src_roi: Option<Roi>,
) -> Result<()> {
    let src_roi = region(src_roi);
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_paste(
            dst.inner_mut(),
            position[0],
            position[1],
            position[2],
            first_channel,
            src.inner(),
            &src_roi,
            ALL_THREADS,
        )
    };
    finish(dst, "paste", succeeded)
}

/// Extract a region and move it to the origin.
///
/// This is [`crop`] followed by a reposition: the result's display window
/// covers exactly the extracted rectangle, starting at 0,0.
///
/// As with `crop`, and unlike the rest of this module, the destination is
/// discarded before anything is written, so pre-allocating one does not choose
/// the output format — the result always takes the source's.
///
/// A channel range narrows which channels survive but does not renumber them:
/// the result keeps the source's channel count with the others blacked out.
/// Use [`channels`] to actually drop channels. Deep images are supported.
pub fn cut(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_cut(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "cut", succeeded)
}

/// Take the absolute value of every channel.
pub fn abs(dst: &mut ImageBuf, a: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_abs(dst.inner_mut(), a.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "absolute value", succeeded)
}

/// Compute the absolute difference between two images.
pub fn absdiff(dst: &mut ImageBuf, a: &ImageBuf, b: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_absdiff_images(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "absolute difference", succeeded)
}

/// Copy pixels, optionally converting them to another format.
pub fn copy(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    convert_to: Option<crate::PixelFormat>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let convert = convert_to.unwrap_or(crate::PixelFormat::Other).to_sys();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_copy(
            dst.inner_mut(),
            src.inner(),
            convert,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "copy", succeeded)
}

/// Crop to a region, keeping the pixels' original coordinates.
///
/// The destination is discarded first, so unlike most of this module it cannot
/// be pre-allocated to choose the result's pixel format; the result takes the
/// source's. [`cut`] additionally moves the result to the origin.
pub fn crop(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_crop(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "crop", succeeded)
}

/// Mirror vertically, top to bottom.
pub fn flip(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_flip(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "flip", succeeded)
}

/// Circularly shift the region, pixels pushed off one edge reappearing at
/// the other — the shift of `[0, 1, 2, 3, 4, 5]` by 2 is `[4, 5, 0, 1, 2, 3]`.
///
/// The destination must be empty: the wrapped writes are a bijection of the
/// region onto a result the same shape, so a fresh destination comes back
/// fully written, while a larger pre-allocated one would keep uninitialized
/// pixels wherever the wrapping never lands. Negative and over-sized shifts
/// wrap as expected.
pub fn circular_shift(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    shift: [i32; 3],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let mut message = String::new();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_circular_shift(
            dst.inner_mut(),
            src.inner(),
            shift[0],
            shift[1],
            shift[2],
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if succeeded {
        Ok(())
    } else {
        Err(Error::operation("circular_shift", message))
    }
}

/// Mirror horizontally, left to right.
pub fn flop(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_flop(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "flop", succeeded)
}

/// Transpose, exchanging rows and columns.
pub fn transpose(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_transpose(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "transpose", succeeded)
}

/// How [`fit`] uses the space when the aspect ratios differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum FitMode {
    /// Preserve the aspect ratio, padding the leftover space.
    #[default]
    Letterbox,
    /// Match the requested width, letting the height fall where it may.
    Width,
    /// Match the requested height, letting the width fall where it may.
    Height,
}

/// Where one output channel's values come from in [`channels`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChannelSource {
    /// Copy an input channel by index.
    Channel(u32),
    /// Fill with a constant instead of copying anything.
    Constant(f32),
}

/// Resize into the destination's own dimensions.
///
/// The destination decides the output size, so it must be allocated at the
/// wanted size — an empty buffer has nothing to resize into. `filter_name` is
/// an OpenImageIO filter such as `"lanczos3"`, `"blackman-harris"` or
/// `"box"`; `None` lets OpenImageIO pick one suited to the scale factor.
pub fn resize(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    filter_name: Option<&str>,
    filter_width: Option<f32>,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_resize(
            dst.inner_mut(),
            src.inner(),
            filter_name.unwrap_or(""),
            filter_width.unwrap_or(0.0),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "resize", succeeded)
}

/// Resize to fit inside the destination, preserving the aspect ratio.
pub fn fit(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    filter_name: Option<&str>,
    filter_width: Option<f32>,
    mode: FitMode,
    exact: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fit(
            dst.inner_mut(),
            src.inner(),
            filter_name.unwrap_or(""),
            filter_width.unwrap_or(0.0),
            mode.name(),
            exact,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "fit", succeeded)
}

/// Resize without a reconstruction filter.
///
/// Cheaper than [`resize`] and correspondingly cruder: `interpolate` chooses
/// between bilinear sampling and nearest neighbour.
pub fn resample(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    interpolate: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_resample(
            dst.inner_mut(),
            src.inner(),
            interpolate,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "resample", succeeded)
}

/// Composite `a` over `b`, the Porter-Duff operator.
///
/// Both images must have an alpha channel and hold premultiplied values.
pub fn over(dst: &mut ImageBuf, a: &ImageBuf, b: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_over(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "over", succeeded)
}

/// Multiply the colour channels by alpha.
pub fn premult(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_premult(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "premultiply", succeeded)
}

/// Divide the colour channels by alpha, undoing [`premult`].
pub fn unpremult(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_unpremult(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "unpremultiply", succeeded)
}

/// Multiply the colour channels back by alpha, undoing [`unpremult`] while
/// keeping the values unpremultiplied work produced for zero-alpha pixels.
///
/// The source must have an alpha channel: unlike [`premult`], whose no-alpha
/// case is a documented copy, there is nothing to re-premultiply by, so a
/// source without one is an error.
pub fn repremult(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_repremult(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "re-premultiply", succeeded)
}

/// Composite `a` over `b` using depth: the closer surface wins per pixel.
///
/// `z_zero_is_infinity` treats a depth of zero as infinitely far rather than
/// infinitely close, which is what renderers that leave empty pixels at zero
/// need. Both images need matching channel counts, and OpenImageIO finds the
/// `Z` channel by name or falls back to guessing that alpha is the last
/// channel on unmarked four-channel images — name the channels.
pub fn zover(
    dst: &mut ImageBuf,
    a: &ImageBuf,
    b: &ImageBuf,
    z_zero_is_infinity: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_zover(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            z_zero_is_infinity,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "zover", succeeded)
}

/// Multiply an image by a single-channel one, per pixel.
///
/// Exactly one of the two operands must have one channel — OpenImageIO
/// accepts the single-channel image on either side — and every channel of
/// the other is multiplied by it: the mask or matte multiply [`mul`] cannot
/// express, since arithmetic requires matching counts. A pre-allocated
/// destination must match the wider operand's channel count.
pub fn scale(dst: &mut ImageBuf, a: &ImageBuf, b: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_scale(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "scale", succeeded)
}

/// How [`fix_non_finite`] treats a `NaN` or infinite value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NonFiniteFix {
    /// Count the bad values without changing them.
    None,
    /// Replace them with zero.
    Black,
    /// Replace them with the average of the finite neighbours in a 3x3 box,
    /// falling back to zero when every neighbour is bad too. On deep images
    /// this degrades to the zero replacement.
    Box3,
    /// Change nothing and report an error if any bad value exists.
    Error,
}

impl NonFiniteFix {
    fn to_sys(self) -> i32 {
        match self {
            Self::None => 0,
            Self::Black => 1,
            Self::Box3 => 2,
            Self::Error => 100,
        }
    }
}

/// Repair `NaN` and infinite values, returning how many pixels were touched.
///
/// For pixel formats that cannot hold a non-finite value this is a copy that
/// reports zero. The destination must be empty or share the source's pixel
/// format, since OpenImageIO walks the source at the destination's width.
pub fn fix_non_finite(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    mode: NonFiniteFix,
    roi: Option<Roi>,
) -> Result<u64> {
    let roi = region_in(roi, dst)?;
    let mut pixels_fixed = 0_i64;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fix_non_finite(
            dst.inner_mut(),
            src.inner(),
            mode.to_sys(),
            &mut pixels_fixed,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "fix non-finite", succeeded)?;
    Ok(pixels_fixed.max(0) as u64)
}

/// Compress the value range logarithmically above a low knee.
///
/// Values up to 0.18 — scene-linear mid-grey, the knee — pass through
/// unchanged; everything above is folded down a log curve (the Sony
/// Imageworks coefficients OpenImageIO ships), so anything brighter than
/// mid-grey moves, and highlights up to about 16.0 land at or below 1.0 —
/// brighter values still exceed 1.0, though only logarithmically. This is the
/// transform that lets high dynamic range imagery survive filtering that
/// would otherwise ring around highlights; [`rangeexpand`] undoes it,
/// approximately — the pair round-trips values, not bit patterns. With
/// `use_luma`, the scale factor comes from luminance so a pixel's hue
/// survives the trip.
pub fn rangecompress(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    use_luma: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rangecompress(
            dst.inner_mut(),
            src.inner(),
            use_luma,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "rangecompress", succeeded)
}

/// Undo [`rangecompress`], expanding the compressed highlights back out.
pub fn rangeexpand(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    use_luma: bool,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_rangeexpand(
            dst.inner_mut(),
            src.inner(),
            use_luma,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "rangeexpand", succeeded)
}

/// Sum the channels into a single-channel image, weighted.
///
/// There must be exactly one weight per source channel. OpenImageIO pads a
/// short list against the *destination's* channel count, which is one, and
/// then reads it across the source's channels — past the end of the caller's
/// own slice. Pass ones for an unweighted sum.
pub fn channel_sum(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    weights: &[f32],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_channel_sum(
            dst.inner_mut(),
            src.inner(),
            weights,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "channel sum", succeeded)
}

/// Concatenate the channels of two images into one buffer.
///
/// The result covers the union of the two data windows and holds `a`'s
/// channels followed by `b`'s — the way AOVs are merged into one layered
/// image. The destination must be empty: OpenImageIO shapes the result
/// itself and disregards both a caller's region and a pre-allocated shape.
/// Deep images are not supported.
pub fn channel_append(dst: &mut ImageBuf, a: &ImageBuf, b: &ImageBuf) -> Result<()> {
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_channel_append(
            dst.inner_mut(),
            a.inner(),
            b.inner(),
            ALL_THREADS,
        )
    };
    finish(dst, "channel append", succeeded)
}

/// The per-pixel maximum across channels, as a single-channel image.
pub fn maxchan(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_maxchan(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "maxchan", succeeded)
}

/// The per-pixel minimum across channels, as a single-channel image.
pub fn minchan(dst: &mut ImageBuf, src: &ImageBuf, roi: Option<Roi>) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_minchan(dst.inner_mut(), src.inner(), &roi, ALL_THREADS)
    };
    finish(dst, "minchan", succeeded)
}

/// Build a new channel layout: reorder, drop, duplicate, or add channels.
///
/// Each entry of `sources` produces one output channel, so the output has
/// `sources.len()` channels. `names`, when given, must have the same length.
///
/// ```
/// use oiio::algo::{self, ChannelSource};
/// # use oiio::{ImageBuf, ImageSpec, PixelFormat};
/// # fn main() -> oiio::Result<()> {
/// # let spec = ImageSpec::new(4, 4, 3, PixelFormat::F32)?;
/// # let rgb = ImageBuf::new(&spec)?;
/// // RGB to BGRA, with a fully opaque alpha that the source lacks.
/// let mut bgra = ImageBuf::empty()?;
/// algo::channels(
///     &mut bgra,
///     &rgb,
///     &[
///         ChannelSource::Channel(2),
///         ChannelSource::Channel(1),
///         ChannelSource::Channel(0),
///         ChannelSource::Constant(1.0),
///     ],
///     Some(&["B", "G", "R", "A"]),
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn channels(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    sources: &[ChannelSource],
    names: Option<&[&str]>,
) -> Result<()> {
    if sources.is_empty() {
        return Err(Error::InvalidImageSpec(
            "a channel layout needs at least one channel".to_owned(),
        ));
    }
    if let Some(names) = names {
        if names.len() != sources.len() {
            return Err(Error::InvalidImageSpec(format!(
                "expected {} channel names, got {}",
                sources.len(),
                names.len()
            )));
        }
    }

    // OpenImageIO takes two parallel arrays: an index per output channel, or
    // -1 to mean "take the constant at this position instead".
    let mut order = Vec::with_capacity(sources.len());
    let mut values = Vec::with_capacity(sources.len());
    for source in sources {
        match *source {
            ChannelSource::Channel(index) => {
                order.push(i32::try_from(index).map_err(|_| {
                    Error::InvalidImageSpec("channel index exceeds i32::MAX".to_owned())
                })?);
                values.push(0.0);
            }
            ChannelSource::Constant(value) => {
                order.push(-1);
                values.push(value);
            }
        }
    }
    let names: Vec<String> = names
        .unwrap_or(&[])
        .iter()
        .map(|name| (*name).to_owned())
        .collect();

    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_channels(
            dst.inner_mut(),
            src.inner(),
            order.len() as i32,
            &order,
            &values,
            &names,
            false,
            ALL_THREADS,
        )
    };
    finish(dst, "channel layout", succeeded)
}

/// Convert between colour spaces.
///
/// The names must be ones the active configuration knows; ask a
/// [`ColorConfig`](crate::ColorConfig) rather than guessing, since they differ
/// between configurations. A role such as `"scene_linear"` works wherever a
/// space name does.
///
/// `unpremult` divides out alpha before converting and multiplies it back
/// afterwards, which is what you want for images holding premultiplied
/// colour: a colour transform is not linear, so applying it to premultiplied
/// values darkens the edges of anything partly transparent.
pub fn color_convert(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    from_space: &str,
    to_space: &str,
    unpremult: bool,
    roi: Option<Roi>,
) -> Result<()> {
    if from_space.is_empty() || to_space.is_empty() {
        return Err(Error::InvalidImageSpec(
            "a colour conversion needs both a source and a destination space".to_owned(),
        ));
    }
    let roi = region_in(roi, dst)?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_colorconvert(
            dst.inner_mut(),
            src.inner(),
            from_space,
            to_space,
            unpremult,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "colour convert", succeeded)
}

/// Compare two images numerically.
///
/// `fail_threshold` and `warn_threshold` are per-channel absolute differences.
/// The result reports the mean and maximum error, where the worst pixel is,
/// and how many values exceeded each threshold.
///
/// This fails rather than reporting nonsense when the comparison cannot be
/// made — one image deep and the other flat, or either holding no pixels. In
/// those cases OpenImageIO returns a result whose measurements were never
/// assigned, so there is nothing to hand back.
pub fn compare(
    a: &ImageBuf,
    b: &ImageBuf,
    fail_threshold: f32,
    warn_threshold: f32,
    roi: Option<Roi>,
) -> Result<CompareSummary> {
    compare_with_relative(a, b, fail_threshold, warn_threshold, 0.0, 0.0, roi)
}

/// Which colour filter array a mosaic uses; see [`demosaic`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MosaicPattern {
    /// The 2x2 Bayer pattern.
    Bayer,
    /// Fujifilm's 6x6 X-Trans pattern.
    XTrans,
}

/// Decode a one-channel camera mosaic into a three-channel colour image.
///
/// `layout` names the filter arrangement, `"RGGB"` and its rotations for
/// Bayer; `algorithm` is `"linear"` or, for Bayer, the sharper `"MHC"`.
/// `white_balance` optionally scales the channels during the decode, as
/// `[r, g, b]` or `[r, g1, b, g2]`.
///
/// The destination must be empty — the decode shapes the result, and
/// OpenImageIO ignores its own preparation verdict on a pre-allocated one —
/// and the source's data window must not start at negative coordinates,
/// which the decoders' pattern arithmetic does not survive.
pub fn demosaic(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    pattern: MosaicPattern,
    algorithm: &str,
    layout: &str,
    white_balance: Option<&[f32]>,
) -> Result<()> {
    if let Some(balance) = white_balance {
        if balance.len() != 3 && balance.len() != 4 {
            return Err(Error::InvalidRoi(format!(
                "white balance is [r, g, b] or [r, g1, b, g2], got {} values",
                balance.len()
            )));
        }
    }
    let mut error = String::new();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_demosaic(
            dst.inner_mut(),
            src.inner(),
            pattern.name(),
            algorithm,
            layout,
            white_balance.unwrap_or(&[]),
            ALL_THREADS,
            &mut error,
        )
    };
    if succeeded {
        Ok(())
    } else {
        Err(Error::operation("demosaic", error))
    }
}

/// Normalize the vectors a 3- or 4-channel image encodes, pixel by pixel.
///
/// Each pixel is read as a vector around `in_center` — 0.5 for the usual
/// unsigned normal-map encoding, 0.0 for signed data — normalized to unit
/// length, scaled, and re-encoded around `out_center`. A fourth channel is
/// passed through untouched. The source must have exactly three or four
/// channels, and a pre-allocated destination must share the source's pixel
/// format, since OpenImageIO reads the source through an iterator of the
/// destination's type.
pub fn normalize(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    in_center: f32,
    out_center: f32,
    scale: f32,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let mut message = String::new();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_normalize(
            dst.inner_mut(),
            src.inner(),
            in_center,
            out_center,
            scale,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if succeeded {
        Ok(())
    } else {
        Err(Error::operation("normalize", message))
    }
}

/// Fill the transparent holes of an image from blurred copies of its
/// neighbourhood — the push-pull technique texture pipelines use before
/// mip-mapping alpha-masked colour.
///
/// The source needs an alpha channel; pixels with zero alpha are filled,
/// and everything else passes through. The whole image is always processed —
/// OpenImageIO ignores a region here, so this takes none — and a failure
/// part way down the internal pyramid is reported rather than returned as a
/// silently black result.
pub fn fillholes_pushpull(dst: &mut ImageBuf, src: &ImageBuf) -> Result<()> {
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_fillholes_pushpull(
            dst.inner_mut(),
            src.inner(),
            ALL_THREADS,
        )
    };
    finish(dst, "fillholes", succeeded)
}

/// Count how many values sit below, above, and inside a per-channel range.
///
/// `low` and `high` give per-channel bounds; short slices are padded by
/// OpenImageIO with "no bound" sentinels, so an empty slice on either side
/// counts nothing against it. Deep images are not supported, and a channel
/// range naming no channel of the source is an error rather than a report of
/// zero everything.
pub fn color_range_check(
    src: &ImageBuf,
    low: &[f32],
    high: &[f32],
    roi: Option<Roi>,
) -> Result<RangeCheckCounts> {
    let roi = region_in(roi, src)?;
    let mut counts = RangeCheckCounts {
        low: 0,
        high: 0,
        in_range: 0,
    };
    let mut message = String::new();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_color_range_check(
            src.inner(),
            low,
            high,
            &mut counts,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if succeeded {
        Ok(counts)
    } else {
        Err(Error::operation("color range check", message))
    }
}

/// Remap a single channel through a colour map given as interpolation knots.
///
/// `source_channel` selects which channel drives the map, or `None` for
/// luminance computed from the first three. `knots` holds `knot_count`
/// entries of `channels` values each, laid out knot-major, and the product
/// must equal the slice length exactly — OpenImageIO's own length check
/// multiplies in `int`, where a large pair overflows into an out-of-bounds
/// read, so the bridge checks it wide first.
pub fn color_map(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    source_channel: Option<u32>,
    knot_count: u32,
    channels: u32,
    knots: &[f32],
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let source_channel = match source_channel {
        None => -1,
        Some(index) => i32::try_from(index)
            .map_err(|_| Error::InvalidRoi("source channel exceeds i32::MAX".to_owned()))?,
    };
    let knot_count = i32::try_from(knot_count)
        .map_err(|_| Error::InvalidRoi("knot count exceeds i32::MAX".to_owned()))?;
    let channels = i32::try_from(channels)
        .map_err(|_| Error::InvalidRoi("channel count exceeds i32::MAX".to_owned()))?;
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_color_map(
            dst.inner_mut(),
            src.inner(),
            source_channel,
            knot_count,
            channels,
            knots,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "color map", succeeded)
}

/// Remap a single channel through one of OpenImageIO's named colour maps,
/// such as `"inferno"`, `"viridis"`, `"turbo"` or `"blue-red"`.
pub fn color_map_named(
    dst: &mut ImageBuf,
    src: &ImageBuf,
    source_channel: Option<u32>,
    map_name: &str,
    roi: Option<Roi>,
) -> Result<()> {
    let roi = region_in(roi, dst)?;
    let source_channel = match source_channel {
        None => -1,
        Some(index) => i32::try_from(index)
            .map_err(|_| Error::InvalidRoi("source channel exceeds i32::MAX".to_owned()))?,
    };
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_color_map_named(
            dst.inner_mut(),
            src.inner(),
            source_channel,
            map_name,
            &roi,
            ALL_THREADS,
        )
    };
    finish(dst, "color map", succeeded)
}

/// [`compare`] with relative thresholds alongside the absolute ones.
///
/// A value fails when its difference exceeds `fail_threshold` **and** exceeds
/// `fail_relative` times the mean magnitude of the two values being compared;
/// zeros here make this identical to [`compare`]. Relative thresholds are how
/// a comparison tolerates the low bits of bright values without ignoring the
/// same absolute error in shadows.
pub fn compare_with_relative(
    a: &ImageBuf,
    b: &ImageBuf,
    fail_threshold: f32,
    warn_threshold: f32,
    fail_relative: f32,
    warn_relative: f32,
    roi: Option<Roi>,
) -> Result<CompareSummary> {
    let roi = region_in(roi, a)?;
    let mut message = String::new();
    let summary = unsafe {
        sys::imagebufalgo::imagebufalgo_compare(
            a.inner(),
            b.inner(),
            fail_threshold,
            warn_threshold,
            fail_relative,
            warn_relative,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if message.is_empty() {
        Ok(summary)
    } else {
        Err(Error::operation("compare", message))
    }
}

/// What [`compare_yee`] measured: how many pixels a human would notice
/// differ, and where the worst one is.
///
/// This is its own type rather than a [`CompareSummary`] because Yee's
/// metric measures none of the mean, root-mean-square or peak
/// signal-to-noise values — returning the shared type would present real
/// zeroes that mean "not measured".
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct YeeComparison {
    /// Pixels predicted to be visibly different.
    pub failures: u64,
    /// The largest perceptual factor of a failing pixel; 0 when none fail.
    pub max_error: f64,
    /// Image coordinates of the worst pixel.
    pub max_position: [i32; 2],
}

impl YeeComparison {
    /// Whether the images would look the same to a human observer.
    pub fn perceptually_equal(&self) -> bool {
        self.failures == 0
    }
}

/// Compare two images with Yee's perceptual metric — how many pixels a
/// human adapted to `luminance` candela per square metre, with the image
/// spanning `fov` degrees of view, would notice differ.
///
/// The first three channels are treated as linear RGB roughly like Adobe
/// RGB; images with fewer channels are padded with zeroes and the result is,
/// in OpenImageIO's words, basically meaningless for them. Both images must
/// be flat and hold pixels, and the region must lie inside them — outside
/// either data window the pixels read as zeroes, which would compare pixels
/// neither image has. Two-dimensional images only. OpenImageIO's usual
/// luminance is 100 and field of view 45; both must be positive, and the
/// field of view under 180.
pub fn compare_yee(
    a: &ImageBuf,
    b: &ImageBuf,
    luminance: f32,
    fov: f32,
    roi: Option<Roi>,
) -> Result<YeeComparison> {
    const OPERATION: &str = "compare_yee";
    if !(luminance.is_finite() && luminance > 0.0) {
        return Err(Error::operation(
            OPERATION,
            format!("the adaptation luminance must be positive and finite, got {luminance}"),
        ));
    }
    if !(fov.is_finite() && fov > 0.0 && fov < 180.0) {
        return Err(Error::operation(
            OPERATION,
            format!("the field of view must be between 0 and 180 degrees, got {fov}"),
        ));
    }
    let roi = region_in(roi, a)?;
    let mut message = String::new();
    let summary = unsafe {
        sys::imagebufalgo::imagebufalgo_compare_yee(
            a.inner(),
            b.inner(),
            luminance,
            fov,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if message.is_empty() {
        Ok(YeeComparison {
            failures: summary.failures,
            max_error: summary.max_error,
            max_position: [summary.max_x, summary.max_y],
        })
    } else {
        Err(Error::operation(OPERATION, message))
    }
}

/// Count the pixels matching each color, within a per-channel tolerance.
///
/// `colors` holds one value per channel for every color to count — its
/// length must be a whole multiple of the image's channel count — and the
/// result has one count per color, in the same order. `eps` is the
/// per-channel tolerance: empty means OpenImageIO's default of `0.001`
/// everywhere (exact for 8-bit images, a wee bit of slack for float), fewer
/// values than channels repeat the last. A region narrows both the pixels
/// visited and, through its channel range, the channels that must match.
/// At most 32768 colors, which bounds the per-thread stack scratch
/// OpenImageIO counts into.
pub fn color_count(
    src: &ImageBuf,
    colors: &[f32],
    eps: &[f32],
    roi: Option<Roi>,
) -> Result<Vec<u64>> {
    const OPERATION: &str = "color_count";
    let channels = src.channel_count() as usize;
    if channels == 0 {
        return Err(Error::operation(
            OPERATION,
            "the image has no channels to match against".to_owned(),
        ));
    }
    if colors.is_empty() || !colors.len().is_multiple_of(channels) {
        return Err(Error::operation(
            OPERATION,
            format!(
                "the colors array holds {} values, which is not a whole number \
                 of {channels}-channel colors",
                colors.len()
            ),
        ));
    }
    let mut counts = vec![0_u64; colors.len() / channels];
    let roi = region_in(roi, src)?;
    let mut message = String::new();
    let succeeded = unsafe {
        sys::imagebufalgo::imagebufalgo_color_count(
            src.inner(),
            &mut counts,
            colors,
            eps,
            &roi,
            ALL_THREADS,
            &mut message,
        )
    };
    if succeeded {
        Ok(counts)
    } else {
        Err(Error::operation(OPERATION, message))
    }
}

enum_names!("horizontal text alignment", TextAlignX {
    Left => "left",
    Right => "right",
    Center => "center",
});

enum_names!("vertical text alignment", TextAlignY {
    Baseline => "baseline",
    Top => "top",
    Bottom => "bottom",
    Center => "center",
});

enum_names!("fit mode", FitMode {
    Letterbox => "letterbox",
    Width => "width",
    Height => "height",
});

enum_names!("non-finite fix", NonFiniteFix {
    None => "none",
    Black => "black",
    Box3 => "box3",
    Error => "error",
});

enum_names!("mosaic pattern", MosaicPattern {
    Bayer => "bayer",
    XTrans => "xtrans",
});

impl<'a> TextOptions<'a> {
    // `#[non_exhaustive]` means a caller outside this crate cannot write
    // `TextOptions { .. }` or use functional update, so these are how a field
    // is changed. They also make the configuration read the same way as
    // `ImageSpec` and `config::Limits`, rather than being a third style.

    /// The same text options with the point size changed.
    #[must_use]
    pub fn with_size(mut self, size: u32) -> Self {
        self.size = size;
        self
    }

    /// The same text options with the font name or path changed.
    #[must_use]
    pub fn with_font(mut self, font: &'a str) -> Self {
        self.font = font;
        self
    }

    /// The same text options with the colour, one value per channel changed.
    #[must_use]
    pub fn with_color(mut self, color: &'a [f32]) -> Self {
        self.color = color;
        self
    }

    /// The same text options with the horizontal alignment changed.
    #[must_use]
    pub fn with_align_x(mut self, align_x: TextAlignX) -> Self {
        self.align_x = align_x;
        self
    }

    /// The same text options with the vertical alignment changed.
    #[must_use]
    pub fn with_align_y(mut self, align_y: TextAlignY) -> Self {
        self.align_y = align_y;
        self
    }

    /// The same text options with the drop-shadow size in pixels changed.
    #[must_use]
    pub fn with_shadow(mut self, shadow: u32) -> Self {
        self.shadow = shadow;
        self
    }
}

impl<'a> OcioOptions<'a> {
    // `#[non_exhaustive]` means a caller outside this crate cannot write
    // `OcioOptions { .. }` or use functional update, so these are how a field
    // is changed. They also make the configuration read the same way as
    // `ImageSpec` and `config::Limits`, rather than being a third style.

    /// The same OCIO options with whether to unpremultiply before converting changed.
    #[must_use]
    pub fn with_unpremult(mut self, unpremult: bool) -> Self {
        self.unpremult = unpremult;
        self
    }

    /// The same OCIO options with whether to apply the transform backwards changed.
    #[must_use]
    pub fn with_inverse(mut self, inverse: bool) -> Self {
        self.inverse = inverse;
        self
    }

    /// The same OCIO options with the OCIO context key changed.
    #[must_use]
    pub fn with_context_key(mut self, context_key: &'a str) -> Self {
        self.context_key = context_key;
        self
    }

    /// The same OCIO options with the OCIO context value changed.
    #[must_use]
    pub fn with_context_value(mut self, context_value: &'a str) -> Self {
        self.context_value = context_value;
        self
    }
}

impl<'a> WarpOptions<'a> {
    // `#[non_exhaustive]` means a caller outside this crate cannot write
    // `WarpOptions { .. }` or use functional update, so these are how a field
    // is changed. They also make the configuration read the same way as
    // `ImageSpec` and `config::Limits`, rather than being a third style.

    /// The same warp options with the reconstruction filter changed.
    #[must_use]
    pub fn with_filter(mut self, filter: Option<&'a str>) -> Self {
        self.filter = filter;
        self
    }

    /// The same warp options with the filter width changed.
    #[must_use]
    pub fn with_filter_width(mut self, filter_width: Option<f32>) -> Self {
        self.filter_width = filter_width;
        self
    }

    /// The same warp options with the wrap mode changed.
    #[must_use]
    pub fn with_wrap(mut self, wrap: Option<&'a str>) -> Self {
        self.wrap = wrap;
        self
    }

    /// The same warp options with whether to clamp at the edges changed.
    #[must_use]
    pub fn with_edge_clamp(mut self, edge_clamp: bool) -> Self {
        self.edge_clamp = edge_clamp;
        self
    }

    /// The same warp options with whether to recompute the destination region changed.
    #[must_use]
    pub fn with_recompute_region(mut self, recompute_region: bool) -> Self {
        self.recompute_region = recompute_region;
        self
    }
}

impl<'a> ContrastRemap<'a> {
    // `#[non_exhaustive]` means a caller outside this crate cannot write
    // `ContrastRemap { .. }` or use functional update, so these are how a field
    // is changed. They also make the configuration read the same way as
    // `ImageSpec` and `config::Limits`, rather than being a third style.

    /// The same contrast remap with the input black point changed.
    #[must_use]
    pub fn with_black(mut self, black: &'a [f32]) -> Self {
        self.black = black;
        self
    }

    /// The same contrast remap with the input white point changed.
    #[must_use]
    pub fn with_white(mut self, white: &'a [f32]) -> Self {
        self.white = white;
        self
    }

    /// The same contrast remap with the output minimum changed.
    #[must_use]
    pub fn with_min(mut self, min: &'a [f32]) -> Self {
        self.min = min;
        self
    }

    /// The same contrast remap with the output maximum changed.
    #[must_use]
    pub fn with_max(mut self, max: &'a [f32]) -> Self {
        self.max = max;
        self
    }

    /// The same contrast remap with the sigmoid contrast changed.
    #[must_use]
    pub fn with_sigmoid_contrast(mut self, sigmoid_contrast: &'a [f32]) -> Self {
        self.sigmoid_contrast = sigmoid_contrast;
        self
    }

    /// The same contrast remap with the sigmoid threshold changed.
    #[must_use]
    pub fn with_sigmoid_threshold(mut self, sigmoid_threshold: &'a [f32]) -> Self {
        self.sigmoid_threshold = sigmoid_threshold;
        self
    }
}