oiio 0.3.2

High-level OpenImageIO bindings over oiio-sys
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
use std::path::Path;

use crate::imageio::validate_buffer_len;
use crate::{path_to_utf8, pixel, sys, Error, ImageSpec, Pixel, PixelFormat, Result, Roi};

/// What a point read outside the data window answers with.
///
/// A closed set on purpose: OpenImageIO's iterator dispatches on the wrap
/// mode through a table whose out-of-range entries are unchecked in release
/// builds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wrap {
    /// Black, which is OpenImageIO's default.
    Default,
    /// Zero for every channel.
    Black,
    /// The nearest edge pixel.
    Clamp,
    /// The image tiled over the plane. Needs a display window with positive
    /// size, whose dimensions the coordinate is folded by.
    Periodic,
    /// The image reflected at each edge. Needs a positive display window
    /// too.
    Mirror,
}

impl Wrap {
    fn to_sys(self) -> sys::imagebuf::WrapMode {
        match self {
            Self::Default => sys::imagebuf::WrapMode::WrapDefault,
            Self::Black => sys::imagebuf::WrapMode::WrapBlack,
            Self::Clamp => sys::imagebuf::WrapMode::WrapClamp,
            Self::Periodic => sys::imagebuf::WrapMode::WrapPeriodic,
            Self::Mirror => sys::imagebuf::WrapMode::WrapMirror,
        }
    }
}

/// Where an [`ImageBuf`]'s pixels live.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Storage {
    /// No pixels yet: the buffer names a file it has not read.
    Uninitialized,
    /// Pixels the buffer allocated and owns.
    Local,
    /// Pixels belonging to the caller, which the buffer only points at.
    App,
    /// Pixels served on demand by an [`ImageCache`](crate::ImageCache).
    Cache,
}

impl Storage {
    fn from_sys(storage: sys::imagebuf::IBStorage) -> Self {
        match storage {
            sys::imagebuf::IBStorage::LOCALBUFFER => Self::Local,
            sys::imagebuf::IBStorage::APPBUFFER => Self::App,
            sys::imagebuf::IBStorage::IMAGECACHE => Self::Cache,
            _ => Self::Uninitialized,
        }
    }
}

/// An image held in memory, the unit OpenImageIO's algorithms operate on.
///
/// A buffer is either allocated from a specification or attached to a file.
/// A file-backed buffer does not read anything until asked, so opening one is
/// cheap:
///
/// ```no_run
/// use oiio::ImageBuf;
/// use std::path::Path;
///
/// # fn main() -> oiio::Result<()> {
/// let mut image = ImageBuf::from_path(Path::new("image.exr"))?;
/// let spec = image.spec()?;          // metadata only, no pixels yet
/// image.read()?;                     // now the pixels
///
/// let roi = spec.data_window()?;
/// let mut pixels = vec![0.0_f32; roi.element_count()?];
/// image.get_pixels_into(roi, &mut pixels)?;
/// # Ok(())
/// # }
/// ```
pub struct ImageBuf {
    inner: cxx::UniquePtr<sys::imagebuf::ImageBuf>,
}

// `ImageBufImpl` holds its own pixel storage, its own `ImageSpec` and its own
// error string; there is no `thread_local` in `imagebuf.cpp`, nothing
// `Perthread`-shaped, and no handle keyed to the creating thread. Every buffer
// this crate makes from a file passes a null cache (see `from_path`, which
// hands `cxx::SharedPtr::null()` to the shim), so `m_imagecache` is null and
// the destructor's one cache-reaching branch (`imagebuf.cpp:866-869`) does not
// fire. Moving the value to another thread and dropping it there is therefore
// a drop of plain owned memory.
//
// `Sync` is NOT claimed, and the clearest reason is a one-liner:
// `void threads(int n) const { m_threads = n; }` (`imagebuf.cpp:287`) writes a
// non-atomic `mutable int m_threads` (`:345`) through a `const` path. A `&self`
// method in C++ is not read-only here. This crate already contains that
// correctly, because the shim takes a non-const `ImageBuf&` and the wrapper is
// `set_threads(&mut self)`, which is the `&mut` discipline doing real work
// rather than decoration. Keep new methods on `&mut self` unless the C++ behind
// them is genuinely const.
//
// Two things this impl does not claim.
//
// First, `write()` reaches OpenImageIO's process-wide shared cache, and it does
// so *because* `m_imagecache` is null. `ImageBuf::write` calls
// `m_impl->invalidate(filename, true)` (`imagebuf.cpp:1767`), whose body
// fetches `ImageCache::create(true)` and, when the buffer's own cache differs
// from the shared one, invalidates the shared one too (`:312-320`; the comment
// there says as much). In a process where only this crate uses OpenImageIO
// that is a locked singleton fetch and a lookup that misses, because nothing
// populates the shared cache. Where foreign OpenImageIO code shares the process
// and has populated it, that invalidation can free state another reader is
// walking, which is the hazard described above `ImageCache`'s own impl. `Send`
// does not create this: two threads can each build a buffer and call `write`
// concurrently today with `ImageBuf: !Send`. It is stated because a comment
// claiming this type never touches an `ImageCache` would be false.
//
// Second, diagnostics do not travel. OpenImageIO's global error channel is
// `static thread_local ErrorHolder` (`strutil.cpp:217`), so a message raised on
// the thread that built a buffer reads back empty on the thread that received
// it. `ImageBuf`'s own `m_err` is a member and does move with the value; it is
// the global channel that does not. Nothing here is unsound, but an error
// explaining a failure can be lost across a move.
//
// Conditions for the above to keep holding. Never pass a real cache to
// `imagebuf_new_from_file`: with one, `drop` becomes a `close` plus
// `invalidate` on that cache from whatever thread the drop lands on, which the
// borrow checker cannot see and so cannot exclude against a concurrent `&self`
// read. Leave `imagebuf_lock`/`imagebuf_unlock` unbound in the safe crate; they
// are declared in `oiio-sys` and referenced nowhere here, and a lock released
// on a thread that did not take it is undefined behaviour. And do not expose
// `imagebuf_new_from_buffer`, whose result aliases caller memory with no
// lifetime, making `Send` a claim about that memory too.
unsafe impl Send for ImageBuf {}

impl ImageBuf {
    /// An image with no specification and no pixels yet.
    ///
    /// This is what to pass as the destination of an
    /// [`algo`](crate::algo) operation that should decide the result's shape
    /// for itself — [`transpose`](crate::algo::transpose) exchanges the
    /// dimensions, and [`copy`](crate::algo::copy) can change the pixel
    /// format. Handing those an already-allocated destination makes them write
    /// into it as it is, keeping its size and format.
    pub fn empty() -> Result<Self> {
        Self::from_inner(sys::imagebuf::imagebuf_default(), "create image buffer")
    }

    /// Allocate an image described by `spec`, with every pixel set to zero.
    ///
    /// A specification larger than the machine can allocate is an error here.
    /// OpenImageIO does not propagate the failure on its own: it records the
    /// error, leaves the buffer with no pixels, and the caller that would find
    /// out is the zero-fill, which asserts and then divides by zero. The shim
    /// allocates and zeroes in two steps so the failure can be returned.
    pub fn new(spec: &ImageSpec) -> Result<Self> {
        // A deep image's samples are indexed by an int inside DeepData::init,
        // so a spec with more pixels than that can hold is refused here rather
        // than allowed to truncate.
        if spec.is_deep() {
            let pixels = spec.pixel_count()?;
            if pixels > i32::MAX as usize {
                return Err(Error::InvalidImageSpec(format!(
                    "a deep image is limited to {} pixels, and this spec has {pixels}",
                    i32::MAX
                )));
            }
        }

        let native_spec = spec.to_sys()?;
        let Some(native_spec) = native_spec.as_ref() else {
            return Err(Error::InvalidImageSpec(
                "OpenImageIO could not allocate an image specification".to_owned(),
            ));
        };
        let mut error = String::new();
        let inner = sys::imagebuf::imagebuf_new_from_spec_checked(native_spec, &mut error);
        if inner.is_null() && !error.is_empty() {
            return Err(Error::operation("allocate image buffer", error));
        }
        Self::from_inner(inner, "allocate image buffer")
    }

    /// Attach to an image file without reading its pixels.
    ///
    /// The specification becomes available immediately;
    /// [`ImageBuf::read`] fetches the pixels.
    pub fn from_path(image_path: &Path) -> Result<Self> {
        Self::from_path_at(image_path, 0, 0)
    }

    /// Attach to one subimage and mip level of an image file.
    pub fn from_path_at(image_path: &Path, subimage: u32, mip_level: u32) -> Result<Self> {
        let filename = path_to_utf8(image_path)?;
        let subimage = level_index(subimage)?;
        let mip_level = level_index(mip_level)?;

        // SAFETY: a null config and a null ioproxy request the defaults, and
        // a null shared cache asks OpenImageIO to use its own.
        let inner = unsafe {
            sys::imagebuf::imagebuf_new_from_file(
                filename,
                subimage,
                mip_level,
                cxx::SharedPtr::null(),
                std::ptr::null(),
                std::ptr::null_mut(),
            )
        };
        let mut buffer = Self::from_inner(inner, "open image buffer")?;

        // Resolve the specification now so a missing or unreadable file is
        // reported here rather than at the first pixel access.
        if !sys::imagebuf::imagebuf_init_spec(buffer.inner_mut(), filename, subimage, mip_level) {
            return Err(Error::OpenImage {
                path: image_path.to_path_buf(),
                message: buffer.take_error(),
            });
        }
        Ok(buffer)
    }

    /// Read the pixels of the attached file, at the subimage and mip level it
    /// is attached to.
    ///
    /// Those are the indices [`ImageBuf::from_path_at`] was given, which
    /// [`ImageBuf::subimage`] and [`ImageBuf::mip_level`] report before any
    /// pixel is read. OpenImageIO's own `read` defaults both to zero instead,
    /// so a buffer attached to mip level 3 whose spec says 64 by 64 came back
    /// 512 by 512 from level 0, with nothing reported: the level was asked
    /// for, confirmed by the spec, and then replaced. Reading what the buffer
    /// says it holds is the only answer that cannot surprise a caller.
    ///
    /// Use [`ImageBuf::read_at`] to read a different one.
    pub fn read(&mut self) -> Result<()> {
        self.read_at(self.subimage(), self.mip_level(), None)
    }

    /// Read one subimage and mip level, optionally converting the pixels.
    ///
    /// Passing `None` keeps the file's own format.
    pub fn read_at(
        &mut self,
        subimage: u32,
        mip_level: u32,
        convert_to: Option<PixelFormat>,
    ) -> Result<()> {
        let subimage = level_index(subimage)?;
        let mip_level = level_index(mip_level)?;
        let convert = convert_to.unwrap_or(PixelFormat::Other).to_sys();
        let succeeded =
            sys::imagebuf::imagebuf_read(self.inner_mut(), subimage, mip_level, true, convert);
        self.check("read image buffer", succeeded)
    }

    /// Read only channels `channels.start..channels.end` of the attached
    /// file.
    ///
    /// Equivalent to [`ImageBuf::read_channels_at`] with subimage 0, mip
    /// level 0 and no conversion.
    pub fn read_channels(&mut self, channels: std::ops::Range<u32>) -> Result<()> {
        self.read_channels_at(0, 0, channels, None)
    }

    /// Read a channel subset of one subimage and mip level, optionally
    /// converting the pixels.
    ///
    /// On success the buffer holds exactly the requested channels,
    /// renumbered from zero, and [`ImageBuf::spec`] reflects that shape;
    /// [`ImageBuf::native_spec`] keeps the file's full channel list.
    /// OpenImageIO documents the subset as advisory — "not guaranteed to be
    /// honored by the underlying implementation" — so this method verifies
    /// afterwards that the buffer holds the channels asked for, and reports
    /// an error when OpenImageIO kept something else.
    ///
    /// The range must be non-empty, ascending and within the native channel
    /// count of the requested subimage. Deep images are refused: OpenImageIO
    /// reads a deep file whole and ignores both the range and `convert_to`.
    ///
    /// A buffer that already holds a *different* subset of the *same size*
    /// of the same subimage cannot be re-read in place — OpenImageIO's
    /// early-out compares only the channel count — so that call returns an
    /// error naming the channels the buffer kept. Read the full range first,
    /// or use a fresh buffer. Files with duplicate channel names can defeat
    /// this detection.
    ///
    /// Passing `None` keeps the file's own format.
    pub fn read_channels_at(
        &mut self,
        subimage: u32,
        mip_level: u32,
        channels: std::ops::Range<u32>,
        convert_to: Option<PixelFormat>,
    ) -> Result<()> {
        const OPERATION: &str = "read image buffer channels";
        let subimage = level_index(subimage)?;
        let mip_level = level_index(mip_level)?;

        // An empty or reversed range must not reach C++: OpenImageIO sizes
        // the buffer as chend - chbegin, so an inverted range turns a
        // negative count into a huge resize whose length_error is
        // std::terminate under the noexcept shim, and an equal pair
        // allocates zero channels that the reader then writes one channel
        // of every pixel into.
        if channels.start >= channels.end {
            return Err(Error::InvalidRoi(format!(
                "channel range {}..{} is empty or reversed",
                channels.start, channels.end
            )));
        }

        // A buffer with no attached file reports success having read
        // nothing; say so instead.
        let filename = self.name().to_owned();
        if filename.is_empty() {
            return Err(Error::operation(
                OPERATION,
                "this buffer is not attached to a file".to_owned(),
            ));
        }

        // Resolve the requested subimage's native spec before validating —
        // OpenImageIO clamps against the native spec only after its own
        // init_spec, so validating against the current subimage would check
        // the wrong image. The call is idempotent once resolved.
        if !sys::imagebuf::imagebuf_init_spec(self.inner_mut(), &filename, subimage, mip_level) {
            return Err(Error::operation(OPERATION, self.take_error()));
        }
        let native = self.native_spec()?;

        // A deep file is read whole, before the channel range or conversion
        // are consulted, which would quietly answer this call with every
        // channel in the file's own format.
        if native.is_deep() {
            return Err(Error::operation(
                OPERATION,
                "this image is deep, and OpenImageIO reads a deep file whole, \
                 ignoring the channel subset; use ImageBuf::read"
                    .to_owned(),
            ));
        }

        // chbegin is never validated upstream, and a too-large chend is
        // silently clamped, handing back fewer channels than asked for
        // under a success return.
        let count = native.channel_count();
        if channels.end > count {
            return Err(Error::InvalidRoi(format!(
                "channel range {}..{} is outside the native channel count {count}",
                channels.start, channels.end
            )));
        }
        let to_i32 = |value: u32| {
            i32::try_from(value)
                .map_err(|_| Error::InvalidRoi("channel index exceeds i32::MAX".to_owned()))
        };
        let chbegin = to_i32(channels.start)?;
        let chend = to_i32(channels.end)?;

        // force is always true: without it, OpenImageIO's first early-out
        // returns an already-read buffer untouched without looking at the
        // channel range at all.
        let convert = convert_to.unwrap_or(PixelFormat::Other).to_sys();
        let succeeded = sys::imagebuf::imagebuf_read_subset(
            self.inner_mut(),
            subimage,
            mip_level,
            chbegin,
            chend,
            true,
            convert,
        );
        self.check(OPERATION, succeeded)?;

        // The second early-out compares only the channel count: a buffer
        // already holding a same-sized different subset of this subimage
        // reports success while keeping the old channels. The subset is
        // also documented as advisory. Verify what the buffer holds.
        let expected = &native.channel_names()[channels.start as usize..channels.end as usize];
        let held = self.spec()?;
        if held.channel_names() != expected {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "the buffer kept previously read channels {:?} instead of {:?}; \
                     OpenImageIO does not re-read when only the position of a \
                     same-sized channel range changes; read the full image first, \
                     or use a fresh buffer",
                    held.channel_names(),
                    expected
                ),
            ));
        }
        Ok(())
    }

    /// The image's specification.
    pub fn spec(&self) -> Result<ImageSpec> {
        ImageSpec::from_sys(sys::imagebuf::imagebuf_spec(self.inner()))
    }

    /// The specification of the file on disk, before any conversion.
    pub fn native_spec(&self) -> Result<ImageSpec> {
        ImageSpec::from_sys(sys::imagebuf::imagebuf_nativespec(self.inner()))
    }

    /// Where this buffer's pixels live.
    pub fn storage(&self) -> Storage {
        Storage::from_sys(sys::imagebuf::imagebuf_storage(self.inner()))
    }

    /// Whether the buffer has a specification yet.
    pub fn is_initialized(&self) -> bool {
        sys::imagebuf::imagebuf_initialized(self.inner())
    }

    /// The file name this buffer is attached to, empty when it has none.
    pub fn name(&self) -> &str {
        sys::imagebuf::imagebuf_name(self.inner())
    }

    /// The format the attached file is stored in, empty when there is none.
    pub fn file_format_name(&self) -> &str {
        sys::imagebuf::imagebuf_file_format_name(self.inner())
    }

    /// Number of subimages in the attached file.
    pub fn subimage_count(&self) -> i32 {
        sys::imagebuf::imagebuf_nsubimages(self.inner())
    }

    /// Number of mip levels of the attached file, **which is 0 on
    /// OpenImageIO older than 3.2.2.0**. On those versions use
    /// [`ImageCache::mip_level_count`](crate::ImageCache::mip_level_count),
    /// which answers on every version.
    ///
    /// Every buffer this crate opens from a file passes a null cache, which
    /// is what the `Send` reasoning on this type rests on, so it always
    /// takes `ImageBufImpl::init_spec`'s `ImageInput` branch rather than the
    /// cache-backed one. Up to and including 3.2.1.3 that branch set
    /// `m_nsubimages` from `oiio:subimages` and left `m_nmiplevels` at the
    /// zero it was initialised with, so this answered 0 for every file,
    /// mipmapped or not, while `subimage_count` from the same function was
    /// correct. OpenImageIO PR #5437 gave the branch a real value from
    /// `oiio:miplevels`; it reached the 3.2 line as a backport that ships in
    /// 3.2.2.0, so from that release on this returns the real count. An
    /// [`ImageCache`](crate::ImageCache) reports 10 levels for OpenEXR's
    /// `ColorCodedLevels.exr`, and so does this on 3.2.2.0 and newer.
    ///
    /// Reading a level works on every version regardless of what this
    /// returns, and [`ImageBuf::from_path_at`] refuses one past the last, so
    /// code that reads levels rather than counting them was never affected.
    pub fn mip_level_count(&self) -> i32 {
        sys::imagebuf::imagebuf_nmiplevels(self.inner())
    }

    /// Whether the pixels in memory have actually been filled in.
    ///
    /// False for a buffer whose read failed. OpenImageIO allocates the pixels
    /// before it opens the file, so a failed read leaves the allocation behind
    /// untouched; without this the buffer looks readable and hands back
    /// whatever the heap happened to contain.
    pub fn pixels_valid(&self) -> bool {
        sys::imagebuf::imagebuf_pixels_valid(self.inner())
    }

    /// Number of channels per pixel.
    ///
    /// `u32` to match every other `channel_count` in the crate, and the
    /// channel indices the API takes. OpenImageIO reports an `int`; a
    /// negative one would mean an uninitialized buffer, which reads as zero
    /// channels here.
    pub fn channel_count(&self) -> u32 {
        sys::imagebuf::imagebuf_nchannels(self.inner()).max(0) as u32
    }

    /// Borrow the buffer's own pixel memory, without copying it.
    ///
    /// This is the way to hand an image to the rest of the Rust ecosystem.
    /// [`get_pixels_into`](Self::get_pixels_into) copies and can convert; this
    /// does neither, so `T` has to be exactly the format the buffer holds, and
    /// a 4K float RGBA frame costs nothing instead of 132 MB.
    ///
    /// The slice borrows the buffer, so nothing can reallocate underneath it:
    /// every method that could is `&mut self`.
    ///
    /// Returns an error rather than a slice when the pixels are not there to
    /// borrow:
    ///
    /// * the image is deep, and has samples rather than pixels;
    /// * its pixels have not been read, or belong to an
    ///   [`ImageCache`](crate::ImageCache) rather than to the buffer;
    /// * `T` is not the format the buffer holds, since nothing is converted;
    /// * the rows are not contiguous, which OpenImageIO permits and which a
    ///   flat slice cannot describe. [`get_pixels_into`](Self::get_pixels_into)
    ///   handles that case.
    ///
    /// ```
    /// use oiio::{ImageBuf, ImageSpec, PixelFormat};
    /// # fn main() -> oiio::Result<()> {
    /// let spec = ImageSpec::new(64, 64, 4, PixelFormat::F32)?;
    /// let image = ImageBuf::new(&spec)?;
    /// let pixels: &[f32] = image.pixels()?;
    /// assert_eq!(pixels.len(), 64 * 64 * 4);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// A buffer attached to a file holds nothing to borrow until it is read,
    /// so neither the read nor the type is optional. Most OpenEXR files hold
    /// `half`, and asking for `f32` over one of those is refused rather than
    /// converted. [`ImageSpec::format`](crate::ImageSpec::format) says which
    /// to ask for when it is not known in advance.
    ///
    /// ```no_run
    /// # fn main() -> oiio::Result<()> {
    /// let mut image = oiio::ImageBuf::from_path("frame.exr".as_ref())?;
    /// image.read()?;
    /// let pixels: &[oiio::f16] = image.pixels()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn pixels<T: Pixel>(&self) -> Result<&[T]> {
        const OPERATION: &str = "borrow image buffer pixels";
        let count = self.borrowable_element_count::<T>(OPERATION)?;

        // SAFETY: `borrowable_element_count` has established that the buffer
        // owns local, contiguous, already-read pixels whose format is exactly
        // `T`, and has derived `count` from that same specification. The slice
        // borrows `self`, and every method that could reallocate or free the
        // pixels takes `&mut self`, so it cannot be invalidated while the
        // borrow lives.
        let data = unsafe { sys::imagebuf::imagebuf_localpixels(self.inner()) };
        Ok(unsafe { std::slice::from_raw_parts(data.cast::<T>(), count) })
    }

    /// Borrow the buffer's own pixel memory for writing, without copying it.
    ///
    /// The mutable counterpart of [`pixels`](Self::pixels), with the same
    /// conditions and the same failures.
    pub fn pixels_mut<T: Pixel>(&mut self) -> Result<&mut [T]> {
        const OPERATION: &str = "borrow image buffer pixels for writing";
        let count = self.borrowable_element_count::<T>(OPERATION)?;

        // SAFETY: as for `pixels`, and the `&mut self` borrow additionally
        // excludes every other access to the buffer for the life of the slice.
        let data = unsafe { sys::imagebuf::imagebuf_localpixels_mut(self.inner_mut()) };
        Ok(unsafe { std::slice::from_raw_parts_mut(data.cast::<T>(), count) })
    }

    /// The conditions both borrows depend on, checked once.
    ///
    /// Returns how many `T` the buffer's local memory holds, having
    /// established that borrowing it is sound.
    fn borrowable_element_count<T: Pixel>(&self, operation: &'static str) -> Result<usize> {
        self.require_flat(operation)?;

        if !sys::imagebuf::imagebuf_pixels_valid(self.inner()) {
            return Err(Error::operation(
                operation,
                "this buffer has no pixels yet; read it first".to_owned(),
            ));
        }

        let spec = self.spec()?;
        let actual = spec.format();
        if actual != T::FORMAT {
            return Err(Error::operation(
                operation,
                format!(
                    "the buffer holds {actual:?} and nothing is converted when \
                     borrowing; ask for {actual:?}, or use get_pixels_into to \
                     convert to {:?}",
                    T::FORMAT
                ),
            ));
        }

        // Null means the pixels are not the buffer's own: either it is backed
        // by an ImageCache, which serves tiles on demand and owns them, or it
        // has no storage at all.
        if unsafe { sys::imagebuf::imagebuf_localpixels(self.inner()) }.is_null() {
            return Err(Error::operation(
                operation,
                format!(
                    "these pixels are not the buffer's to lend: its storage is \
                     {:?}",
                    self.storage()
                ),
            ));
        }

        // OpenImageIO does not promise contiguity, and says so where
        // `localpixels` is documented. A flat slice cannot describe a buffer
        // with gaps between its rows, so refuse rather than hand back a slice
        // whose indices quietly mean the wrong pixels.
        if !sys::imagebuf::imagebuf_contiguous(self.inner()) {
            return Err(Error::operation(
                operation,
                "this buffer's rows are not contiguous, so a flat slice would \
                 not describe it; use get_pixels_into"
                    .to_owned(),
            ));
        }

        spec.element_count()
    }

    /// Copy a region out into a contiguous buffer.
    ///
    /// The destination length must exactly equal `roi.element_count()`, and
    /// values are converted to `T` if the image holds another format. To
    /// borrow the pixels instead of copying them, see [`pixels`](Self::pixels).
    pub fn get_pixels_into<T: Pixel>(&self, roi: Roi, pixels: &mut [T]) -> Result<()> {
        self.require_flat("read image buffer pixels")?;
        self.require_region_inside(&roi)?;
        validate_buffer_len(roi.element_count()?, pixels.len())?;
        let sys_roi = roi.to_sys();

        // SAFETY: Pixel is sealed to initialized scalar layouts, and the shim
        // re-derives the layout from the region before writing anything.
        let succeeded = unsafe {
            sys::imagebuf::imagebuf_get_pixels_span(
                self.inner(),
                &sys_roi,
                pixel::type_desc::<T>(),
                pixel::as_bytes_mut(pixels),
            )
        };
        if !succeeded {
            return Err(Error::operation(
                "read image buffer pixels",
                sys::imagebuf::imagebuf_geterror(self.inner(), true),
            ));
        }
        if let Err(error) = self.require_filled("read image buffer pixels") {
            // The copy has already happened, so the caller's slice is holding
            // whatever the allocation held. Returning an error is not enough on
            // its own: scrub it, so a caller who ignores the error still cannot
            // read process memory out of it.
            // SAFETY: as above; `pixels` is a slice of initialized scalars and
            // zero is a valid bit pattern for every one of them.
            pixel::as_bytes_mut(pixels).fill(0);
            return Err(error);
        }
        Ok(())
    }

    /// Copy a contiguous buffer into a region.
    ///
    /// The source length must exactly equal `roi.element_count()`.
    pub fn set_pixels<T: Pixel>(&mut self, roi: Roi, pixels: &[T]) -> Result<()> {
        self.require_flat("write image buffer pixels")?;
        self.require_region_inside(&roi)?;
        validate_buffer_len(roi.element_count()?, pixels.len())?;
        let sys_roi = roi.to_sys();

        // SAFETY: as in `get_pixels_into`.
        let succeeded = unsafe {
            sys::imagebuf::imagebuf_set_pixels_span(
                self.inner_mut(),
                &sys_roi,
                pixel::type_desc::<T>(),
                pixel::as_bytes(pixels),
            )
        };
        self.check("write image buffer pixels", succeeded)
    }

    /// Write the image to a file, keeping its current pixel format.
    pub fn write(&mut self, image_path: &Path) -> Result<()> {
        self.write_as(image_path, None)
    }

    /// Write the image to a file in a chosen pixel format.
    pub fn write_as(&mut self, image_path: &Path, format: Option<PixelFormat>) -> Result<()> {
        let filename = path_to_utf8(image_path)?;
        let dtype = format.unwrap_or(PixelFormat::Other).to_sys();
        let succeeded = sys::imagebuf::imagebuf_write(self.inner_mut(), filename, dtype, "");
        self.check("write image buffer", succeeded)
    }

    /// Write the whole current subimage through an already-open writer.
    ///
    /// This is how a buffer reaches a multi-part file, an in-memory writer
    /// ([`crate::ImageOutput::to_memory`]), or a format conversion chosen at
    /// open time: the writer's own open specification governs everything
    /// about the file — pixel format (the buffer's values are converted
    /// automatically), tiling, and metadata.
    ///
    /// The writer's data window — origin included — and channel count must
    /// exactly equal the buffer's, and both must be deep or both flat:
    /// OpenImageIO trusts the two to agree and walks the writer's window
    /// over the buffer's memory, so a larger window would read past the
    /// buffer and a smaller or shifted one would silently crop or shift.
    /// Nothing may have been written to the current subimage yet. The
    /// writer is left open: finish it with [`crate::ImageOutput::close`] or
    /// continue with [`crate::ImageOutput::append_subimage`].
    pub fn write_to(&mut self, output: &mut crate::ImageOutput) -> Result<()> {
        const OPERATION: &str = "write image buffer to output";
        // An uninitialized buffer takes the cache-backed branch upstream,
        // where a temporary sized by the buffer's zero byte count is walked
        // by the writer's window.
        if !self.is_initialized() {
            return Err(Error::operation(
                OPERATION,
                "this buffer has no specification yet; nothing to write".to_owned(),
            ));
        }
        let buf_spec = self.spec()?;
        let out_spec = output.spec();
        // ImageBuf::write validates the pixels and then overwrites that
        // verdict with the write's own return, so a failed deferred read
        // would publish the untouched allocation into the file — or into
        // in-memory bytes — under a success return. Run the read here,
        // where its failure is reportable, and refuse a flat buffer whose
        // pixels never arrived. A deep buffer holds samples, not flat
        // pixels, and is checked by the deepness guards below instead.
        if !self.is_deep() {
            if !self.name().is_empty() && !self.pixels_valid() {
                let (subimage, mip_level) = (self.subimage(), self.mip_level());
                self.read_at(subimage, mip_level, None)?;
            }
            self.require_filled(OPERATION)?;
        }
        if self.is_deep() && !out_spec.is_deep() {
            return Err(Error::operation(
                OPERATION,
                "the writer was opened for flat pixels but this buffer is deep; \
                 open it with a spec from ImageSpec::as_deep"
                    .to_owned(),
            ));
        }
        if !self.is_deep() && out_spec.is_deep() {
            return Err(Error::operation(
                OPERATION,
                "the writer was opened for deep samples but this buffer is flat".to_owned(),
            ));
        }
        // ImageBuf::write(ImageOutput*) never compares the two specs: the
        // in-memory path hands the buffer's pointer and strides to a write
        // that walks the WRITER's width, height and channel count over that
        // memory, and the deep path indexes the buffer's samples by the
        // writer's window. A bigger writer window reads past the buffer's
        // allocation; a smaller or shifted one silently crops or shifts. So:
        // exact equality, origin included.
        if buf_spec.origin() != out_spec.origin()
            || buf_spec.dimensions() != out_spec.dimensions()
            || buf_spec.channel_count() != out_spec.channel_count()
        {
            return Err(Error::InvalidImageSpec(format!(
                "the buffer's data window (origin {:?}, size {:?}, {} channels) must \
                 exactly equal the writer's (origin {:?}, size {:?}, {} channels); \
                 rebuild the buffer or writer from the other's spec",
                buf_spec.origin(),
                buf_spec.dimensions(),
                buf_spec.channel_count(),
                out_spec.origin(),
                out_spec.dimensions(),
                out_spec.channel_count()
            )));
        }
        // This path writes from the top of the data window at the C++ level,
        // beneath the crate's in-order cursor; EXR's forward-only scanline
        // writer makes a partial rewrite format-dependent.
        let top = out_spec.origin()[1];
        if output.scanline_cursor() != top {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "rows {top}..{} of this subimage were already written through \
                     write_scanlines; write_to needs an untouched subimage",
                    output.scanline_cursor()
                ),
            ));
        }
        // SAFETY: the pointer comes from a live &mut ImageOutput, is
        // consumed within this one call, and the pinned writer is not moved.
        let succeeded = unsafe {
            let out_ptr = output.native_mut().get_unchecked_mut() as *mut sys::imageio::ImageOutput;
            sys::imagebuf::imagebuf_write_to_imageoutput(self.inner_mut(), out_ptr)
        };
        // ImageBuf::write transfers the writer's error into the buffer, so
        // the buffer's error state carries the message.
        self.check(OPERATION, succeeded)?;
        output.mark_whole_subimage_written();
        Ok(())
    }

    /// Ensure the pixels are held locally and writable.
    ///
    /// A cache-backed buffer is read into its own storage; one that is already
    /// local is left alone.
    pub fn make_writable(&mut self) -> Result<()> {
        let succeeded = sys::imagebuf::imagebuf_make_writeable(self.inner_mut(), true);
        self.check("make image buffer writable", succeeded)
    }

    /// Whether this buffer holds a deep image, where each pixel is a list of
    /// samples rather than one value per channel.
    ///
    /// A buffer becomes deep by being built from a deep
    /// [`ImageSpec`](ImageSpec::as_deep), or by being read from a deep file.
    pub fn is_deep(&self) -> bool {
        sys::imagebuf::imagebuf_deep(self.inner())
    }

    /// How many samples one pixel holds.
    ///
    /// Zero for a pixel nothing was written to, and for any pixel of a flat
    /// image.
    pub fn deep_sample_count(&self, x: i32, y: i32) -> u32 {
        sys::imagebuf::imagebuf_deep_samples(self.inner(), x, y, 0).max(0) as u32
    }

    /// Set how many samples one pixel holds.
    ///
    /// Shrinking a pixel drops the samples past the new end but keeps the room
    /// they occupied, so growing it again within that room brings their old
    /// values back rather than zeroes. Write every sample you intend to read.
    ///
    /// The storage the counts describe is allocated on the first value
    /// written, so a total too large for the machine is reported there — or
    /// here, once the samples are already allocated and this call has to
    /// grow them.
    pub fn set_deep_sample_count(&mut self, x: i32, y: i32, count: u32) -> Result<()> {
        self.require_deep("set deep sample count")?;
        // OpenImageIO's setter indexes the pixel without checking the range,
        // so an out-of-range coordinate silently resizes a different pixel —
        // one the reader, which does check, then reports as empty.
        self.require_inside("set deep sample count", x, y)?;
        let count = i32::try_from(count).map_err(|_| {
            Error::InvalidImageSpec("deep sample count exceeds i32::MAX".to_owned())
        })?;
        let mut error = String::new();
        if !sys::imagebuf::imagebuf_set_deep_samples(self.inner_mut(), x, y, 0, count, &mut error) {
            return Err(Error::operation("set deep sample count", error));
        }
        Ok(())
    }

    /// One sample's value, as a float.
    pub fn deep_value(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<f32> {
        let (channel, sample) = self.deep_index("read deep value", x, y, channel, sample)?;
        Ok(sys::imagebuf::imagebuf_deep_value(
            self.inner(),
            x,
            y,
            0,
            channel,
            sample,
        ))
    }

    /// One sample's value, as an unsigned integer.
    ///
    /// Use this for a channel whose type is unsigned, and note what the
    /// alternative does rather than assuming it is approximate.
    /// [`deep_value`](Self::deep_value) does not round an unsigned channel, it
    /// *normalises* it: OpenImageIO converts through `convert_type`, which
    /// divides by [`u32::MAX`]. An object id of 2,056,745,377 comes back as
    /// 0.47887334, which is a plausible colour value and not a wrong-looking
    /// number, so nothing announces the loss. Deep EXRs from a renderer carry
    /// `id` and `particleid` channels as `uint32` next to half `R G B A Z`, so
    /// a caller walking every channel with `deep_value` reads most of them
    /// correctly and silently scales the identifiers into nothing.
    pub fn deep_value_uint(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<u32> {
        let (channel, sample) = self.deep_index("read deep value", x, y, channel, sample)?;
        Ok(sys::imagebuf::imagebuf_deep_value_uint(
            self.inner(),
            x,
            y,
            0,
            channel,
            sample,
        ))
    }

    /// Set one sample's value from a float.
    pub fn set_deep_value(
        &mut self,
        x: i32,
        y: i32,
        channel: u32,
        sample: u32,
        value: f32,
    ) -> Result<()> {
        let (channel, sample) = self.deep_index("write deep value", x, y, channel, sample)?;
        let mut error = String::new();
        if !sys::imagebuf::imagebuf_set_deep_value(
            self.inner_mut(),
            x,
            y,
            0,
            channel,
            sample,
            value,
            &mut error,
        ) {
            return Err(Error::operation("write deep value", error));
        }
        Ok(())
    }

    /// Set one sample's value from an unsigned integer.
    pub fn set_deep_value_uint(
        &mut self,
        x: i32,
        y: i32,
        channel: u32,
        sample: u32,
        value: u32,
    ) -> Result<()> {
        let (channel, sample) = self.deep_index("write deep value", x, y, channel, sample)?;
        let mut error = String::new();
        if !sys::imagebuf::imagebuf_set_deep_value_uint(
            self.inner_mut(),
            x,
            y,
            0,
            channel,
            sample,
            value,
            &mut error,
        ) {
            return Err(Error::operation("write deep value", error));
        }
        Ok(())
    }

    /// Reject a coordinate outside the data window.
    fn require_inside(&self, operation: &'static str, x: i32, y: i32) -> Result<()> {
        let spec = self.spec()?;
        let [origin_x, origin_y, _] = spec.origin();
        let [width, height, _] = spec.dimensions();
        // Widened to i64: with a negative origin and a huge coordinate the
        // i32 subtraction wraps negative in release builds, which reads as
        // "inside" and lets the coordinate through to OpenImageIO's silent
        // out-of-window skip — the very thing this guard reports.
        let inside = x >= origin_x
            && y >= origin_y
            && (i64::from(x) - i64::from(origin_x)) < i64::from(width)
            && (i64::from(y) - i64::from(origin_y)) < i64::from(height);
        if inside {
            Ok(())
        } else {
            Err(Error::operation(
                operation,
                format!(
                    "{x},{y} is outside the data window {origin_x},{origin_y} \
                     to {},{}",
                    origin_x + width as i32,
                    origin_y + height as i32
                ),
            ))
        }
    }

    /// Refuse a deep image where flat pixels are expected.
    ///
    /// A deep `ImageBuf` reports `Storage::Local` but has no flat storage at
    /// all: `realloc` allocates zero bytes and the samples live in the
    /// `DeepData`. `ImageBuf::get_pixels` then takes its general path, and the
    /// iterator leaves `m_proxydata` null for a deep buffer because neither of
    /// the two branches that assign it applies, so `p[c]` reads or writes
    /// through a null pointer. Reading a deep EXR with `ImageBuf::read` is
    /// enough to get here.
    /// Refuse pixels that were allocated but never filled in.
    ///
    /// `ImageBufImpl::read` allocates before it opens the file, and the
    /// allocation is not zeroed. When the open or the decode then fails it
    /// records the error and clears the valid flag, but leaves the untouched
    /// allocation and the local storage in place. `ImageBuf::get_pixels` gates
    /// its fast path on `localpixels()` alone and never consults the flag, so
    /// it copied whatever the heap happened to hold into the caller's slice and
    /// reported success.
    ///
    /// This has to run afterwards rather than before. A buffer attached to a
    /// file it has not read yet is indistinguishable from one whose read
    /// failed: both are local storage with the flag clear. It is `localpixels`
    /// inside the read that performs the deferred load and sets the flag, so
    /// the flag only answers the question once the call has been made.
    fn require_filled(&self, operation: &'static str) -> Result<()> {
        if self.storage() != Storage::Local || self.pixels_valid() {
            return Ok(());
        }
        // Take whatever the failed read recorded, both to say something useful
        // and so OpenImageIO does not complain at destruction that nobody
        // collected it.
        let recorded = sys::imagebuf::imagebuf_geterror(self.inner(), true);
        let mut message =
            "the pixels were never read; the deferred read failed and left the allocation untouched"
                .to_owned();
        if !recorded.is_empty() {
            message.push_str(" (");
            message.push_str(recorded.trim_end());
            message.push(')');
        }
        Err(Error::operation(operation, message))
    }

    fn require_flat(&self, operation: &'static str) -> Result<()> {
        if self.is_deep() {
            Err(Error::operation(
                operation,
                "this image is deep; use DeepImage or ImageBuf::deep_value \
                 to reach its samples"
                    .to_owned(),
            ))
        } else {
            Ok(())
        }
    }

    /// Refuse a region the image does not have, on any axis.
    ///
    /// The channel axis is the one that traps. `ImageBuf::get_pixels` clamps
    /// `chend` to the channel count but never `chbegin`, so a range starting at
    /// or past the end leaves a zero or negative channel count; `ROI::contains`
    /// still passes, so it takes the fast path into `copy_image`, which divides
    /// the pixel size by that count and then memcpys with it.
    ///
    /// The spatial axes are quieter and just as wrong. A region outside the
    /// data window reads as zeros, because the iterator's default wrap is
    /// `WrapBlack`, so the caller cannot tell an absent region from a black
    /// one; and `set_pixels` skips every pixel that does not exist and still
    /// reports success, so the write silently goes nowhere. A `chend` past the
    /// channel count is worse than either: the strides were computed from the
    /// range the caller asked for, so OpenImageIO writes the real channels at
    /// the wide stride and every remaining slot keeps whatever the caller's
    /// buffer already held.
    ///
    /// `ImageInput::read_region_into` has always rejected these, so this is
    /// also what stops the two halves of the crate from disagreeing.
    fn require_region_inside(&self, roi: &Roi) -> Result<()> {
        roi.validate_within(&self.spec()?)
    }

    fn require_deep(&self, operation: &'static str) -> Result<()> {
        if self.is_deep() {
            Ok(())
        } else {
            Err(Error::operation(
                operation,
                "this image is not deep; build it from ImageSpec::as_deep".to_owned(),
            ))
        }
    }

    /// Validate a channel and sample index before it reaches C++.
    ///
    /// OpenImageIO answers an out-of-range index with a null pointer and then
    /// either reads zero or drops the write, both silently, so the check has to
    /// happen here.
    fn deep_index(
        &self,
        operation: &'static str,
        x: i32,
        y: i32,
        channel: u32,
        sample: u32,
    ) -> Result<(i32, i32)> {
        self.require_deep(operation)?;
        let channels = self.channel_count();
        if channel >= channels {
            return Err(Error::operation(
                operation,
                format!("channel {channel} is outside the image's {channels}"),
            ));
        }
        let samples = self.deep_sample_count(x, y);
        if sample >= samples {
            return Err(Error::operation(
                operation,
                format!("sample {sample} is outside the {samples} at {x},{y}"),
            ));
        }
        let to_i32 = |value: u32| {
            i32::try_from(value)
                .map_err(|_| Error::InvalidImageSpec("deep index exceeds i32::MAX".to_owned()))
        };
        Ok((to_i32(channel)?, to_i32(sample)?))
    }

    fn from_inner(
        inner: cxx::UniquePtr<sys::imagebuf::ImageBuf>,
        operation: &'static str,
    ) -> Result<Self> {
        if inner.is_null() {
            return Err(Error::operation(
                operation,
                "OpenImageIO returned a null image buffer".to_owned(),
            ));
        }
        Ok(Self { inner })
    }

    pub(crate) fn take_error(&self) -> String {
        sys::imagebuf::imagebuf_geterror(self.inner(), true)
    }

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

    /// Which subimage this buffer currently represents.
    ///
    /// Meaningful for a buffer attached to a file; a buffer built from a
    /// specification reports zero, and several operations that rewrite the
    /// buffer reset it to zero.
    pub fn subimage(&self) -> u32 {
        sys::imagebuf::imagebuf_subimage(self.inner()).max(0) as u32
    }

    /// Which mip level this buffer currently represents.
    pub fn mip_level(&self) -> u32 {
        sys::imagebuf::imagebuf_miplevel(self.inner()).max(0) as u32
    }

    /// How many threads operations on this buffer may use; zero means
    /// OpenImageIO's global default.
    pub fn threads(&self) -> u32 {
        sys::imagebuf::imagebuf_threads(self.inner()).max(0) as u32
    }

    /// Set the thread count for operations on this buffer; zero restores
    /// OpenImageIO's global default.
    pub fn set_threads(&mut self, count: u32) -> Result<()> {
        let count = i32::try_from(count)
            .map_err(|_| Error::InvalidImageSpec("thread count exceeds i32::MAX".to_owned()))?;
        sys::imagebuf::imagebuf_set_threads(self.inner_mut(), count);
        Ok(())
    }

    /// One channel of one pixel, with out-of-window coordinates answered by
    /// the wrap mode. Deep buffers are refused — their pixels are sample
    /// lists, not values.
    pub fn channel_at(&self, x: i32, y: i32, channel: u32, wrap: Wrap) -> Result<f32> {
        self.require_flat("read a channel")?;
        let channel = i32::try_from(channel)
            .map_err(|_| Error::InvalidRoi("channel exceeds i32::MAX".to_owned()))?;
        self.require_wrappable(wrap)?;
        let value =
            sys::imagebuf::imagebuf_getchannel(self.inner(), x, y, 0, channel, wrap.to_sys());
        // The point read triggers the deferred file read, whose failure
        // OpenImageIO records without telling the iterator, which serves the
        // untouched allocation; checked after the call, as get_pixels does.
        self.require_filled("read a channel")?;
        Ok(value)
    }

    /// Every channel of one pixel, written into `values`.
    ///
    /// A slice shorter than the channel count reads that many channels; a
    /// longer one has its tail zeroed — by this crate, since OpenImageIO
    /// writes only the first `channel_count` values and would leave the
    /// rest holding whatever the caller had there.
    pub fn pixel_at_into(&self, x: i32, y: i32, wrap: Wrap, values: &mut [f32]) -> Result<()> {
        self.require_flat("read a pixel")?;
        self.require_wrappable(wrap)?;
        let count = i32::try_from(values.len())
            .map_err(|_| Error::InvalidRoi("channel count exceeds i32::MAX".to_owned()))?;
        // SAFETY: the pointer and count describe exactly the caller's slice.
        unsafe {
            sys::imagebuf::imagebuf_getpixel(
                self.inner(),
                x,
                y,
                0,
                values.as_mut_ptr(),
                count,
                wrap.to_sys(),
            );
        }
        let channels = self.channel_count() as usize;
        if values.len() > channels {
            values[channels..].fill(0.0);
        }
        // Checked after the call: the deferred read happens inside it, and a
        // failure leaves the slice holding the untouched allocation.
        if let Err(error) = self.require_filled("read a pixel") {
            values.fill(0.0);
            return Err(error);
        }
        Ok(())
    }

    /// Set every channel of one pixel.
    ///
    /// The coordinate must lie inside the data window: OpenImageIO skips an
    /// outside write silently, which this crate reports instead.
    pub fn set_pixel_at(&mut self, x: i32, y: i32, values: &[f32]) -> Result<()> {
        self.require_flat("write a pixel")?;
        self.require_inside("write a pixel", x, y)?;
        sys::imagebuf::imagebuf_setpixel(self.inner_mut(), x, y, 0, values);
        Ok(())
    }

    /// A bilinearly interpolated pixel at a continuous coordinate, written
    /// into `values`, whose length must equal the channel count.
    pub fn interpolated_pixel_into(
        &self,
        x: f32,
        y: f32,
        wrap: Wrap,
        values: &mut [f32],
    ) -> Result<()> {
        self.require_interpolatable(wrap, values)?;
        // SAFETY: the slice holds exactly the channel count, checked above.
        unsafe {
            sys::imagebuf::imagebuf_interppixel(
                self.inner(),
                x,
                y,
                values.as_mut_ptr(),
                wrap.to_sys(),
            );
        }
        self.finish_point_read(values)
    }

    /// [`ImageBuf::interpolated_pixel_into`] with bicubic interpolation.
    pub fn interpolated_pixel_bicubic_into(
        &self,
        x: f32,
        y: f32,
        wrap: Wrap,
        values: &mut [f32],
    ) -> Result<()> {
        self.require_interpolatable(wrap, values)?;
        // SAFETY: the slice holds exactly the channel count, checked above.
        unsafe {
            sys::imagebuf::imagebuf_interppixel_bicubic(
                self.inner(),
                x,
                y,
                values.as_mut_ptr(),
                wrap.to_sys(),
            );
        }
        self.finish_point_read(values)
    }

    /// A bilinearly interpolated pixel addressed in NDC — `0..1` across the
    /// display window — written into `values`, whose length must equal the
    /// channel count. The display window must have positive size, which
    /// [`ImageBuf::set_full_window`] guarantees for windows set through it.
    pub fn interpolated_pixel_ndc_into(
        &self,
        s: f32,
        t: f32,
        wrap: Wrap,
        values: &mut [f32],
    ) -> Result<()> {
        self.require_interpolatable(wrap, values)?;
        self.require_positive_display("interpolate in NDC")?;
        // SAFETY: the slice holds exactly the channel count, checked above.
        unsafe {
            sys::imagebuf::imagebuf_interppixel_NDC(
                self.inner(),
                s,
                t,
                values.as_mut_ptr(),
                wrap.to_sys(),
            );
        }
        self.finish_point_read(values)
    }

    /// [`ImageBuf::interpolated_pixel_ndc_into`] with bicubic interpolation.
    pub fn interpolated_pixel_bicubic_ndc_into(
        &self,
        s: f32,
        t: f32,
        wrap: Wrap,
        values: &mut [f32],
    ) -> Result<()> {
        self.require_interpolatable(wrap, values)?;
        self.require_positive_display("interpolate in NDC")?;
        // SAFETY: the slice holds exactly the channel count, checked above.
        unsafe {
            sys::imagebuf::imagebuf_interppixel_bicubic_NDC(
                self.inner(),
                s,
                t,
                values.as_mut_ptr(),
                wrap.to_sys(),
            );
        }
        self.finish_point_read(values)
    }

    /// The shared epilogue of the point reads: the deferred file read runs
    /// inside the call, and a failure leaves the output holding the
    /// untouched allocation — error and scrub, as `get_pixels_into` does.
    fn finish_point_read(&self, values: &mut [f32]) -> Result<()> {
        if let Err(error) = self.require_filled("interpolate a pixel") {
            values.fill(0.0);
            return Err(error);
        }
        Ok(())
    }

    /// The shared preconditions of the interpolators: a flat buffer, a wrap
    /// mode this buffer supports, a slice of exactly the channel count, and
    /// a channel count OpenImageIO's per-call stack scratch can hold.
    fn require_interpolatable(&self, wrap: Wrap, values: &[f32]) -> Result<()> {
        self.require_flat("interpolate a pixel")?;
        self.require_wrappable(wrap)?;
        let channels = self.channel_count() as usize;
        if values.len() != channels {
            return Err(Error::BufferLength {
                expected: channels,
                actual: values.len(),
            });
        }
        // The interpolators alloca their scratch from the channel count on
        // OpenImageIO's stack frame; a four-figure channel count is fine, an
        // unbounded one is a stack overflow no catch can reach.
        if channels > 1024 {
            return Err(Error::operation(
                "interpolate a pixel",
                format!("interpolation supports at most 1024 channels, this image has {channels}"),
            ));
        }
        Ok(())
    }

    /// Periodic and mirror wraps divide by the display window's size.
    fn require_wrappable(&self, wrap: Wrap) -> Result<()> {
        if matches!(wrap, Wrap::Periodic | Wrap::Mirror) {
            self.require_positive_display("wrap periodically")?;
        }
        Ok(())
    }

    fn require_positive_display(&self, operation: &'static str) -> Result<()> {
        let spec = self.spec()?;
        // All three axes: OpenImageIO wraps z as well as x and y whenever a
        // point falls outside the data window, and a zero full_depth is an
        // integer division by zero inside wrap_periodic and wrap_mirror.
        let [width, height, depth] = spec.full_dimensions();
        if width == 0 || height == 0 || depth == 0 {
            return Err(Error::operation(
                operation,
                "the display window has a zero-sized axis, which this operation divides by"
                    .to_owned(),
            ));
        }
        Ok(())
    }

    /// Move the data window's origin, carrying the pixels with it.
    ///
    /// Exclusive because OpenImageIO documents spec mutation as not
    /// thread-safe, as are the other metadata setters here.
    pub fn set_origin(&mut self, origin: [i32; 3]) {
        sys::imagebuf::imagebuf_set_origin(self.inner_mut(), origin[0], origin[1], origin[2]);
    }

    /// Set the display (full) window from an origin and a size.
    ///
    /// The size must be positive on every axis: OpenImageIO stores whatever
    /// it is given, and a zero or negative display window later divides the
    /// periodic and mirror wrap modes and the NDC mappings by it.
    pub fn set_full_window(&mut self, origin: [i32; 3], size: [u32; 3]) -> Result<()> {
        let mut end = [0_i32; 3];
        for axis in 0..3 {
            if size[axis] == 0 {
                return Err(Error::InvalidImageSpec(
                    "the display window needs a positive size on every axis".to_owned(),
                ));
            }
            let extent = i32::try_from(size[axis])
                .map_err(|_| Error::InvalidImageSpec("display window too large".to_owned()))?;
            end[axis] = origin[axis].checked_add(extent).ok_or_else(|| {
                Error::InvalidImageSpec("the display window overflows i32".to_owned())
            })?;
        }
        sys::imagebuf::imagebuf_set_full(
            self.inner_mut(),
            origin[0],
            end[0],
            origin[1],
            end[1],
            origin[2],
            end[2],
        );
        Ok(())
    }

    /// Set the display window from a region.
    ///
    /// The crate's [`Roi`] is always defined and non-empty, which is what
    /// keeps OpenImageIO's undefined-region arithmetic out of reach here.
    pub fn set_display_window(&mut self, roi: Roi) {
        let sys_roi = roi.to_sys();
        sys::imagebuf::imagebuf_set_roi_full(self.inner_mut(), &sys_roi);
    }

    /// Record the EXIF-style orientation, 1 through 8.
    pub fn set_orientation(&mut self, orientation: u32) -> Result<()> {
        if !(1..=8).contains(&orientation) {
            return Err(Error::InvalidImageSpec(format!(
                "orientation is EXIF's 1..=8, got {orientation}"
            )));
        }
        sys::imagebuf::imagebuf_set_orientation(self.inner_mut(), orientation as i32);
        Ok(())
    }

    /// Replace this buffer's metadata with a copy of another's, keeping the
    /// pixels and the geometry.
    pub fn copy_metadata(&mut self, src: &ImageBuf) {
        sys::imagebuf::imagebuf_copy_metadata(self.inner_mut(), src.inner());
    }

    /// Merge another buffer's metadata into this one's.
    ///
    /// With `override_existing`, attributes both images carry take the other
    /// image's value; otherwise existing attributes win. A non-empty
    /// `pattern` is a regular expression selecting which attribute names are
    /// merged, and an invalid pattern is an error — OpenImageIO would
    /// otherwise let the regex constructor take the process down.
    pub fn merge_metadata(
        &mut self,
        src: &ImageBuf,
        override_existing: bool,
        pattern: &str,
    ) -> Result<()> {
        let mut error = String::new();
        if !sys::imagebuf::imagebuf_merge_metadata(
            self.inner_mut(),
            src.inner(),
            override_existing,
            pattern,
            &mut error,
        ) {
            return Err(Error::operation("merge metadata", error));
        }
        Ok(())
    }

    /// Whether this buffer carries a thumbnail.
    ///
    /// This asks for the stored thumbnail rather than OpenImageIO's
    /// `has_thumbnail` flag: through 3.1.15, `set_thumbnail` stores the
    /// image without raising the flag (3.1.16 fixed it), so the flag denies
    /// thumbnails attached in memory while the storage tells the truth on
    /// every version.
    pub fn has_thumbnail(&self) -> bool {
        !sys::imagebuf::imagebuf_get_thumbnail(self.inner()).is_null()
    }

    /// An owned copy of the thumbnail this buffer carries, if any.
    pub fn thumbnail(&self) -> Result<Option<ImageBuf>> {
        let shared = sys::imagebuf::imagebuf_get_thumbnail(self.inner());
        let Some(stored) = shared.as_ref() else {
            return Ok(None);
        };
        let mut error = String::new();
        let inner = sys::imagebuf::imagebuf_clone_checked(stored, &mut error);
        if inner.is_null() {
            return Err(Error::operation("copy thumbnail", error));
        }
        Ok(Some(Self { inner }))
    }

    /// Attach a thumbnail to this buffer, to be written alongside it by
    /// formats that store one.
    ///
    /// OpenImageIO stores a copy, using the same failure-swallowing copy
    /// constructor [`ImageBuf::try_clone`] describes, so the stored copy is
    /// checked here and a copy that failed is an error, not a quiet broken
    /// thumbnail.
    pub fn set_thumbnail(&mut self, thumbnail: &ImageBuf) -> Result<()> {
        sys::imagebuf::imagebuf_set_thumbnail(self.inner_mut(), thumbnail.inner());
        let stored = sys::imagebuf::imagebuf_get_thumbnail(self.inner());
        if let Some(stored) = stored.as_ref() {
            if sys::imagebuf::imagebuf_has_error(stored) {
                let message = sys::imagebuf::imagebuf_geterror(stored, false);
                sys::imagebuf::imagebuf_clear_thumbnail(self.inner_mut());
                return Err(Error::operation("set thumbnail", message));
            }
        }
        Ok(())
    }

    /// Remove any thumbnail this buffer carries.
    pub fn clear_thumbnail(&mut self) {
        sys::imagebuf::imagebuf_clear_thumbnail(self.inner_mut());
    }

    /// Copy this buffer, reporting failure instead of handing back a copy
    /// that cannot serve pixels.
    ///
    /// OpenImageIO's copy constructor catches its own allocation failure,
    /// records an error on the copy, and returns it anyway — with the
    /// source's valid-pixels flag still set, so the first read of the broken
    /// copy would reach a division by zero or a null cache inside
    /// OpenImageIO. [`Clone`] uses this and panics on failure, which is the
    /// convention for `Clone` under memory pressure; call this directly to
    /// handle the failure instead.
    pub fn try_clone(&self) -> Result<Self> {
        let mut error = String::new();
        let inner = sys::imagebuf::imagebuf_clone_checked(self.inner(), &mut error);
        if inner.is_null() {
            return Err(Error::operation("copy image buffer", error));
        }
        Ok(Self { inner })
    }

    pub(crate) fn inner(&self) -> &sys::imagebuf::ImageBuf {
        self.inner
            .as_ref()
            .expect("ImageBuf invariant violated: null native pointer")
    }

    pub(crate) fn inner_mut(&mut self) -> std::pin::Pin<&mut sys::imagebuf::ImageBuf> {
        self.inner
            .as_mut()
            .expect("ImageBuf invariant violated: null native pointer")
    }
}

impl Clone for ImageBuf {
    /// Panics when the copy cannot be allocated; use
    /// [`ImageBuf::try_clone`] to handle that as an error instead.
    fn clone(&self) -> Self {
        self.try_clone()
            .expect("copying this image buffer failed; ImageBuf::try_clone reports the reason")
    }
}

impl std::fmt::Debug for ImageBuf {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ImageBuf")
            .field("name", &self.name())
            .field("storage", &self.storage())
            .field("channels", &self.channel_count())
            .finish_non_exhaustive()
    }
}

fn level_index(index: u32) -> Result<i32> {
    i32::try_from(index)
        .map_err(|_| Error::InvalidImageSpec("image level index exceeds i32::MAX".to_owned()))
}

enum_names!("wrap mode", Wrap {
    Default => "default",
    Black => "black",
    Clamp => "clamp",
    Periodic => "periodic",
    Mirror => "mirror",
});

enum_names!("storage kind", Storage {
    Uninitialized => "uninitialized",
    Local => "local",
    App => "app",
    Cache => "cache",
});