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
#include "ffi_imagebufalgo.h"
#include "oiio-sys/src/imagebufalgo.rs.h"
#include <OpenImageIO/color.h>
#include <OpenImageIO/paramlist.h>
#include <algorithm>
#include <sstream>
#include <string>
namespace oiio {
namespace {
// OpenImageIO's arithmetic takes Image_or_Const, which is constructible from
// either an ImageBuf or a span of constants. Each pairing gets its own shim so
// the choice is made in C++ rather than smuggled across the bridge.
inline OIIO::cspan<float>
to_cspan(rust::Slice<const float> values)
{
return OIIO::cspan<float>(values.data(), std::ptrdiff_t(values.size()));
}
inline OIIO::string_view
to_string_view(const rust::Str text)
{
return OIIO::string_view(text.data(), text.size());
}
bool
to_texture_mode(int32_t mode, OIIO::ImageBufAlgo::MakeTextureMode& out)
{
if (mode < 0 || mode >= int32_t(OIIO::ImageBufAlgo::_MakeTxLast))
return false;
out = OIIO::ImageBufAlgo::MakeTextureMode(mode);
return true;
}
// A refused input is explained on the operation's own stream, while a failed
// write lands in the global error channel. Report whichever spoke, and both
// when both did.
void
collect_texture_failure(const std::ostringstream& printed, rust::String& error)
{
std::string message = OIIO::geterror();
const std::string logged = printed.str();
if (!logged.empty()) {
if (!message.empty())
message += '\n';
message += logged;
}
error = rust::String::lossy(message);
}
// Every colour operation shares one pixel engine, and that engine corrupts
// channels past the fourth. Where color_ocio.cpp says
//
// // If there are "leftover" channels, just copy them
// // unaltered from the source.
//
// the loop underneath it writes `r[c] = 0.5 + 10 * a[c];`. It looks like
// debugging code that was committed; whatever its history, it is the content
// of both 3.1.9 and 3.2.0.2dev, and it means any colour conversion of an
// image with more than four channels — a multi-AOV EXR, say — silently
// scribbles over every channel after the first four.
//
// The four the transform actually reads are correct, so the repair is to copy
// the rest from the source afterwards, which is what the comment promises. The
// copy costs one pass over channels that were about to be wrong anyway.
bool
repair_leftover_channels(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
// The region arrives already clamped to the source by color_region, and
// beginning at channel zero, so the scribble genuinely starts at 4.
ROI bounded = roi.defined() ? roi : src.roi();
bounded.chend = std::min(bounded.chend, src.nchannels());
if (bounded.chend <= 4)
return true;
ROI leftover = bounded;
leftover.chbegin = 4;
leftover.chend = std::min(bounded.chend, dst.nchannels());
if (leftover.chend <= leftover.chbegin)
return true;
return OIIO::ImageBufAlgo::copy(dst, src, OIIO::TypeDesc(), leftover,
nthreads);
}
// ociolook resolves "scene_linear" through the ColorConfig two statements
// before it checks whether that pointer is null, so the documented way of
// asking for the source's own colour space crashes on the default
// configuration. Every colour shim here passes a real ColorConfig, which side
// steps it entirely.
const OIIO::ColorConfig&
default_color_config()
{
return OIIO::ColorConfig::default_colorconfig();
}
// None of the statistics guards against a deep image, and a deep ImageBuf's
// iterator has no pixel pointer, so the first read dereferences null. Refuse
// them here.
bool
reject_deep(const ImageBuf& src, const char* operation, rust::String& error)
{
if (!src.deep())
return false;
error = rust::String::lossy(std::string(operation)
+ ": deep images have no contiguous pixels to measure");
return true;
}
// A defined region is used verbatim by these calls, and a default-constructed
// ROI carries chend = 10000. Bring it back to what the image actually holds,
// in space as well as in channels: OpenImageIO's iterators serve reads outside
// the data window as black, but three of its fast paths take a raw pointer
// from the region instead — simplePixelHashSHA1 and the float-RGBA colour path
// among them — and read past the allocation.
// Refuse two image sources that disagree on how many channels they have.
//
// `mad` builds its destination from the union of its sources, so the wider
// one decides the channel count, and the kernels then run that destination
// range over every operand: all four of them (`imagebufalgo_mad.cpp:77-78`,
// `:97-98`, `:115-116`, `:133-134` on v3.1.14.1) step
// `r[ch] = a[ch] * b[ch] + c[ch]` out to `roi.chend` without consulting any
// operand's own channel count. `ImageBuf::ConstIterator::operator[]` does not
// bounds-check either -- it indexes a proxy built over the raw pixel pointer
// (`imagebuf.h:2017`) -- so for a channel the narrower source does not have,
// the read runs past that source's pixel and the destination receives a real
// multiply-add over whatever it reached, under a success return.
//
// Nothing zeroes those channels first. IBAprep's "clear the extra channels"
// block is gated on `roi.chend < dst->nchannels()` (`imagebufalgo.cpp:274`,
// `:299` on 3.2.2.0), and `mad` calls IBAprep with no prepflags
// (`imagebufalgo_mad.cpp:185`), so `roi.chend` is still equal to the
// destination's channel count when the gate is tested and the block never
// runs. That holds on every 3.1.x and 3.2.x source checked; it is not a
// difference between versions.
//
// Property testing caught it on CI, as a one-against-two and a
// six-against-three. The shape is refused because the result is not defined
// by anything in OpenImageIO, rather than by what happens to sit in memory
// past the narrower source; `channels` is the operation for lining two
// images up first.
bool
refuse_channel_mismatch(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const char* operation)
{
if (!a.initialized() || !b.initialized())
return false;
if (a.nchannels() == b.nchannels())
return false;
dst.errorfmt("{}: the sources have {} and {} channels; OpenImageIO sizes "
"the destination from the wider one and does not reliably "
"write the channels only that one has",
operation, a.nchannels(), b.nchannels());
return true;
}
ROI
bounded_to_source(const ImageBuf& src, const ROI& roi)
{
if (!roi.defined())
return src.roi();
ROI bounded = roi;
bounded.chbegin = std::max(bounded.chbegin, 0);
bounded.chend = std::min(bounded.chend, src.nchannels());
ROI clipped = OIIO::roi_intersection(bounded, src.roi());
// roi_intersection takes the larger begin and the smaller end, so two
// regions that do not overlap at all come back INVERTED — end before
// begin. ROI::width() is a plain subtraction returning int, and callers
// convert it to an unsigned size: simplePixelHashSHA1 multiplies it by the
// pixel size into an imagesize_t, where a negative width becomes an
// enormous one. Collapse an empty intersection to a genuinely empty region
// instead of an inverted one.
if (clipped.xend < clipped.xbegin)
clipped.xend = clipped.xbegin;
if (clipped.yend < clipped.ybegin)
clipped.yend = clipped.ybegin;
if (clipped.zend < clipped.zbegin)
clipped.zend = clipped.zbegin;
if (clipped.chend < clipped.chbegin)
clipped.chend = clipped.chbegin;
return clipped;
}
// A deep image has no contiguous pixels, so any kernel that walks them
// dereferences a null pointer. IBAprep refuses deep images, but it is only
// ever shown dst, A, B and C: an image passed separately — a convolution
// kernel, an ST map — never reaches it, and fft skips IBAprep altogether.
// Each such argument is checked here instead.
bool
refuse_deep(ImageBuf& dst, const ImageBuf& image, const char* operation,
const char* which)
{
if (!image.deep())
return false;
dst.errorfmt("{}: the {} is a deep image, and this reads the contiguous "
"pixels a deep image does not have",
operation, which);
return true;
}
// copy and paste do support deep images, but only deep into deep. The mixed
// cases fall through to the flat kernel; copy additionally calls IBAprep with
// SUPPORT_DEEP and then discards its answer, so its own rejection never fires.
bool
refuse_mixed_deep(ImageBuf& dst, const ImageBuf& src, const char* operation)
{
if (!dst.initialized() || dst.deep() == src.deep())
return false;
dst.errorfmt("{}: one of these images is deep and the other is not; "
"OpenImageIO copies deep to deep or flat to flat, not across",
operation);
return true;
}
// warp_ sizes its per-pixel scratch buffer from the destination and then has
// filtered_sample fill it from the source, so a destination with fewer
// channels is written past the end of a stack allocation. rotate and an exact
// fit both reach the same kernel. The wider direction is refused as well, on
// the narrower ground that this family was never traced channel by channel
// the way mad and copy were: what these operations leave in the channels only
// the destination has is not established here, and a destination that matches
// its source needs no answer. A pre-allocated destination must match the
// source's channel count in both directions.
bool
refuse_narrow_destination(ImageBuf& dst, const ImageBuf& src,
const char* operation)
{
if (!dst.initialized() || dst.deep()
|| dst.nchannels() == src.nchannels())
return false;
dst.errorfmt("{}: the destination is allocated with {} channels and the "
"source has {}; narrower overruns OpenImageIO's per-pixel "
"buffer and wider is returned partly unwritten, so line the "
"channel counts up first",
operation, dst.nchannels(), src.nchannels());
return true;
}
// A defined region that does not overlap the source names no pixels at all.
// OpenImageIO sizes the destination from it, gets a buffer with no storage,
// and then asserts inside its own zeroing of the channels outside the range —
// which ends the process rather than returning false. Refusing is both safe
// and more use to the caller than an empty result would be.
bool
refuse_empty_region(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
const char* operation)
{
if (!roi.defined())
return false;
const auto empty = [](const ROI& r) {
return r.xend <= r.xbegin || r.yend <= r.ybegin || r.zend <= r.zbegin;
};
if (empty(OIIO::roi_intersection(roi, src.roi()))) {
dst.errorfmt("{}: the region {},{} to {},{} does not overlap the "
"source, whose pixels span {},{} to {},{}",
operation, roi.xbegin, roi.ybegin, roi.xend, roi.yend,
src.roi().xbegin, src.roi().ybegin, src.roi().xend,
src.roi().yend);
return true;
}
// The destination matters too when it is already allocated: OpenImageIO
// intersects the region with it, and an empty result leaves the kernel
// dividing by a zero-width scanline.
if (dst.initialized() && empty(OIIO::roi_intersection(roi, dst.roi()))) {
dst.errorfmt("{}: the region {},{} to {},{} does not overlap the "
"destination, whose pixels span {},{} to {},{}",
operation, roi.xbegin, roi.ybegin, roi.xend, roi.yend,
dst.roi().xbegin, dst.roi().ybegin, dst.roi().xend,
dst.roi().yend);
return true;
}
return false;
}
// Several operations support deep images on both sides but assert rather than
// erroring when only one side is deep: the deep path calls copy_deep_pixel,
// whose OIIO_ASSERT(dst.deep() && src.deep()) a release build does not check.
// With no explicit region, IBAprep uses the UNION of the inputs' data windows.
// Two images whose windows sit far apart — one at the origin, one at 100000 —
// union to everything in between, and OpenImageIO then tries to allocate a
// destination that size. The allocation fails, and what follows is a division
// by the resulting zero-width scanline. Same shape as the fft case above.
bool
refuse_distant_pair(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const char* operation)
{
const OIIO::imagesize_t held = a.roi().npixels() + b.roi().npixels();
const OIIO::imagesize_t spanned
= OIIO::roi_union(a.roi(), b.roi()).npixels();
if (spanned <= held * 16 + 1024)
return false;
dst.errorfmt("{}: the two images sit too far apart to combine: one spans "
"{},{} to {},{} and the other {},{} to {},{}, so the result "
"would cover {} pixels for {} of input. Give an explicit "
"region, or move them onto the same coordinates",
operation, a.roi().xbegin, a.roi().ybegin, a.roi().xend,
a.roi().yend, b.roi().xbegin, b.roi().ybegin, b.roi().xend,
b.roi().yend, spanned, held);
return true;
}
// OpenImageIO's arithmetic accepts deep images and then handles them poorly:
// the surplus-channel fixup calls a deep copy over a channel range that copy
// asserts against, and several paths reach copy_deep_pixel with a destination
// that never came out deep. Those assertions are compiled away in a release
// build, so what a caller gets is a dead process.
//
// The crate has operations built for deep images — flatten, deepen,
// deep_merge, deep_holdout — and they are guarded properly. Deep arithmetic is
// not something OpenImageIO supports well enough to pass on, so these refuse
// it outright rather than passing on a landmine.
bool
refuse_deep_mismatch(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const char* operation)
{
if (!a.deep() && !b.deep())
return false;
dst.errorfmt("{}: deep images are not supported here; flatten them first, "
"or use deep_merge or deep_holdout",
operation);
return true;
}
// The deep compositing operations need every image deep, and OpenImageIO
// asserts rather than erroring when a destination it allocated does not come
// out deep. These say so before it can.
bool
require_deep(ImageBuf& dst, const ImageBuf& image, const char* operation,
const char* which)
{
if (image.deep())
return false;
dst.errorfmt("{}: the {} is not a deep image", operation, which);
return true;
}
bool
refuse_flat_destination(ImageBuf& dst, const char* operation)
{
if (!dst.initialized() || dst.deep())
return false;
dst.errorfmt("{}: the destination is a flat image; pass an empty one or a "
"deep one",
operation);
return true;
}
// resize_ is the mirror image: it sizes the same per-pixel buffer from the
// destination and then reads the SOURCE pixel to that length, so a WIDER
// destination reads past the source. warp overruns for a narrower one, resize
// for a wider one, and fit reaches warp_ when exact and resize_ otherwise —
// so fit needs both, which comes to requiring the counts to match.
bool
refuse_wide_destination(ImageBuf& dst, const ImageBuf& src,
const char* operation)
{
if (!dst.initialized() || dst.nchannels() <= src.nchannels())
return false;
dst.errorfmt("{}: the destination has {} channels and the source has {}; "
"OpenImageIO reads past the source pixel when the "
"destination is wider",
operation, dst.nchannels(), src.nchannels());
return true;
}
// The companion to the guard above, for the operations that pass the CALLER'S
// region through to the kernel rather than having IBAprep widen one for them.
//
// The two are not interchangeable and an operation needs whichever matches how
// its range is decided. `invert`, `clamp`, `contrast_remap` and `st_warp` call
// IBAprep with an undefined region, and its initialized-destination branch
// replaces that with the destination's whole window including chend, so the
// destination's width is what reaches the kernel and
// refuse_wide_destination is the guard that sees it. `flip`, `flop` and the
// three quarter rotations instead copy the region they were given straight
// into their own loop bounds: with an undefined region they substitute
// `src.roi()` and are correct, and only a DEFINED region whose chend runs past
// the source reaches an unchecked read. Guarding those on the destination's
// width instead would refuse the undefined case too, which works today.
//
// `transpose` already clamps its region to the source and is the model for what
// the others should have done.
bool
refuse_wide_region(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
const char* operation)
{
if (!roi.defined() || !src.initialized()
|| roi.chend <= src.nchannels())
return false;
dst.errorfmt("{}: the region asks for channels up to {} and the source has "
"{}; OpenImageIO reads past the source pixel rather than "
"clipping the region to it",
operation, roi.chend, src.nchannels());
return true;
}
// The colour engine mishandles a region that starts above channel zero in
// three separate ways, all measured: it transforms channels 0..n rather than
// the ones asked for, it leaves the requested upper channels merely copied,
// and the scribble described above begins at min(4, roi.nchannels()) rather
// than at channel 4, so it lands below where the repair reaches. No ordering
// of the repair rescues that, so the region is refused instead — the same
// shape is_constant_color and nonzero_region already refuse.
//
// The region is clamped to the source as well, because the float-RGBA fast
// path memcpys from the source's pixel address across the region's width, and
// IBAprep has only intersected the region with the destination.
bool
color_region(ImageBuf& dst, const ImageBuf& src, const ROI& roi, ROI& bounded,
const char* operation)
{
if (refuse_deep(dst, src, operation, "source"))
return false;
bounded = bounded_to_source(src, roi);
if (bounded.chbegin != 0) {
dst.errorfmt("{}: the region must begin at channel zero; OpenImageIO "
"transforms the wrong channels otherwise",
operation);
return false;
}
return true;
}
} // namespace
PixelStatistics
imagebufalgo_pixel_stats(const ImageBuf& src, const ROI& roi, int nthreads)
{
PixelStatistics result;
result.ok = false;
if (src.deep()) {
result.error = rust::String::lossy(
"pixel statistics: deep images are measured per sample, which this "
"call does not report");
return result;
}
// OpenImageIO decides success by asking whether `src` carries an error at
// all, so anything left over from an earlier call would be attributed to
// this one. Clear it before measuring.
src.geterror(true);
const OIIO::ImageBufAlgo::PixelStats stats
= OIIO::ImageBufAlgo::computePixelStats(src, bounded_to_source(src, roi),
nthreads);
if (stats.min.empty()) {
std::string message = src.geterror(true);
if (message.empty())
message = "OpenImageIO reported no statistics and no reason";
result.error = rust::String::lossy(message);
return result;
}
const auto copy_floats = [](const std::vector<float>& from,
rust::Vec<float>& to) {
to.reserve(from.size());
for (float value : from)
to.push_back(value);
};
const auto copy_counts = [](const std::vector<OIIO::imagesize_t>& from,
rust::Vec<uint64_t>& to) {
to.reserve(from.size());
for (OIIO::imagesize_t value : from)
to.push_back(uint64_t(value));
};
copy_floats(stats.min, result.min);
copy_floats(stats.max, result.max);
copy_floats(stats.avg, result.average);
copy_floats(stats.stddev, result.standard_deviation);
copy_counts(stats.nancount, result.nan_count);
copy_counts(stats.infcount, result.infinite_count);
copy_counts(stats.finitecount, result.finite_count);
result.ok = true;
return result;
}
rust::Vec<uint64_t>
imagebufalgo_histogram(const ImageBuf& src, int channel, int bins, float min,
float max, bool ignore_empty, const ROI& roi,
int nthreads, rust::String& error)
{
rust::Vec<uint64_t> result;
if (reject_deep(src, "histogram", error))
return result;
src.geterror(true);
const std::vector<OIIO::imagesize_t> counts
= OIIO::ImageBufAlgo::histogram(src, channel, bins, min, max,
ignore_empty,
bounded_to_source(src, roi), nthreads);
if (counts.empty()) {
std::string message = src.geterror(true);
if (message.empty())
message = "OpenImageIO produced no histogram and no reason";
error = rust::String::lossy(message);
return result;
}
result.reserve(counts.size());
for (OIIO::imagesize_t count : counts)
result.push_back(uint64_t(count));
return result;
}
bool
imagebufalgo_is_constant_color(const ImageBuf& src, float threshold,
rust::Slice<float> color, const ROI& roi,
int nthreads, rust::String& error)
{
if (reject_deep(src, "is_constant_color", error))
return false;
const ROI bounded = bounded_to_source(src, roi);
if (bounded.chbegin != 0) {
// imagebufalgo_compare.cpp sizes the reference vector to the region's
// channel count but indexes it with absolute channel numbers, so a
// region starting above channel zero writes past its end.
error = rust::String::lossy(
"is_constant_color: the region must begin at channel zero; "
"OpenImageIO writes past its own buffer otherwise");
return false;
}
src.geterror(true);
const bool constant
= OIIO::ImageBufAlgo::isConstantColor(src, threshold,
OIIO::span<float>(color.data(),
std::ptrdiff_t(
color.size())),
bounded, nthreads);
if (!constant) {
const std::string message = src.geterror(true);
if (!message.empty())
error = rust::String::lossy(message);
}
return constant;
}
bool
imagebufalgo_is_constant_channel(const ImageBuf& src, int channel, float value,
float threshold, const ROI& roi, int nthreads,
rust::String& error)
{
if (reject_deep(src, "is_constant_channel", error))
return false;
if (channel < 0 || channel >= src.nchannels()) {
// OpenImageIO returns false here and records nothing, which is
// indistinguishable from "the channel is not constant".
error = rust::String::lossy("is_constant_channel: channel "
+ std::to_string(channel) + " is outside the "
+ std::to_string(src.nchannels())
+ " the image has");
return false;
}
src.geterror(true);
const bool constant
= OIIO::ImageBufAlgo::isConstantChannel(src, channel, value, threshold,
bounded_to_source(src, roi),
nthreads);
if (!constant) {
const std::string message = src.geterror(true);
if (!message.empty())
error = rust::String::lossy(message);
}
return constant;
}
bool
imagebufalgo_is_monochrome(const ImageBuf& src, float threshold, const ROI& roi,
int nthreads, rust::String& error)
{
if (reject_deep(src, "is_monochrome", error))
return false;
src.geterror(true);
const bool monochrome
= OIIO::ImageBufAlgo::isMonochrome(src, threshold,
bounded_to_source(src, roi),
nthreads);
if (!monochrome) {
const std::string message = src.geterror(true);
if (!message.empty())
error = rust::String::lossy(message);
}
return monochrome;
}
ROI
imagebufalgo_nonzero_region(const ImageBuf& src, const ROI& roi, int nthreads,
rust::String& error)
{
const ROI bounded = bounded_to_source(src, roi);
if (bounded.chbegin != 0) {
// nonzero_region trims by calling isConstantColor, so it inherits that
// function's out-of-bounds write for a region above channel zero.
error = rust::String::lossy(
"nonzero_region: the region must begin at channel zero; "
"OpenImageIO writes past its own buffer otherwise");
return ROI();
}
src.geterror(true);
return OIIO::ImageBufAlgo::nonzero_region(src, bounded, nthreads);
}
rust::String
imagebufalgo_pixel_hash_sha1(const ImageBuf& src, const rust::Str extrainfo,
const ROI& roi, int nthreads, rust::String& error)
{
if (reject_deep(src, "pixel_hash_sha1", error))
return rust::String();
const ROI hashed = bounded_to_source(src, roi);
if (!src.initialized() || src.spec().pixel_bytes() == 0
|| hashed.npixels() == 0) {
// simplePixelHashSHA1 divides by roi.width() * pixel_bytes() without
// checking it, so an empty region takes the process down with an
// integer division by zero. That includes a region clamped to nothing
// because it never overlapped the image.
error = rust::String::lossy(
"pixel_hash_sha1: the region holds no pixels to hash");
return rust::String();
}
src.geterror(true);
// Block size fixed at 0: any other value changes the digest for identical
// pixels, and combined with a region that does not start at the image's
// first row it indexes past the end of the block-results vector.
const std::string digest
= OIIO::ImageBufAlgo::computePixelHashSHA1(src,
to_string_view(extrainfo),
hashed, 0, nthreads);
if (digest.empty()) {
std::string message = src.geterror(true);
if (message.empty())
message = "OpenImageIO produced no digest and no reason";
error = rust::String::lossy(message);
}
return rust::String::lossy(digest);
}
bool
imagebufalgo_zero(ImageBuf& dst, const ROI& roi, int nthreads)
{
return OIIO::ImageBufAlgo::zero(dst, roi, nthreads);
}
bool
imagebufalgo_fill(ImageBuf& dst, rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::fill(dst, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_add_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "add")
|| refuse_deep_mismatch(dst, a, b, "add"))
return false;
return OIIO::ImageBufAlgo::add(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_add_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::add(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_sub_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "sub")
|| refuse_deep_mismatch(dst, a, b, "sub"))
return false;
return OIIO::ImageBufAlgo::sub(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_sub_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::sub(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_mul_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "mul")
|| refuse_deep_mismatch(dst, a, b, "mul"))
return false;
return OIIO::ImageBufAlgo::mul(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_mul_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::mul(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_div_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "div")
|| refuse_deep_mismatch(dst, a, b, "div"))
return false;
return OIIO::ImageBufAlgo::div(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_div_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::div(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_abs(ImageBuf& dst, const ImageBuf& a, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, a, roi, "abs"))
return false;
return OIIO::ImageBufAlgo::abs(dst, a, roi, nthreads);
}
bool
imagebufalgo_absdiff_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "absdiff")
|| refuse_deep_mismatch(dst, a, b, "absdiff"))
return false;
return OIIO::ImageBufAlgo::absdiff(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_copy(ImageBuf& dst, const ImageBuf& src, TypeDesc convert,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "copy"))
return false;
if (refuse_mixed_deep(dst, src, "copy"))
return false;
// A destination that is already allocated keeps its own shape, and the
// clamp that looks like it protects the extra channels does not. `copy`
// runs `roi.chend = std::min(roi.chend, src.nchannels())`
// (`imagebufalgo_copy.cpp:196` on v3.1.14.1) against the ROI it was
// handed, but a default ROI has `chend` 0 and is undefined, so that is a
// no-op; IBAprep's initialized-destination branch then replaces the ROI
// wholesale with the destination's own pixel window
// (`imagebufalgo.cpp:110-112`). `copy_` goes on to run `d[c] = s[c]` over
// that full range with no guard against the source's channel count
// (`imagebufalgo_copy.cpp:145-146`) -- where `paste_`, a hundred lines
// above it in the same file, does guard, with
// `c < src_nchans ? s[c] : D(0)` (`:46`). So the destination's extra channels are written from an
// unchecked read past the source's pixel: the same unbounded
// `ConstIterator::operator[]` that makes mad unsafe, reached by a
// different route. Property testing caught it on CI as a one-channel
// source copied into a pre-allocated five-channel destination whose
// window did not even overlap the source's: success, with inf in a
// channel the source does not have. Refuse the shapes the copy cannot
// cover.
if (dst.initialized() && !dst.deep()) {
if (dst.nchannels() != src.nchannels()) {
dst.errorfmt("copy: the destination is allocated with {} channels "
"and the source has {}; line them up with channels "
"first, or copy into an empty destination",
dst.nchannels(), src.nchannels());
return false;
}
const OIIO::ROI overlap = OIIO::roi_intersection(dst.roi(), src.roi());
if (overlap.xend <= overlap.xbegin || overlap.yend <= overlap.ybegin) {
dst.errorfmt(
"copy: the source's data window does not reach the allocated "
"destination, so nothing would be copied and the destination "
"would come back unchanged under a success return");
return false;
}
}
return OIIO::ImageBufAlgo::copy(dst, src, convert, roi, nthreads);
}
bool
imagebufalgo_crop(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "crop"))
return false;
return OIIO::ImageBufAlgo::crop(dst, src, roi, nthreads);
}
bool
imagebufalgo_flip(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "flip")
|| refuse_wide_region(dst, src, roi, "flip"))
return false;
return OIIO::ImageBufAlgo::flip(dst, src, roi, nthreads);
}
bool
imagebufalgo_flop(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "flop")
|| refuse_wide_region(dst, src, roi, "flop"))
return false;
return OIIO::ImageBufAlgo::flop(dst, src, roi, nthreads);
}
bool
imagebufalgo_transpose(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "transpose"))
return false;
if (refuse_deep(dst, src, "transpose", "source"))
return false;
return OIIO::ImageBufAlgo::transpose(dst, src, roi, nthreads);
}
bool
imagebufalgo_colorconvert(ImageBuf& dst, const ImageBuf& src,
const rust::Str fromspace, const rust::Str tospace,
bool unpremult, const ROI& roi, int nthreads)
{
ROI bounded;
if (!color_region(dst, src, roi, bounded, "colorconvert"))
return false;
const std::string from(to_string_view(fromspace));
const std::string to(to_string_view(tospace));
if (!OIIO::ImageBufAlgo::colorconvert(dst, src, from, to, unpremult, "", "",
&default_color_config(), bounded,
nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_colormatrixtransform(ImageBuf& dst, const ImageBuf& src,
rust::Slice<const float> matrix,
bool unpremult, const ROI& roi, int nthreads)
{
if (matrix.size() != 16) {
dst.errorfmt("colour matrix transform: the matrix needs sixteen "
"values, got {}",
matrix.size());
return false;
}
ROI bounded;
if (!color_region(dst, src, roi, bounded, "colour matrix transform"))
return false;
float m[4][4];
for (std::size_t row = 0; row < 4; ++row)
for (std::size_t column = 0; column < 4; ++column)
m[row][column] = matrix[row * 4 + column];
if (!OIIO::ImageBufAlgo::colormatrixtransform(dst, src, m, unpremult,
bounded, nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_ociolook(ImageBuf& dst, const ImageBuf& src,
const rust::Str looks, const rust::Str fromspace,
const rust::Str tospace, bool unpremult, bool inverse,
const rust::Str context_key,
const rust::Str context_value, const ROI& roi,
int nthreads)
{
const std::string look_list(to_string_view(looks));
const std::string from(to_string_view(fromspace));
const std::string to(to_string_view(tospace));
const std::string key(to_string_view(context_key));
const std::string value(to_string_view(context_value));
ROI bounded;
if (!color_region(dst, src, roi, bounded, "ociolook"))
return false;
if (!OIIO::ImageBufAlgo::ociolook(dst, src, look_list, from, to, unpremult,
inverse, key, value,
&default_color_config(), bounded,
nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_ociodisplay(ImageBuf& dst, const ImageBuf& src,
const rust::Str display, const rust::Str view,
const rust::Str fromspace, const rust::Str looks,
bool unpremult, bool inverse,
const rust::Str context_key,
const rust::Str context_value, const ROI& roi,
int nthreads)
{
const std::string display_name(to_string_view(display));
const std::string view_name(to_string_view(view));
const std::string from(to_string_view(fromspace));
const std::string look_list(to_string_view(looks));
const std::string key(to_string_view(context_key));
const std::string value(to_string_view(context_value));
ROI bounded;
if (!color_region(dst, src, roi, bounded, "ociodisplay"))
return false;
if (!OIIO::ImageBufAlgo::ociodisplay(dst, src, display_name, view_name,
from, look_list, unpremult, inverse,
key, value, &default_color_config(),
bounded, nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_ociofiletransform(ImageBuf& dst, const ImageBuf& src,
const rust::Str name, bool unpremult,
bool inverse, const ROI& roi, int nthreads)
{
// OpenImageIO hands this straight to OCIO through c_str(string_view),
// which reads one byte past a view that is not NUL-terminated. A Rust
// &str never is, so it becomes a std::string here first.
const std::string transform(to_string_view(name));
if (transform.empty()) {
dst.errorfmt("colour file transform: no transform file was named");
return false;
}
ROI bounded;
if (!color_region(dst, src, roi, bounded, "ociofiletransform"))
return false;
if (!OIIO::ImageBufAlgo::ociofiletransform(dst, src, transform, unpremult,
inverse, &default_color_config(),
bounded, nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_ocionamedtransform(ImageBuf& dst, const ImageBuf& src,
const rust::Str name, bool unpremult,
bool inverse, const rust::Str context_key,
const rust::Str context_value, const ROI& roi,
int nthreads)
{
const std::string transform(to_string_view(name));
const std::string key(to_string_view(context_key));
const std::string value(to_string_view(context_value));
ROI bounded;
if (!color_region(dst, src, roi, bounded, "ocionamedtransform"))
return false;
if (!OIIO::ImageBufAlgo::ocionamedtransform(dst, src, transform, unpremult,
inverse, key, value,
&default_color_config(),
bounded, nthreads))
return false;
return repair_leftover_channels(dst, src, bounded, nthreads);
}
bool
imagebufalgo_resize(ImageBuf& dst, const ImageBuf& src,
const rust::Str filtername, float filterwidth,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "resize"))
return false;
if (refuse_wide_destination(dst, src, "resize"))
return false;
OIIO::ParamValueList options;
if (filtername.size() != 0)
options["filtername"] = std::string(filtername.data(),
filtername.size());
if (filterwidth > 0.0f)
options["filterwidth"] = filterwidth;
return OIIO::ImageBufAlgo::resize(dst, src, options, roi, nthreads);
}
bool
imagebufalgo_fit(ImageBuf& dst, const ImageBuf& src, const rust::Str filtername,
float filterwidth, const rust::Str fillmode, bool exact,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "fit"))
return false;
// An exact fit reaches warp_ and an inexact one reaches resize_; the two
// overrun in opposite directions, so a pre-allocated destination has to
// match the source's channel count either way.
if (refuse_narrow_destination(dst, src, "fit")
|| refuse_wide_destination(dst, src, "fit"))
return false;
OIIO::ParamValueList options;
if (filtername.size() != 0)
options["filtername"] = std::string(filtername.data(),
filtername.size());
if (filterwidth > 0.0f)
options["filterwidth"] = filterwidth;
if (fillmode.size() != 0)
options["fillmode"] = std::string(fillmode.data(), fillmode.size());
options["exact"] = int(exact);
return OIIO::ImageBufAlgo::fit(dst, src, options, roi, nthreads);
}
bool
imagebufalgo_resample(ImageBuf& dst, const ImageBuf& src, bool interpolate,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "resample"))
return false;
return OIIO::ImageBufAlgo::resample(dst, src, interpolate, roi, nthreads);
}
bool
imagebufalgo_over(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "over")
|| refuse_deep_mismatch(dst, a, b, "over"))
return false;
return OIIO::ImageBufAlgo::over(dst, a, b, roi, nthreads);
}
// premult and unpremult, given a source with no alpha channel, document that
// they "just copy instead of dividing by alpha" — and implement that copy as
//
// paste(dst, src.spec().x, src.spec().y, src.spec().z, roi.chbegin, src, roi, ...)
//
// but paste ADDS its offset to the source's own coordinates, so the origin is
// counted twice. For a data window at 5,7 the pixels land 5,7 further along
// than they should: part of the destination gets the image, the rest is left
// as allocated. Measured on a 4x1 RGB image at origin 5,7 — every pixel of the
// result came back empty, and the call reported success.
//
// The copy is the intent, so do the copy -- but through `imagebufalgo_copy`
// rather than `OIIO::ImageBufAlgo::copy`, so that the guards that shim applies
// to a direct `copy` apply here too. Calling the library function directly
// routed around the channel guard at the top of this file, which made
// `premult` and `unpremult` on an alpha-less source the one public way into the
// unchecked read past the source's pixel: measured on a 4x4 one-channel ramp
// into a pre-allocated 4x4 five-channel destination, pixel 0,0 came back as the
// source's next four pixels and pixel 3,3 read past the end of its allocation,
// both under a success return. The policy belongs in one place.
bool
copy_instead_of_alpha_division(ImageBuf& dst, const ImageBuf& src,
const ROI& roi, int nthreads)
{
return imagebufalgo_copy(dst, src, OIIO::TypeDesc(), roi, nthreads);
}
bool
imagebufalgo_premult(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "premult"))
return false;
if (src.spec().alpha_channel < 0)
return copy_instead_of_alpha_division(dst, src, roi, nthreads);
return OIIO::ImageBufAlgo::premult(dst, src, roi, nthreads);
}
bool
imagebufalgo_unpremult(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "unpremult"))
return false;
if (src.spec().alpha_channel < 0)
return copy_instead_of_alpha_division(dst, src, roi, nthreads);
return OIIO::ImageBufAlgo::unpremult(dst, src, roi, nthreads);
}
bool
imagebufalgo_repremult(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "repremult"))
return false;
// Unlike premult/unpremult, whose no-alpha fallback is a documented copy,
// repremult with no alpha channel silently degenerates to a paste that
// this file already documents as broken for offset origins. An image with
// no alpha cannot be re-premultiplied; say so.
if (src.spec().alpha_channel < 0) {
dst.errorfmt("repremult: the source has no alpha channel to "
"re-premultiply by");
return false;
}
return OIIO::ImageBufAlgo::repremult(dst, src, roi, nthreads);
}
bool
imagebufalgo_zover(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
bool z_zeroisinf, const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "zover")
|| refuse_deep_mismatch(dst, a, b, "zover")
|| refuse_narrow_destination(dst, a, "zover")
|| refuse_channel_mismatch(dst, a, b, "zover"))
return false;
return OIIO::ImageBufAlgo::zover(dst, a, b, z_zeroisinf, roi, nthreads);
}
bool
imagebufalgo_scale(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "scale")
|| refuse_deep_mismatch(dst, a, b, "scale"))
return false;
// A pre-allocated destination wider than the multi-channel input makes
// the kernel read a[c] past that input's last pixel: IBAprep clamps the
// channel range only to max(dst, a, b), and scale_impl loops it over
// the wide operand unchecked. Same class the mad and copy guards close.
const int wide = std::max(a.nchannels(), b.nchannels());
if (dst.initialized() && !dst.deep() && dst.nchannels() != wide) {
dst.errorfmt("scale: the destination is allocated with {} channels "
"and the wider source has {}; use an empty destination "
"or matching channel counts",
dst.nchannels(), wide);
return false;
}
// The KWArgs parameter is reserved and ignored in 3.1; not forwarded.
return OIIO::ImageBufAlgo::scale(dst, a, b, {}, roi, nthreads);
}
bool
imagebufalgo_fix_non_finite(ImageBuf& dst, const ImageBuf& src, int mode,
int64_t& pixels_fixed, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "fix_non_finite"))
return false;
// The kernel iterates Iterator<T,T> over the destination's type while
// reading the source; a pre-allocated destination of a different width
// walks the source at the wrong stride. Same guard unsharp_mask carries.
if (dst.initialized() && !dst.deep()
&& dst.spec().format != src.spec().format) {
dst.errorfmt("fix_non_finite: the destination is allocated as {} and "
"the source is {}; use an empty destination or matching "
"formats",
dst.spec().format, src.spec().format);
return false;
}
int fixed = 0;
bool ok = OIIO::ImageBufAlgo::fixNonFinite(
dst, src, OIIO::ImageBufAlgo::NonFiniteFixMode(mode), &fixed, roi,
nthreads);
pixels_fixed = fixed;
return ok;
}
bool
imagebufalgo_rangecompress(ImageBuf& dst, const ImageBuf& src, bool use_luma,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rangecompress"))
return false;
return OIIO::ImageBufAlgo::rangecompress(dst, src, use_luma, roi,
nthreads);
}
bool
imagebufalgo_rangeexpand(ImageBuf& dst, const ImageBuf& src, bool use_luma,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rangeexpand"))
return false;
return OIIO::ImageBufAlgo::rangeexpand(dst, src, use_luma, roi, nthreads);
}
bool
imagebufalgo_channel_append(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
int nthreads)
{
// channel_append never calls IBAprep: it derives the union region and
// writes both inputs' channels through iterators over the destination it
// shaped itself. A deep input has no flat pixels for those iterators, and
// a pre-allocated destination keeps its own shape while the kernel writes
// the union's — scratch writes into blackpixel storage shared across
// threads. Refuse both; the caller-supplied region is not forwarded
// because upstream disregards it.
if (a.deep() || b.deep() || dst.deep()) {
dst.errorfmt("channel_append: deep images are not supported");
return false;
}
if (dst.initialized()) {
dst.errorfmt("channel_append: use an empty destination; a "
"pre-allocated one keeps its shape while the kernel "
"writes the union of the sources");
return false;
}
if (refuse_distant_pair(dst, a, b, "channel_append"))
return false;
return OIIO::ImageBufAlgo::channel_append(dst, a, b, {}, nthreads);
}
// maxchan and minchan reduce across channels into one; neither is IBAprep'd
// against a deep source, and both read a[roi.chbegin] unconditionally, so the
// channel range must be real before OpenImageIO sees it.
static bool
refuse_bad_chan_reduce(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
const char* operation)
{
if (src.deep()) {
dst.errorfmt("{}: deep images are not supported", operation);
return true;
}
if (roi.defined()
&& (roi.chbegin >= src.nchannels() || roi.chend <= roi.chbegin)) {
dst.errorfmt("{}: the channel range {}..{} names no channel of a "
"{}-channel image",
operation, roi.chbegin, roi.chend, src.nchannels());
return true;
}
if (dst.initialized() && !dst.deep() && dst.nchannels() != 1) {
dst.errorfmt("{}: the result has one channel and the destination is "
"allocated with {}; use an empty destination",
operation, dst.nchannels());
return true;
}
// The spatial half of the same hazard: upstream clamps only its private
// copy of the region against the destination and hands the kernel the
// ORIGINAL one, so every position outside a smaller destination's window
// lands the write iterator on the buffer's shared blackpixel scratch —
// concurrent unsynchronized writes from the thread pool. The walked
// region must lie inside the destination's window.
if (dst.initialized() && !dst.deep()) {
const OIIO::ROI walked = roi.defined() ? roi : src.roi();
const OIIO::ROI window = dst.roi();
if (walked.xbegin < window.xbegin || walked.xend > window.xend
|| walked.ybegin < window.ybegin || walked.yend > window.yend) {
dst.errorfmt(
"{}: the region to reduce does not fit the allocated "
"destination's data window; use an empty destination",
operation);
return true;
}
}
return false;
}
bool
imagebufalgo_maxchan(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_bad_chan_reduce(dst, src, roi, "maxchan"))
return false;
return OIIO::ImageBufAlgo::maxchan(dst, src, roi, nthreads);
}
bool
imagebufalgo_minchan(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_bad_chan_reduce(dst, src, roi, "minchan"))
return false;
return OIIO::ImageBufAlgo::minchan(dst, src, roi, nthreads);
}
bool
imagebufalgo_demosaic(ImageBuf& dst, const ImageBuf& src, rust::Str pattern,
rust::Str algorithm, rust::Str layout,
rust::Slice<const float> white_balance, int nthreads,
rust::String& error)
{
error = rust::String();
if (src.deep()) {
error = rust::String::lossy("demosaic: deep images are not supported");
return false;
}
// The decoders fold the pixel coordinate into a channel-map cell with
// arithmetic that goes negative for a data window left of the origin,
// and the cell picks the decode routine — a negative index there is an
// indirect call through whatever sits before the table. Mosaics from
// cameras start at the origin; require that.
if (src.spec().x < 0 || src.spec().y < 0) {
error = rust::String::lossy(
"demosaic: the source's data window must not start at negative "
"coordinates");
return false;
}
// The result is three channels decoded from a one-channel mosaic, and
// IBAprep's verdict on a pre-allocated destination is ignored upstream;
// an empty destination sidesteps both.
if (dst.initialized()) {
error = rust::String::lossy(
"demosaic: use an empty destination; the result is shaped by the "
"decode");
return false;
}
OIIO::ParamValueList arguments;
arguments.attribute("pattern", to_string_view(pattern));
arguments.attribute("algorithm", to_string_view(algorithm));
arguments.attribute("layout", to_string_view(layout));
if (!white_balance.empty())
arguments.attribute("white_balance",
OIIO::TypeDesc(OIIO::TypeDesc::FLOAT,
int(white_balance.size())),
white_balance.data());
dst.geterror(true);
const bool ok = OIIO::ImageBufAlgo::demosaic(dst, src, arguments, {},
nthreads);
if (!ok || dst.has_error()) {
std::string recorded = dst.geterror(true);
if (recorded.empty())
recorded = "OpenImageIO could not demosaic the image";
error = rust::String::lossy(recorded);
return false;
}
return true;
}
bool
imagebufalgo_normalize(ImageBuf& dst, const ImageBuf& src, float in_center,
float out_center, float scale, const ROI& roi,
int nthreads, rust::String& error)
{
error = rust::String();
if (refuse_empty_region(dst, src, roi, "normalize"))
return false;
// The kernel reads the source through an iterator of the destination's
// type, so a pre-allocated destination of a different width walks the
// source at the wrong stride.
if (dst.initialized() && !dst.deep()
&& dst.spec().format != src.spec().format) {
dst.errorfmt("normalize: the destination is allocated as {} and the "
"source is {}; use an empty destination or matching "
"formats",
dst.spec().format, src.spec().format);
return false;
}
// The kernel writes r[0..2] unconditionally, ignoring the channel
// clamp, and upstream refuses only a destination WIDER than the source
// -- so a pre-allocated one- or two-channel destination is written past
// each pixel and past the end of the allocation at the last one. The
// channel counts must match exactly.
if (dst.initialized() && !dst.deep()
&& dst.nchannels() != src.nchannels()) {
dst.errorfmt("normalize: the destination is allocated with {} "
"channels and the source has {}; the kernel writes "
"three channels regardless, so use an empty destination "
"or matching counts",
dst.nchannels(), src.nchannels());
return false;
}
// The 3/4-channel refusal is recorded on the SOURCE, not the
// destination, so both must be drained to say why the call failed.
src.geterror(true);
if (OIIO::ImageBufAlgo::normalize(dst, src, in_center, out_center, scale,
roi, nthreads))
return true;
std::string recorded = dst.geterror(true);
if (recorded.empty())
recorded = src.geterror(true);
if (recorded.empty())
recorded = "OpenImageIO could not normalize the image";
error = rust::String::lossy(recorded);
return false;
}
bool
imagebufalgo_fillholes_pushpull(ImageBuf& dst, const ImageBuf& src,
int nthreads)
{
// The push-pull pyramid always processes the whole source — a caller's
// region would be quietly ignored, so the shim does not take one. Its
// internal paste/resize/over returns are discarded upstream, which turns
// an allocation failure part way down into a silently black result under
// a success return; the error state check catches what the return does
// not, and the try/catch covers the pyramid's own float allocations
// (roughly twice the image again) escaping through this noexcept shim.
if (src.deep() || dst.deep()) {
dst.errorfmt("fillholes_pushpull: deep images are not supported");
return false;
}
try {
dst.geterror(true);
const bool ok = OIIO::ImageBufAlgo::fillholes_pushpull(dst, src, {},
nthreads);
if (!ok)
return false;
if (dst.has_error())
return false;
return true;
} catch (const std::exception& exception) {
const std::string recorded = exception.what();
dst.errorfmt("fillholes_pushpull: {}",
recorded.empty() ? "the pyramid could not be allocated"
: recorded.c_str());
return false;
}
}
bool
imagebufalgo_color_range_check(const ImageBuf& src,
rust::Slice<const float> low,
rust::Slice<const float> high,
RangeCheckCounts& counts, const ROI& roi,
int nthreads, rust::String& error)
{
error = rust::String();
// The kernel iterates flat pixels; a deep source has none, and this
// measurement is never IBAprep'd against one.
if (src.deep()) {
error = rust::String::lossy(
"color_range_check: deep images are not supported");
return false;
}
// chend is clamped to the source but chbegin is not, so a channel range
// starting past the last channel loops over nothing and reports every
// counter as zero under a success return. Refuse it instead.
if (roi.defined()
&& (roi.chbegin >= src.nchannels() || roi.chend <= roi.chbegin)) {
error = rust::String::lossy(
"color_range_check: the channel range names no channel of the "
"source");
return false;
}
OIIO::imagesize_t lowcount = 0, highcount = 0, inrange = 0;
src.geterror(true);
const bool ok = OIIO::ImageBufAlgo::color_range_check(
src, &lowcount, &highcount, &inrange, to_cspan(low), to_cspan(high),
roi, nthreads);
if (!ok) {
std::string recorded = src.geterror(true);
if (recorded.empty())
recorded = "OpenImageIO could not check the range";
error = rust::String::lossy(recorded);
return false;
}
counts.low = lowcount;
counts.high = highcount;
counts.in_range = inrange;
return true;
}
bool
imagebufalgo_color_map(ImageBuf& dst, const ImageBuf& src, int srcchannel,
int nknots, int channels, rust::Slice<const float> knots,
const ROI& roi, int nthreads)
{
if (src.deep()) {
dst.errorfmt("color_map: deep images are not supported");
return false;
}
// The room check upstream multiplies nknots * channels as int, so a pair
// whose product overflows passes it and the interpolation reads the knot
// span far out of bounds. Do the multiply wide and against the actual
// slice length here.
if (nknots < 2 || channels < 1) {
dst.errorfmt("color_map: at least two knots and one channel are "
"needed, got {} and {}",
nknots, channels);
return false;
}
const uint64_t needed = uint64_t(nknots) * uint64_t(channels);
if (needed != uint64_t(knots.size())) {
dst.errorfmt("color_map: {} knots of {} channels need {} values, got "
"{}",
nknots, channels, needed, knots.size());
return false;
}
if (srcchannel < -1 || srcchannel >= src.nchannels()) {
dst.errorfmt("color_map: source channel {} is not -1 (luminance) or "
"a channel of a {}-channel image",
srcchannel, src.nchannels());
return false;
}
return OIIO::ImageBufAlgo::color_map(dst, src, srcchannel, nknots,
channels, to_cspan(knots), roi,
nthreads);
}
bool
imagebufalgo_color_map_named(ImageBuf& dst, const ImageBuf& src,
int srcchannel, rust::Str mapname, const ROI& roi,
int nthreads)
{
if (src.deep()) {
dst.errorfmt("color_map: deep images are not supported");
return false;
}
if (srcchannel < -1 || srcchannel >= src.nchannels()) {
dst.errorfmt("color_map: source channel {} is not -1 (luminance) or "
"a channel of a {}-channel image",
srcchannel, src.nchannels());
return false;
}
return OIIO::ImageBufAlgo::color_map(dst, src, srcchannel,
OIIO::string_view(mapname.data(),
mapname.size()),
roi, nthreads);
}
bool
imagebufalgo_channel_sum(ImageBuf& dst, const ImageBuf& src,
rust::Slice<const float> weights, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "channel_sum"))
return false;
if (refuse_deep(dst, src, "channel_sum", "source"))
return false;
// OpenImageIO pads the weights to the DESTINATION's channel count, which
// is one, and then indexes them across the SOURCE's channels. A shorter
// slice than the source has channels is read past its end.
if (std::ptrdiff_t(weights.size()) != std::ptrdiff_t(src.nchannels())) {
dst.errorfmt("channel_sum: expected one weight per source channel, "
"got {} for {} channels",
weights.size(), src.nchannels());
return false;
}
// The result is one channel. A pre-allocated destination with a different
// count carries its own hazard: `channel_sum` clamps the ROI to the
// source's channels (`imagebufalgo_pixelmath.cpp:530` on v3.1.14.1) but
// pads the weights to the *destination's*
// (`IBA_FIX_PERCHAN_LEN(weights, dst.nchannels(), ...)`, `:537`), while
// the kernel indexes `weights[c]` across the source's range (`:513-514`).
// A source wider than the destination reads past that padded buffer.
if (dst.initialized() && !dst.deep() && dst.nchannels() != 1) {
dst.errorfmt("channel_sum: the result has one channel and the "
"destination is allocated with {}; use an empty "
"destination",
dst.nchannels());
return false;
}
return OIIO::ImageBufAlgo::channel_sum(dst, src, to_cspan(weights), roi,
nthreads);
}
bool
imagebufalgo_channels(ImageBuf& dst, const ImageBuf& src, int nchannels,
rust::Slice<const int> channelorder,
rust::Slice<const float> channelvalues,
const rust::Vec<rust::String>& newchannelnames,
bool shuffle_channel_names, int nthreads)
{
std::vector<std::string> names;
names.reserve(newchannelnames.size());
for (const rust::String& name : newchannelnames)
names.emplace_back(name.data(), name.size());
return OIIO::ImageBufAlgo::channels(
dst, src, nchannels,
OIIO::cspan<int>(channelorder.data(),
std::ptrdiff_t(channelorder.size())),
to_cspan(channelvalues),
OIIO::cspan<std::string>(names.data(), std::ptrdiff_t(names.size())),
shuffle_channel_names, nthreads);
}
CompareSummary
imagebufalgo_compare(const ImageBuf& a, const ImageBuf& b, float failthresh,
float warnthresh, float failrelative, float warnrelative,
const ROI& roi, int nthreads, rust::String& error)
{
CompareSummary refused {};
if (a.deep() != b.deep()) {
// CompareResults is a plain aggregate with no initialisers. When the
// images disagree about deepness, compare sets only `error` and
// returns, leaving every measurement indeterminate — so there is
// nothing here worth handing back.
error = rust::String::lossy(
"compare: one image is deep and the other is not");
return refused;
}
if (!a.initialized() || !b.initialized()) {
error = rust::String::lossy("compare: both images must hold pixels");
return refused;
}
a.geterror(true);
const OIIO::ImageBufAlgo::CompareResults results
= OIIO::ImageBufAlgo::compare(a, b, failthresh, warnthresh,
failrelative, warnrelative, roi,
nthreads);
if (results.error && results.nfail == 0) {
// `error` means "some values exceeded the fail threshold" on the
// normal path and "the comparison did not happen" otherwise; nfail
// tells the two apart.
std::string message = a.geterror(true);
if (message.empty())
message = "OpenImageIO could not compare these images";
error = rust::String::lossy(message);
return refused;
}
CompareSummary summary;
summary.mean_error = results.meanerror;
summary.root_mean_square_error = results.rms_error;
summary.peak_signal_to_noise_ratio = results.PSNR;
summary.max_error = results.maxerror;
summary.max_x = results.maxx;
summary.max_y = results.maxy;
summary.max_z = results.maxz;
summary.max_channel = results.maxc;
summary.warnings = uint64_t(results.nwarn);
summary.failures = uint64_t(results.nfail);
summary.failed = results.error;
return summary;
}
CompareSummary
imagebufalgo_compare_yee(const ImageBuf& a, const ImageBuf& b, float luminance,
float fov, const ROI& roi, int nthreads,
rust::String& error)
{
CompareSummary refused {};
if (a.deep() || b.deep()) {
error = rust::String::lossy(
"compare_yee: deep images are not supported");
return refused;
}
if (!a.initialized() || !b.initialized()) {
error = rust::String::lossy(
"compare_yee: both images must hold pixels");
return refused;
}
// The comparison allocates three float working copies shaped by the
// region, and reads outside either image come back as zeroes — a region
// past both images would "compare equal" over pixels neither has. An
// undefined region takes OpenImageIO's own default, the union of both.
const OIIO::ROI reach = roi_union(get_roi(a.spec()), get_roi(b.spec()));
OIIO::ROI region = roi;
if (!region.defined()) {
region = reach;
} else if (region.xbegin < reach.xbegin || region.xend > reach.xend
|| region.ybegin < reach.ybegin || region.yend > reach.yend
|| region.zbegin < reach.zbegin || region.zend > reach.zend) {
error = rust::String::lossy(
"compare_yee: the region must lie inside the images");
return refused;
}
// compare_Yee pastes the region into a depth-1 scratch, silently
// dropping every slice past the first while scanning rows for all of
// them, so a volumetric comparison would report equality it never
// measured.
if (region.zend - region.zbegin > 1) {
error = rust::String::lossy(
"compare_yee: two-dimensional images only; OpenImageIO's "
"comparison drops every slice past the first");
return refused;
}
OIIO::ImageBufAlgo::CompareResults results {};
const int failures = OIIO::ImageBufAlgo::compare_Yee(a, b, results,
luminance, fov,
region, nthreads);
CompareSummary summary {};
summary.max_error = results.maxerror;
// compare_Yee reports the worst pixel relative to the region's corner;
// every other comparison here speaks image coordinates, so translate.
summary.max_x = results.maxx + region.xbegin;
summary.max_y = results.maxy + region.ybegin;
summary.failures = uint64_t(results.nfail);
summary.failed = failures > 0;
return summary;
}
bool
imagebufalgo_color_count(const ImageBuf& src, rust::Slice<uint64_t> count,
rust::Slice<const float> color,
rust::Slice<const float> eps, const ROI& roi,
int nthreads, rust::String& error)
{
error = rust::String();
if (src.deep()) {
error = rust::String::lossy(
"color_count: deep images are not supported");
return false;
}
// Each worker counts into an OIIO_ALLOCA scratch of one long long per
// color, and a stack overflow never throws; bound it well below any
// real palette.
constexpr size_t max_colors = 32768;
if (count.empty() || count.size() > max_colors) {
error = rust::String::lossy(
"color_count: between 1 and 32768 colors, which is the bound on "
"OpenImageIO's per-thread stack scratch");
return false;
}
if (color.size() < count.size() * size_t(src.nchannels())) {
// OpenImageIO checks this too, but by recording an error on `src`;
// saying it here keeps the source's error state untouched.
error = rust::String::lossy(
"color_count: the color array must hold one value per channel "
"for every counted color");
return false;
}
src.geterror(true);
static_assert(sizeof(OIIO::imagesize_t) == sizeof(uint64_t),
"imagesize_t is the counts' type");
// Iterating a region beyond the data window would count the zeroes the
// iterator serves for pixels that do not exist.
const ROI bounded = bounded_to_source(src, roi);
const bool ok
= OIIO::ImageBufAlgo::color_count(src,
(OIIO::imagesize_t*)count.data(),
int(count.size()), to_cspan(color),
to_cspan(eps), bounded, nthreads);
if (!ok) {
std::string message = src.geterror(true);
if (message.empty())
message = "OpenImageIO could not count the colors";
error = rust::String::lossy(message);
}
return ok;
}
bool
imagebufalgo_circular_shift(ImageBuf& dst, const ImageBuf& src, int xshift,
int yshift, int zshift, const ROI& roi,
int nthreads, rust::String& error)
{
error = rust::String();
if (src.deep()) {
error = rust::String::lossy(
"circular_shift: deep images are not supported");
return false;
}
// The shift is a bijection of the region onto a destination the same
// shape, so a fresh destination is fully written; a pre-allocated one
// that outsizes the region would keep uninitialized pixels wherever the
// wrapped writes never land.
if (dst.initialized()) {
error = rust::String::lossy(
"circular_shift: use an empty destination; the result is shaped "
"by the region");
return false;
}
dst.geterror(true);
const bool ok = OIIO::ImageBufAlgo::circular_shift(dst, src, xshift,
yshift, zshift, roi,
nthreads);
if (!ok || dst.has_error()) {
std::string recorded = dst.geterror(true);
if (recorded.empty())
recorded = "OpenImageIO could not shift the image";
error = rust::String::lossy(recorded);
return false;
}
return true;
}
bool
imagebufalgo_fill_vertical(ImageBuf& dst, rust::Slice<const float> top,
rust::Slice<const float> bottom, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::fill(dst, to_cspan(top), to_cspan(bottom), roi,
nthreads);
}
bool
imagebufalgo_fill_corners(ImageBuf& dst, rust::Slice<const float> topleft,
rust::Slice<const float> topright,
rust::Slice<const float> bottomleft,
rust::Slice<const float> bottomright, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::fill(dst, to_cspan(topleft), to_cspan(topright),
to_cspan(bottomleft),
to_cspan(bottomright), roi, nthreads);
}
bool
imagebufalgo_checker(ImageBuf& dst, int width, int height, int depth,
rust::Slice<const float> color1,
rust::Slice<const float> color2, int xoffset, int yoffset,
int zoffset, const ROI& roi, int nthreads)
{
if (width < 1 || height < 1 || depth < 1) {
// These divide the coordinate, and nothing upstream checks them.
dst.errorfmt("checker: every square dimension must be at least 1, got "
"{}x{}x{}",
width, height, depth);
return false;
}
return OIIO::ImageBufAlgo::checker(dst, width, height, depth,
to_cspan(color1), to_cspan(color2),
xoffset, yoffset, zoffset, roi,
nthreads);
}
bool
imagebufalgo_noise(ImageBuf& dst, const rust::Str noisetype, float a, float b,
bool mono, int seed, const ROI& roi, int nthreads)
{
return OIIO::ImageBufAlgo::noise(dst, to_string_view(noisetype), a, b, mono,
seed, roi, nthreads);
}
bool
imagebufalgo_render_point(ImageBuf& dst, int x, int y,
rust::Slice<const float> color, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::render_point(dst, x, y, to_cspan(color), roi,
nthreads);
}
bool
imagebufalgo_render_line(ImageBuf& dst, int x1, int y1, int x2, int y2,
rust::Slice<const float> color, bool skip_first_point,
const ROI& roi, int nthreads)
{
return OIIO::ImageBufAlgo::render_line(dst, x1, y1, x2, y2, to_cspan(color),
skip_first_point, roi, nthreads);
}
bool
imagebufalgo_render_box(ImageBuf& dst, int x1, int y1, int x2, int y2,
rust::Slice<const float> color, bool fill,
const ROI& roi, int nthreads)
{
if (fill && (x2 < x1 || y2 < y1)) {
// The filled path intersects an empty region and draws nothing, while
// reporting success. The outline path accepts either corner order, so
// only this one needs saying.
dst.errorfmt("render_box: a filled box needs its first corner above "
"and left of its second, got {},{} to {},{}",
x1, y1, x2, y2);
return false;
}
return OIIO::ImageBufAlgo::render_box(dst, x1, y1, x2, y2, to_cspan(color),
fill, roi, nthreads);
}
namespace {
// Every glyph failing to rasterise leaves the measured box at its initial
// xbegin = ybegin = INT_MAX, xend = yend = INT_MIN. render_text builds an
// ImageSpec from that without clamping, and the width underflows.
bool
text_renders_something(const rust::Str text)
{
for (std::size_t i = 0; i < text.size(); ++i) {
const char c = text.data()[i];
if (c != '\n' && c != '\r' && c != '\0')
return true;
}
return false;
}
} // namespace
bool
imagebufalgo_render_text(ImageBuf& dst, int x, int y, const rust::Str text,
int fontsize, const rust::Str fontname,
rust::Slice<const float> color, int alignx, int aligny,
int shadow, const ROI& roi, int nthreads)
{
if (!text_renders_something(text)) {
dst.errorfmt("render_text: there is nothing to draw; OpenImageIO "
"measures an inverted box for text with no glyphs and "
"builds an image from it");
return false;
}
if (fontsize < 1) {
dst.errorfmt("render_text: the font size must be at least 1, got {}",
fontsize);
return false;
}
return OIIO::ImageBufAlgo::render_text(
dst, x, y, to_string_view(text), fontsize, to_string_view(fontname),
to_cspan(color), OIIO::ImageBufAlgo::TextAlignX(alignx),
OIIO::ImageBufAlgo::TextAlignY(aligny), shadow, roi, nthreads);
}
ROI
imagebufalgo_text_size(const rust::Str text, int fontsize,
const rust::Str fontname)
{
if (!text_renders_something(text) || fontsize < 1)
return ROI();
ROI measured = OIIO::ImageBufAlgo::text_size(to_string_view(text), fontsize,
to_string_view(fontname));
if (!measured.defined())
return measured;
// text_size measures x and y and leaves the rest of the region at its
// default, so z and the channels come back as empty 0..0 ranges. Text is
// two-dimensional and single-channel; render_text applies exactly this
// fixup to the same measurement before using it.
measured.zbegin = 0;
measured.zend = 1;
measured.chbegin = 0;
measured.chend = 1;
return measured;
}
bool
imagebufalgo_flatten(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "flatten"))
return false;
if (dst.initialized() && dst.nchannels() > src.nchannels()) {
// The kernel allocates its accumulator with src.nchannels() floats and
// then writes up to roi.chend, which IBAprep clamps only to the larger
// of the two buffers. A wider destination reads stack past the end of
// that allocation.
dst.errorfmt("flatten: the destination has {} channels and the source "
"has {}; OpenImageIO reads past its own accumulator when "
"the destination is wider",
dst.nchannels(), src.nchannels());
return false;
}
return OIIO::ImageBufAlgo::flatten(dst, src, roi, nthreads);
}
bool
imagebufalgo_deepen(ImageBuf& dst, const ImageBuf& src, float zvalue,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "deepen"))
return false;
if (dst.initialized()) {
// Only an uninitialized destination gets the deep, float specification
// deepen builds. Into a pre-allocated one, writes to channels it does
// not have are dropped without a word.
dst.errorfmt("deepen: the destination must be empty, so it can take "
"the deep specification this builds");
return false;
}
return OIIO::ImageBufAlgo::deepen(dst, src, zvalue, roi, nthreads);
}
bool
imagebufalgo_deep_merge(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
bool occlusion_cull, const ROI& roi, int nthreads)
{
if (require_deep(dst, a, "deep_merge", "first image")
|| require_deep(dst, b, "deep_merge", "second image")
|| refuse_flat_destination(dst, "deep_merge")
|| refuse_empty_region(dst, a, roi, "deep_merge"))
return false;
return OIIO::ImageBufAlgo::deep_merge(dst, a, b, occlusion_cull, roi,
nthreads);
}
bool
imagebufalgo_deep_holdout(ImageBuf& dst, const ImageBuf& src,
const ImageBuf& holdout, const ROI& roi, int nthreads)
{
if (require_deep(dst, src, "deep_holdout", "source")
|| require_deep(dst, holdout, "deep_holdout", "holdout")
|| refuse_flat_destination(dst, "deep_holdout")
|| refuse_empty_region(dst, src, roi, "deep_holdout"))
return false;
return OIIO::ImageBufAlgo::deep_holdout(dst, src, holdout, roi, nthreads);
}
// The binomial branch of make_kernel sizes its tap arrays from the raw float
// extent and then indexes them over the odd-rounded image size. In
// `imagebufalgo.cpp` the size is `w = std::max(1, (int)ceilf(width)) | 1`,
// while the taps are `OIIO_ALLOCA(float, width)` filled by `i < width`, and
// the consuming loop reads `wfilter[p.x() - spec.x]` for `p.x() - spec.x` in
// `[0, w)`. For an even width the last tap is read past the end of the
// allocation; for a fractional one the fill itself writes past it.
//
// This is not cosmetic. Across six runs of `make_kernel("binomial", 4, 4)`
// here, three returned a kernel of NaN, one was numerically zero, and two
// were correct, because the value read is whatever the stack held. A NaN
// kernel poisons every pixel of whatever it convolves, and the caller is
// given no error.
//
// Odd integer extents are the case where the allocation and the loop agree,
// so they are the case this accepts.
// The one extent shape where the allocation and the consuming loop agree.
static bool
binomial_extent_is_safe(float extent)
{
return extent >= 1.0f && extent == std::floor(extent)
&& std::fmod(extent, 2.0f) == 1.0f;
}
static bool
is_binomial(const rust::Str name)
{
return OIIO::Strutil::iequals(to_string_view(name), "binomial");
}
static bool
refuse_unsafe_binomial_kernel(ImageBuf& dst, const rust::Str name, float width,
float height)
{
if (!is_binomial(name)
|| (binomial_extent_is_safe(width) && binomial_extent_is_safe(height)))
return false;
dst.errorfmt(
"make_kernel: a binomial kernel needs odd whole width and height, "
"and was asked for {} by {}; OpenImageIO sizes the taps from the "
"extent given and then indexes them over the next odd size, so an "
"even or fractional one reads past its own allocation and can return "
"a kernel of NaN",
width, height);
return true;
}
bool
imagebufalgo_make_kernel(ImageBuf& dst, const rust::Str name, float width,
float height, float depth, bool normalize)
{
if (refuse_unsafe_binomial_kernel(dst, name, width, height))
return false;
dst = OIIO::ImageBufAlgo::make_kernel(to_string_view(name), width, height,
depth, normalize);
// An unrecognised filter name still yields a box kernel, with the
// complaint left on the buffer. Convolving with a silent substitute would
// be worse than reporting it.
return !dst.has_error();
}
bool
imagebufalgo_convolve(ImageBuf& dst, const ImageBuf& src,
const ImageBuf& kernel, bool normalize, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "convolve"))
return false;
if (!kernel.initialized() || kernel.roi().npixels() == 0
|| kernel.nchannels() < 1) {
// Otherwise the kernel sum stays zero, normalising divides by it, and
// every pixel comes back NaN with the call reporting success.
dst.errorfmt("convolve: the kernel is empty");
return false;
}
// The kernel is a third image, so IBAprep never sees it.
if (refuse_deep(dst, kernel, "convolve", "kernel"))
return false;
return OIIO::ImageBufAlgo::convolve(dst, src, kernel, normalize, roi,
nthreads);
}
bool
imagebufalgo_laplacian(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "laplacian"))
return false;
return OIIO::ImageBufAlgo::laplacian(dst, src, roi, nthreads);
}
bool
imagebufalgo_unsharp_mask(ImageBuf& dst, const ImageBuf& src,
const rust::Str kernel, float width, float contrast,
float threshold, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "unsharp_mask"))
return false;
if (refuse_narrow_destination(dst, src, "unsharp_mask"))
return false;
// unsharp_mask builds its blur kernel by calling make_kernel with the
// name and width given: `make_kernel(kernel, 1, width)` above a width of
// three, `make_kernel(kernel, width, width)` at or below it. Either way
// the width reaches the binomial branch as an extent, so the same
// allocation defect applies and the same rule has to hold here.
if (is_binomial(kernel) && !binomial_extent_is_safe(width)) {
dst.errorfmt(
"unsharp_mask: a binomial kernel needs an odd whole width, and "
"was asked for {}; OpenImageIO sizes the taps from the width "
"given and then indexes them over the next odd size, so an even "
"or fractional one reads past its own allocation and can blur "
"with a kernel of NaN",
width);
return false;
}
if (dst.initialized() && dst.spec().format != src.spec().format) {
// The final pass dispatches on the destination's type and then reads
// the source through an iterator of that same type. ImageBuf iterators
// reinterpret the buffer rather than converting, so a mismatch misreads
// the source, and reads past its end when the destination is wider.
dst.errorfmt("unsharp_mask: the destination is {} and the source is "
"{}; OpenImageIO reads the source as the destination's "
"type, so they must match, or pass an empty destination",
dst.spec().format, src.spec().format);
return false;
}
return OIIO::ImageBufAlgo::unsharp_mask(dst, src, to_string_view(kernel),
width, contrast, threshold, roi,
nthreads);
}
namespace {
// A width of one gives w_2 = max(1, 0) = 1, so the window is [x-1, x): one
// pixel, one to the left. The image comes back translated rather than
// unchanged, which no caller asking for a 1-pixel filter wants.
bool
check_window(ImageBuf& dst, const char* operation, int width, int height)
{
if (width < 2) {
dst.errorfmt("{}: the window must be at least 2 wide, got {}; "
"OpenImageIO translates the image by one pixel for 1",
operation, width);
return false;
}
if (height > 0 && height < 2) {
dst.errorfmt("{}: the window must be at least 2 high, got {}; "
"pass 0 or -1 to match the width",
operation, height);
return false;
}
return true;
}
// dilate and erode leave -FLT_MAX or +FLT_MAX in any destination pixel that
// had no source pixel under it, and report success. Keeping the region inside
// the source's data window means that case cannot arise.
ROI
within_source(const ImageBuf& src, const ROI& roi)
{
if (!roi.defined())
return src.roi();
return OIIO::roi_intersection(roi, src.roi());
}
} // namespace
bool
imagebufalgo_median_filter(ImageBuf& dst, const ImageBuf& src, int width,
int height, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "median_filter"))
return false;
if (!check_window(dst, "median_filter", width, height))
return false;
return OIIO::ImageBufAlgo::median_filter(dst, src, width, height, roi,
nthreads);
}
bool
imagebufalgo_dilate(ImageBuf& dst, const ImageBuf& src, int width, int height,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "dilate"))
return false;
if (!check_window(dst, "dilate", width, height))
return false;
return OIIO::ImageBufAlgo::dilate(dst, src, width, height,
within_source(src, roi), nthreads);
}
bool
imagebufalgo_erode(ImageBuf& dst, const ImageBuf& src, int width, int height,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "erode"))
return false;
if (!check_window(dst, "erode", width, height))
return false;
return OIIO::ImageBufAlgo::erode(dst, src, width, height,
within_source(src, roi), nthreads);
}
bool
imagebufalgo_fft(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
// fft never calls IBAprep; it goes straight to paste, which walks the
// source's pixels, and then to hfft_, whose assertions a release build
// compiles away.
if (refuse_deep(dst, src, "fft", "source"))
return false;
if (!src.initialized() || src.roi().npixels() == 0) {
dst.errorfmt("fft: the source holds no pixels to transform");
return false;
}
// fft transforms the union of the data and display windows, allocating a
// complex buffer that size. Those two windows are independent — moving a
// data window without moving the display window leaves them far apart —
// and the union of two distant windows spans everything between. A 10x3
// image whose data window sits at 100000,100000 with its display window
// still at the origin asks for 100010 x 100003 pixels: the allocation
// fails, and OpenImageIO then zeroes a buffer it never got, which takes
// the process down.
//
// Zero-padding out to a display window a few times the data window is
// ordinary; a union orders of magnitude larger is two windows that
// disagree, not padding.
const ROI transformed = OIIO::roi_union(src.roi(), src.roi_full());
const OIIO::imagesize_t held = src.roi().npixels();
const OIIO::imagesize_t requested = transformed.npixels();
if (requested > held * 16 + 1024) {
dst.errorfmt(
"fft: the source's pixels span {},{} to {},{} but its display "
"window spans {},{} to {},{}, so the transform would cover {} "
"pixels for an image holding {}. Crop the source, or give it a "
"display window near its pixels",
src.roi().xbegin, src.roi().ybegin, src.roi().xend, src.roi().yend,
src.roi_full().xbegin, src.roi_full().ybegin, src.roi_full().xend,
src.roi_full().yend, requested, held);
return false;
}
return OIIO::ImageBufAlgo::fft(dst, src, roi, nthreads);
}
bool
imagebufalgo_ifft(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_deep(dst, src, "ifft", "source"))
return false;
if (!src.initialized() || src.roi().npixels() == 0) {
dst.errorfmt("ifft: the source holds no pixels to transform");
return false;
}
if (!src.localpixels()) {
// hfft_ casts src.pixeladdr(...) to a complex pointer behind an
// assertion that a release build compiles out. A cache-backed buffer
// answers that address with null.
dst.errorfmt("ifft: the source's pixels are not in memory; read the "
"image before transforming it");
return false;
}
// Being in memory is not enough. ifft transforms the union of the source's
// data and display windows, allocates its working buffer at the origin
// with that size, and then reads the SOURCE at those same coordinates —
// hfft_'s own assertion says dst.roi() == src.roi(), and nothing enforces
// it. So a data window that does not start at the origin, or that is
// smaller than the display window, walks off the allocation: the first
// crashes, the second quietly returns heap contents as pixels. An overscan
// EXR is exactly the second shape, and so is anything algo::crop produced.
const ROI transformed = OIIO::roi_union(src.roi(), src.roi_full());
if (src.spec().x != 0 || src.spec().y != 0 || src.spec().z != 0
|| !src.roi().contains(transformed)) {
dst.errorfmt(
"ifft: the source's pixels must start at the origin and cover its "
"display window. This one holds {},{} to {},{} with a display "
"window of {},{} to {},{}; OpenImageIO would read outside it",
src.roi().xbegin, src.roi().ybegin, src.roi().xend, src.roi().yend,
src.roi_full().xbegin, src.roi_full().ybegin, src.roi_full().xend,
src.roi_full().yend);
return false;
}
return OIIO::ImageBufAlgo::ifft(dst, src, roi, nthreads);
}
bool
imagebufalgo_polar_to_complex(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "polar_to_complex"))
return false;
return OIIO::ImageBufAlgo::polar_to_complex(dst, src, roi, nthreads);
}
bool
imagebufalgo_complex_to_polar(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "complex_to_polar"))
return false;
return OIIO::ImageBufAlgo::complex_to_polar(dst, src, roi, nthreads);
}
bool
imagebufalgo_rotate90(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rotate90")
|| refuse_wide_region(dst, src, roi, "rotate90"))
return false;
return OIIO::ImageBufAlgo::rotate90(dst, src, roi, nthreads);
}
bool
imagebufalgo_rotate180(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rotate180")
|| refuse_wide_region(dst, src, roi, "rotate180"))
return false;
return OIIO::ImageBufAlgo::rotate180(dst, src, roi, nthreads);
}
bool
imagebufalgo_rotate270(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rotate270")
|| refuse_wide_region(dst, src, roi, "rotate270"))
return false;
return OIIO::ImageBufAlgo::rotate270(dst, src, roi, nthreads);
}
bool
imagebufalgo_reorient(ImageBuf& dst, const ImageBuf& src, int nthreads)
{
const bool succeeded = OIIO::ImageBufAlgo::reorient(dst, src, nthreads);
if (!succeeded && !dst.has_error()) {
// reorient's switch has no default arm, so an Orientation outside 1..8
// leaves dst untouched and records nothing. Say what happened rather
// than returning an empty error.
dst.errorfmt("reorient: the source's Orientation is {}, which is not "
"one of the eight EXIF orientations",
src.orientation());
}
return succeeded;
}
bool
imagebufalgo_rotate(ImageBuf& dst, const ImageBuf& src, float angle,
bool has_center, float center_x, float center_y,
const rust::Str filtername, float filterwidth,
bool recompute_roi, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "rotate"))
return false;
if (refuse_narrow_destination(dst, src, "rotate"))
return false;
if (!has_center)
return OIIO::ImageBufAlgo::rotate(dst, src, angle,
to_string_view(filtername),
filterwidth, recompute_roi, roi,
nthreads);
return OIIO::ImageBufAlgo::rotate(dst, src, angle, center_x, center_y,
to_string_view(filtername), filterwidth,
recompute_roi, roi, nthreads);
}
bool
imagebufalgo_warp(ImageBuf& dst, const ImageBuf& src,
rust::Slice<const float> matrix, const rust::Str filtername,
float filterwidth, const rust::Str wrap, bool edgeclamp,
bool recompute_roi, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "warp"))
return false;
if (matrix.size() != 9) {
dst.errorfmt("warp: the transform needs nine values, got {}",
matrix.size());
return false;
}
if (refuse_narrow_destination(dst, src, "warp"))
return false;
float m[3][3];
for (std::size_t row = 0; row < 3; ++row)
for (std::size_t column = 0; column < 3; ++column)
m[row][column] = matrix[row * 3 + column];
// Only names OpenImageIO recognises are sent: IBA_check_optional's report
// of an unknown one is discarded upstream, so a typo would be silent.
OIIO::ParamValueList options;
if (filtername.size() != 0)
options["filtername"] = std::string(to_string_view(filtername));
if (filterwidth > 0.0f)
options["filterwidth"] = filterwidth;
if (wrap.size() != 0)
options["wrap"] = std::string(to_string_view(wrap));
options["edgeclamp"] = int(edgeclamp);
options["recompute_roi"] = int(recompute_roi);
return OIIO::ImageBufAlgo::warp(dst, src, m, options, roi, nthreads);
}
bool
imagebufalgo_st_warp(ImageBuf& dst, const ImageBuf& src, const ImageBuf& stbuf,
const rust::Str filtername, float filterwidth, int chan_s,
int chan_t, bool flip_s, bool flip_t, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "st_warp"))
return false;
// OpenImageIO checks these against stbuf's channel count but never against
// zero, and a negative index reads out of bounds. The safe wrapper takes
// them as unsigned, so this is the belt to that braces.
if (chan_s < 0 || chan_t < 0) {
dst.errorfmt("st_warp: channel indices must not be negative, got "
"{} and {}",
chan_s, chan_t);
return false;
}
// stbuf is a third image, so IBAprep never sees it.
if (refuse_deep(dst, stbuf, "st_warp", "coordinate map"))
return false;
// warp clamps its region to the source before IBAprep; st_warp does not,
// and deliberately restores the channel range IBAprep chose, so the
// destination's width is what the sampler accumulates over.
if (refuse_wide_destination(dst, src, "st_warp"))
return false;
return OIIO::ImageBufAlgo::st_warp(dst, src, stbuf,
to_string_view(filtername), filterwidth,
chan_s, chan_t, flip_s, flip_t, roi,
nthreads);
}
// Every `mad` variant needs TWO channel guards, and they answer different
// questions. `refuse_channel_mismatch` compares the image operands against
// each other, because a*b+c reads each of them over the union width.
// `refuse_wide_destination` compares the destination against operand `a`,
// because the kernel takes its channel range from the DESTINATION: a
// pre-allocated destination wider than the operands makes it read past each
// operand's pixel and, at the end of the buffer, past the allocation. Only the
// first was here, so a two-channel operand into a six-channel destination
// passed the guard and came back holding 12, 20, 30 and 42 in the channels the
// operands do not have, which is a*b+c computed on the NEXT pixel's values.
// `copy` has carried the destination check inline since 0.2.0; this is the same
// check, and `mad` is the same defect reached through another kernel.
//
// Found by tests/wide_destination_test.rs, which exists for this class.
bool
imagebufalgo_mad_iii(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ImageBuf& c, const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "mad")
|| refuse_deep_mismatch(dst, a, b, "mad")
|| refuse_channel_mismatch(dst, a, b, "mad")
// a*b+c reads every image operand to the union channel count, so c has
// to line up too, not only a and b.
|| refuse_channel_mismatch(dst, a, c, "mad")
|| refuse_wide_destination(dst, a, "mad"))
return false;
return OIIO::ImageBufAlgo::mad(dst, a, b, c, roi, nthreads);
}
bool
imagebufalgo_mad_iic(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
rust::Slice<const float> c, const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "mad")
|| refuse_deep_mismatch(dst, a, b, "mad")
|| refuse_channel_mismatch(dst, a, b, "mad")
|| refuse_wide_destination(dst, a, "mad"))
return false;
return OIIO::ImageBufAlgo::mad(dst, a, b, to_cspan(c), roi, nthreads);
}
bool
imagebufalgo_mad_ici(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> b, const ImageBuf& c,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, c, "mad")
|| refuse_deep_mismatch(dst, a, c, "mad")
// b is a constant; a and c are both images and must line up.
|| refuse_channel_mismatch(dst, a, c, "mad")
|| refuse_wide_destination(dst, a, "mad"))
return false;
return OIIO::ImageBufAlgo::mad(dst, a, to_cspan(b), c, roi, nthreads);
}
bool
imagebufalgo_mad_icc(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> b, rust::Slice<const float> c,
const ROI& roi, int nthreads)
{
// One image operand, so there is nothing to line up against it, but the
// destination's width still drives the kernel.
if (refuse_wide_destination(dst, a, "mad"))
return false;
return OIIO::ImageBufAlgo::mad(dst, a, to_cspan(b), to_cspan(c), roi,
nthreads);
}
bool
imagebufalgo_invert(ImageBuf& dst, const ImageBuf& a, const ROI& roi,
int nthreads)
{
// IBAprep widens an undefined region to the destination's whole window,
// chend included, and the kernel then indexes the source with it. See
// refuse_wide_region above for why these four need the destination guard
// and the mirrors and rotations need the region one.
if (refuse_empty_region(dst, a, roi, "invert")
|| refuse_wide_destination(dst, a, "invert"))
return false;
return OIIO::ImageBufAlgo::invert(dst, a, roi, nthreads);
}
bool
imagebufalgo_pow(ImageBuf& dst, const ImageBuf& a, rust::Slice<const float> b,
const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, a, roi, "pow"))
return false;
return OIIO::ImageBufAlgo::pow(dst, a, to_cspan(b), roi, nthreads);
}
bool
imagebufalgo_clamp(ImageBuf& dst, const ImageBuf& src,
rust::Slice<const float> min, rust::Slice<const float> max,
bool clampalpha01, const ROI& roi, int nthreads)
{
// IBAprep widens an undefined region to the destination's whole window,
// chend included, and the kernel then indexes the source with it. See
// refuse_wide_region above for why these four need the destination guard
// and the mirrors and rotations need the region one.
if (refuse_empty_region(dst, src, roi, "clamp")
|| refuse_wide_destination(dst, src, "clamp"))
return false;
return OIIO::ImageBufAlgo::clamp(dst, src, to_cspan(min), to_cspan(max),
clampalpha01, roi, nthreads);
}
bool
imagebufalgo_min_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "min")
|| refuse_deep_mismatch(dst, a, b, "min"))
return false;
return OIIO::ImageBufAlgo::min(dst, a, b, roi, nthreads);
}
bool
imagebufalgo_min_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
return OIIO::ImageBufAlgo::min(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_max_images(ImageBuf& dst, const ImageBuf& a, const ImageBuf& b,
const ROI& roi, int nthreads)
{
if (refuse_distant_pair(dst, a, b, "max")
|| refuse_deep_mismatch(dst, a, b, "max"))
return false;
// OpenImageIO's image/image max is not memory-safe when the channel counts
// disagree. imagebufalgo_pixelmath.cpp:169 reads
//
// roi.chend = std::max(roi.chend, std::max(A.nchannels(), B.nchannels()));
//
// where min at line 72 uses std::min twice. The widening is unconditional,
// so no ROI a caller supplies can prevent it, and it happens after IBAprep
// has clamped the range to what the buffers actually hold. The kernel then
// reads a[c] and b[c] past the shorter input, and writes r[c] past dst if
// dst has fewer channels than the inputs; ImageBuf's iterators do no
// bounds checking. max's own OIIO_ASSERT(roi.chend <= dst.nchannels()),
// in the now-unreachable block below the dispatch, records the intent that
// was lost. Present in 3.1.9 and still in 3.2.0.2dev.
//
// So refuse exactly the shapes that would run off the end, and clamp the
// channel range so the widening is a no-op. min needs none of this.
if (a.nchannels() != b.nchannels()) {
dst.errorfmt(
"max: the two images must have the same number of channels, got "
"{} and {} (OpenImageIO's max reads out of bounds otherwise)",
a.nchannels(), b.nchannels());
return false;
}
if (dst.initialized() && dst.nchannels() < a.nchannels()) {
dst.errorfmt(
"max: the destination has {} channels but the sources have {} "
"(OpenImageIO's max writes out of bounds otherwise)",
dst.nchannels(), a.nchannels());
return false;
}
ROI bounded = roi;
if (!bounded.defined())
bounded = OIIO::roi_union(a.roi(), b.roi());
bounded.chbegin = std::max(bounded.chbegin, 0);
bounded.chend = std::min(bounded.chend, a.nchannels());
return OIIO::ImageBufAlgo::max(dst, a, b, bounded, nthreads);
}
bool
imagebufalgo_max_constant(ImageBuf& dst, const ImageBuf& a,
rust::Slice<const float> values, const ROI& roi,
int nthreads)
{
// The image/constant path is the correct mirror of min's and needs no
// guard: it goes through IBAprep_CLAMP_MUTUAL_NCHANNELS.
return OIIO::ImageBufAlgo::max(dst, a, to_cspan(values), roi, nthreads);
}
bool
imagebufalgo_contrast_remap(ImageBuf& dst, const ImageBuf& src,
rust::Slice<const float> black,
rust::Slice<const float> white,
rust::Slice<const float> min,
rust::Slice<const float> max,
rust::Slice<const float> scontrast,
rust::Slice<const float> sthresh, const ROI& roi,
int nthreads)
{
// IBAprep widens an undefined region to the destination's whole window,
// chend included, and the kernel then indexes the source with it. See
// refuse_wide_region above for why these four need the destination guard
// and the mirrors and rotations need the region one.
if (refuse_empty_region(dst, src, roi, "contrast_remap")
|| refuse_wide_destination(dst, src, "contrast_remap"))
return false;
return OIIO::ImageBufAlgo::contrast_remap(dst, src, to_cspan(black),
to_cspan(white), to_cspan(min),
to_cspan(max),
to_cspan(scontrast),
to_cspan(sthresh), roi, nthreads);
}
bool
imagebufalgo_saturate(ImageBuf& dst, const ImageBuf& src, float scale,
int firstchannel, const ROI& roi, int nthreads)
{
if (refuse_empty_region(dst, src, roi, "saturate"))
return false;
return OIIO::ImageBufAlgo::saturate(dst, src, scale, firstchannel, roi,
nthreads);
}
bool
imagebufalgo_paste(ImageBuf& dst, int xbegin, int ybegin, int zbegin,
int chbegin, const ImageBuf& src, const ROI& srcroi,
int nthreads)
{
if (refuse_mixed_deep(dst, src, "paste"))
return false;
// chbegin offsets the source's channels into the destination and is not
// clamped anywhere. Far enough negative and the destination's channel
// count goes negative too, at which point IBAprep hands it to
// default_channel_names(), which is noexcept and reserves that many:
// std::terminate, with nothing printed.
const ROI source = srcroi.defined() ? srcroi : src.roi();
if (chbegin + source.chend <= 0) {
dst.errorfmt("paste: a first channel of {} leaves the source's {} "
"channels entirely outside the destination",
chbegin, source.nchannels());
return false;
}
ROI effective = srcroi;
// Everything below is the deep path, which never goes through IBAprep.
// ImageBufAlgo::paste sends a deep source to deep_paste_
// (imagebufalgo_copy.cpp:56) and that function substitutes
// dst.reset(src.spec()) for the IBAprep call. Three separate things
// follow from the substitution and all three are reported as success.
if (src.deep()) {
// The region the caller asked the source to land on, computed the
// way ImageBufAlgo::paste computes it.
const ROI target(source.xbegin + xbegin,
source.xbegin + xbegin + source.width(),
source.ybegin + ybegin,
source.ybegin + ybegin + source.height(),
source.zbegin + zbegin,
source.zbegin + zbegin + source.depth(),
source.chbegin, source.chend);
// One. deep_paste_ never reads the channel part of dstroi, so chbegin
// is dropped. A flat paste with a first channel of 2 widens the
// destination to seven channels and puts the source at channel 2; a
// deep one returns five channels with the source at channel 0 and
// says it worked. There is nothing to pass on here, so this refuses.
if (srcroi.defined()
&& (srcroi.chbegin != 0 || srcroi.chend < src.nchannels())) {
dst.errorfmt("paste: OpenImageIO's deep path copies whole pixels, "
"so a source channel range of {}..{} out of {} "
"cannot be honored; paste every channel and select "
"afterwards with channels",
srcroi.chbegin, srcroi.chend, src.nchannels());
return false;
}
if (chbegin != 0) {
dst.errorfmt("paste: OpenImageIO's deep path ignores the first "
"channel, so a value of {} would be dropped without "
"being reported; paste at channel zero and move the "
"channels afterwards with channels or channel_append",
chbegin);
return false;
}
// Two. The reset takes the source's window, so the destination region
// is gone before a sample is written. deep_paste_ then writes at
// x + (dstroi.xbegin - srcroi.xbegin) through
// ImageBuf::set_deep_samples and ImageBuf::copy_deep_pixel, and both
// of those call pixelindex() with check_range defaulting to false. A
// coordinate outside the destination is not clipped, it gets a linear
// index that wraps into the next scanline: an 8x8 source pasted at
// x=10 into an empty destination comes back shifted one row and two
// columns, with the writes that ran off the end dropped by
// DeepData::set_samples and its own bounds test. 128 samples became
// 108. The flat path has none of this, because paste_ iterates and
// tests d.exists().
//
// Sizing an uninitialized destination from the destination region is
// what IBAprep does for the flat path (imagebufalgo.cpp:229,
// set_roi(spec, roi)), so this makes the two agree rather than
// inventing a third behaviour. At an offset of zero it is the same
// reset OpenImageIO would have done.
//
// Three. deep_paste_ opens with
// OIIO_ASSERT(dst.deep() && src.deep()) and only twelve lines later
// handles an uninitialized destination itself, so it asserts against
// the one shape it goes on to support. Where OIIO_ASSERT is live,
// which is how conda-forge builds OpenImageIO, every such paste
// prints one: 25 in a single CI run that reported success throughout.
// Doing the reset here leaves the assertion looking at the deep
// destination it expects.
if (!dst.initialized()) {
// Both windows take the destination region, which is what
// IBAprep does for the flat path (imagebufalgo.cpp:252, :233) and
// what upstream's own fix does. The tile dimensions are cleared
// for the same reason: a tiled source would otherwise hand back a
// tiled destination that the flat path never produces.
ImageSpec spec = src.spec();
OIIO::set_roi(spec, target);
OIIO::set_roi_full(spec, target);
spec.tile_width = 0;
spec.tile_height = 0;
spec.tile_depth = 0;
dst.reset(spec);
} else {
// An allocated destination cannot be resized, so the source
// region is narrowed until what lands is inside it. That is both
// the flat path's behaviour and what this call documents: pixels
// outside the destination are dropped.
const ROI landed = OIIO::roi_intersection(target, dst.roi());
if (landed.xend <= landed.xbegin || landed.yend <= landed.ybegin
|| landed.zend <= landed.zbegin) {
// Nothing overlaps, so nothing is pasted. This returns true
// rather than an error because the flat path does: paste_
// iterates and every destination pixel fails d.exists(), so
// the call succeeds having copied nothing. Refusing here
// would make a deep paste stricter than a flat one for the
// same arguments, and stricter than the library once
// upstream's fix ships.
return true;
}
effective = ROI(landed.xbegin - xbegin, landed.xend - xbegin,
landed.ybegin - ybegin, landed.yend - ybegin,
landed.zbegin - zbegin, landed.zend - zbegin,
source.chbegin, source.chend);
}
}
if (!OIIO::ImageBufAlgo::paste(dst, xbegin, ybegin, zbegin, chbegin, src,
effective, nthreads))
return false;
if (!dst.initialized()) {
// OpenImageIO can leave the destination unallocated and still report
// success, having recorded its complaint through an assertion rather
// than an error.
dst.errorfmt("paste: the destination could not be sized from a first "
"channel of {}",
chbegin);
return false;
}
return true;
}
bool
imagebufalgo_cut(ImageBuf& dst, const ImageBuf& src, const ROI& roi,
int nthreads)
{
if (refuse_empty_region(dst, src, roi, "cut"))
return false;
return OIIO::ImageBufAlgo::cut(dst, src, roi, nthreads);
}
bool
imagebufalgo_make_texture_from_buffer(int32_t mode, const ImageBuf& input,
const rust::Str outputfilename,
const ImageSpec& config,
rust::String& error)
{
OIIO::ImageBufAlgo::MakeTextureMode texture_mode;
if (!to_texture_mode(mode, texture_mode)) {
error = rust::String::lossy("unknown make_texture mode");
return false;
}
std::ostringstream printed;
const bool succeeded
= OIIO::ImageBufAlgo::make_texture(texture_mode, input,
std::string(to_string_view(
outputfilename)),
config, &printed);
if (!succeeded)
collect_texture_failure(printed, error);
return succeeded;
}
bool
imagebufalgo_make_texture_from_file(int32_t mode, const rust::Str filename,
const rust::Str outputfilename,
const ImageSpec& config,
rust::String& error)
{
OIIO::ImageBufAlgo::MakeTextureMode texture_mode;
if (!to_texture_mode(mode, texture_mode)) {
error = rust::String::lossy("unknown make_texture mode");
return false;
}
std::ostringstream printed;
const bool succeeded
= OIIO::ImageBufAlgo::make_texture(texture_mode,
std::string(
to_string_view(filename)),
std::string(to_string_view(
outputfilename)),
config, &printed);
if (!succeeded)
collect_texture_failure(printed, error);
return succeeded;
}
} // namespace oiio