oiio 0.3.2

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

use crate::image_spec::element_count;
use crate::{path_to_utf8, pixel, sys, DeepImage, Error, ImageSpec, Pixel, Result, Roi};

/// An open image, either a file or a buffer in memory.
///
/// Field order is load-bearing: Rust drops fields in declaration order, so the
/// reader closes before the proxy it reads through, which in turn drops before
/// the memory that proxy borrows.
pub struct ImageInput {
    inner: cxx::UniquePtr<sys::imageio::ImageInput>,
    _proxy: Option<cxx::UniquePtr<sys::filesystem::IOProxy>>,
    _bytes: Option<Vec<u8>>,
}

// OpenImageIO's position on `ImageInput` is that two threads must not call
// into one concurrently, which forbids `Sync` and says nothing against `Send`:
// a reader is not bound to the thread that opened it. The base class carries a
// `std::recursive_mutex` for callers who want to serialise access themselves,
// and every use of it upstream is a scoped guard inside a single call, so no
// lock is ever held across a return and nothing can be left locked by the
// thread that moves the value away.
//
// The three owned pieces move as a unit. `_bytes` is the Vec an in-memory
// reader was opened over and `_proxy` is the `IOProxy` pointing into it;
// because they are fields of the same struct they travel together, and the
// proxy registers itself nowhere thread-keyed.
//
// `close()` takes `self` by value, which is what keeps the close and the
// destructor on one thread. Keep it that way: it is the reason there is no
// window in which a half-closed reader could be observed from elsewhere.
//
// `Sync` is not claimed and should not be. Besides the concurrency rule above,
// the error channel OpenImageIO fills on failure is
// `static thread_local ErrorHolder` (`strutil.cpp:217`), so a message raised on
// one thread is not readable from another; `take_error` taking `&mut self` is
// what keeps that honest.
//
// Two conditions. Leave `lock`, `unlock` and `try_lock` (`imageio.h:2200-2206`)
// unbound, since a recursive mutex unlocked by a thread that did not lock it is
// undefined behaviour, and if they are ever exposed the guard must itself be
// `!Send`. And note this impl covers every format plugin, because the crate
// cannot choose which reader a file produces: the readers surveyed for
// thread-bound state keep theirs inside a single call, and a reader that held
// state across calls keyed to its creating thread would invalidate this.
unsafe impl Send for ImageInput {}

impl ImageInput {
    /// Open an image file with configuration hints.
    ///
    /// The hint spec's attributes steer the reader before it opens:
    /// `oiio:UnassociatedAlpha` asks for alpha left unassociated,
    /// `oiio:RawColor` suppresses colour conversion in formats that would
    /// apply one, and each format documents its own. The hint spec's
    /// dimensions are ignored; only its attributes matter.
    pub fn from_path_with_config(image_path: &Path, config: &ImageSpec) -> Result<Self> {
        let image_path_str = path_to_utf8(image_path)?;
        let native = config.to_sys()?;
        let Some(native) = native.as_ref() else {
            return Err(Error::InvalidImageSpec(
                "OpenImageIO could not allocate the configuration hints".to_owned(),
            ));
        };
        match sys::imageio::imageinput_open_with_config(image_path_str, native) {
            Ok(imageinput) if !imageinput.is_null() => Ok(Self {
                inner: imageinput,
                _proxy: None,
                _bytes: None,
            }),
            Ok(_) => {
                let message = if sys::imageio::has_error() {
                    sys::imageio::get_error(true)
                } else {
                    "OpenImageIO did not provide an error message".to_owned()
                };
                Err(Error::OpenImage {
                    path: image_path.to_path_buf(),
                    message,
                })
            }
            Err(exception) => Err(Error::OpenImage {
                path: image_path.to_path_buf(),
                message: exception.what().to_owned(),
            }),
        }
    }

    /// Open an image file.
    pub fn from_path(image_path: &Path) -> Result<Self> {
        let image_path_str = path_to_utf8(image_path)?;

        match sys::imageio::imageinput_open_without_config(image_path_str) {
            Ok(imageinput) if !imageinput.is_null() => Ok(Self {
                inner: imageinput,
                _proxy: None,
                _bytes: None,
            }),
            Ok(_) => {
                let message = if sys::imageio::has_error() {
                    sys::imageio::get_error(true)
                } else {
                    "OpenImageIO did not provide an error message".to_owned()
                };
                Err(Error::OpenImage {
                    path: image_path.to_path_buf(),
                    message,
                })
            }
            Err(error) => Err(Error::OpenImage {
                path: image_path.to_path_buf(),
                message: error.to_string(),
            }),
        }
    }

    /// Read an image already held in memory, without touching the filesystem.
    ///
    /// `name_hint` is not opened; it only tells OpenImageIO which reader to
    /// use, so its extension must match the bytes. The buffer is moved into
    /// the reader and released when the reader is dropped.
    ///
    /// ```
    /// use oiio::{ImageInput, ImageOutput, ImageSpec, PixelFormat};
    ///
    /// # fn main() -> oiio::Result<()> {
    /// let spec = ImageSpec::new(4, 4, 3, PixelFormat::F32)?;
    /// let pixels = vec![0.5_f32; spec.element_count()?];
    ///
    /// let mut output = ImageOutput::to_memory("image.exr", &spec)?;
    /// output.write_image(&pixels)?;
    /// let encoded = output.close_into_bytes()?;
    ///
    /// let mut input = ImageInput::from_memory("image.exr", encoded)?;
    /// let mut decoded = vec![0.0_f32; spec.element_count()?];
    /// input.read_image_into(&mut decoded)?;
    /// input.close()?;
    ///
    /// assert_eq!(decoded, pixels);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_memory(name_hint: &str, bytes: Vec<u8>) -> Result<Self> {
        // The proxy borrows the buffer, so `bytes` must outlive it. Moving the
        // Vec afterwards moves only its header, never the heap allocation the
        // proxy points at.
        // SAFETY: `bytes` is moved into the returned value below and dropped
        // after both the reader and the proxy.
        let mut proxy = unsafe { sys::filesystem::ioproxy_memreader_new(&bytes) };
        let Some(proxy_ref) = proxy.as_mut() else {
            return Err(Self::memory_error(
                name_hint,
                "OpenImageIO could not allocate a memory proxy".to_owned(),
            ));
        };

        // SAFETY: the proxy outlives the reader; both are owned by the value
        // returned here, and the reader is declared first so it drops first.
        let inner = unsafe {
            let proxy_ptr = proxy_ref.get_unchecked_mut() as *mut sys::filesystem::IOProxy;
            sys::imageio::imageinput_open_with_ioproxy(name_hint, proxy_ptr)
        };
        if inner.is_null() {
            return Err(Self::memory_error(name_hint, global_error()));
        }

        Ok(Self {
            inner,
            _proxy: Some(proxy),
            _bytes: Some(bytes),
        })
    }

    /// Return the input plugin's format name.
    pub fn format_name(&self) -> &str {
        sys::imageio::imageinput_format_name(self.inner())
    }

    fn memory_error(name_hint: &str, message: String) -> Error {
        Error::OpenImage {
            path: PathBuf::from(name_hint),
            message: if message.is_empty() {
                "OpenImageIO did not provide an error message".to_owned()
            } else {
                message
            },
        }
    }

    /// Return an owned description of the currently selected image.
    pub fn image_spec(&self) -> Result<ImageSpec> {
        ImageSpec::from_sys(sys::imageio::imageinput_spec(self.inner()))
    }

    /// Return an owned description of a subimage and mip level.
    pub fn image_spec_at(&mut self, subimage: u32, mip_level: u32) -> Result<ImageSpec> {
        let subimage_i32 = level_index(subimage)?;
        let mip_level_i32 = level_index(mip_level)?;
        let spec = sys::imageio::imageinput_spec_subimage_miplevel(
            self.inner_mut(),
            subimage_i32,
            mip_level_i32,
        );
        let Some(spec) = spec.as_ref() else {
            let _ = sys::imageio::imageinput_geterror(self.inner_mut());
            return Err(Error::InvalidImageLevel {
                subimage,
                mip_level,
            });
        };
        if !sys::imageio::imagespec_valid(spec) {
            let _ = sys::imageio::imageinput_geterror(self.inner_mut());
            return Err(Error::InvalidImageLevel {
                subimage,
                mip_level,
            });
        }
        ImageSpec::from_sys(spec)
    }

    /// Read all channels of the base image into a contiguous scalar buffer.
    ///
    /// The buffer length must exactly equal
    /// `width * height * depth * channels`. No call into C++ is made if the
    /// length is wrong or the multiplication overflows.
    pub fn read_image_into<T: Pixel>(&mut self, pixels: &mut [T]) -> Result<()> {
        self.read_image_into_at(0, 0, pixels)
    }

    /// Read all channels of a subimage and mip level into a contiguous buffer.
    pub fn read_image_into_at<T: Pixel>(
        &mut self,
        subimage: u32,
        mip_level: u32,
        pixels: &mut [T],
    ) -> Result<()> {
        let spec = self.image_spec_at(subimage, mip_level)?;
        if spec.is_deep() {
            return Err(Error::UnsupportedDeepImage);
        }
        let expected = spec.element_count()?;
        validate_buffer_len(expected, pixels.len())?;

        let channel_end = i32::try_from(spec.channel_count()).map_err(|_| {
            Error::InvalidImageSpec("channel count does not fit in an i32".to_owned())
        })?;
        // SAFETY: Pixel is sealed to initialized scalar layouts whose type,
        // alignment, element count, and byte extent were validated above.
        let succeeded = unsafe {
            sys::imageio::imageinput_read_image_span(
                self.inner_mut(),
                level_index(subimage)?,
                level_index(mip_level)?,
                0,
                channel_end,
                pixel::type_desc::<T>(),
                pixel::as_bytes_mut(pixels),
            )
        };
        if succeeded {
            Ok(())
        } else {
            Err(self.take_error("read image"))
        }
    }

    /// Read part of the base image into a contiguous scalar buffer.
    ///
    /// See [`ImageInput::read_region_into_at`].
    pub fn read_region_into<T: Pixel>(&mut self, roi: Roi, pixels: &mut [T]) -> Result<()> {
        self.read_region_into_at(0, 0, roi, pixels)
    }

    /// Read part of a subimage and mip level into a contiguous buffer.
    ///
    /// The region selects pixels and channels, so this is also how a channel
    /// subset is read: start from [`ImageSpec::data_window`] and narrow it.
    ///
    /// ```no_run
    /// use oiio::ImageInput;
    /// use std::path::Path;
    ///
    /// # fn main() -> oiio::Result<()> {
    /// let mut input = ImageInput::from_path(Path::new("image.exr"))?;
    /// let spec = input.image_spec()?;
    ///
    /// // The first three channels of the top 64 scanlines.
    /// let roi = spec.data_window()?.with_y(0..64)?.with_channels(0..3)?;
    /// let mut pixels = vec![0.0_f32; roi.element_count()?];
    /// input.read_region_into(roi, &mut pixels)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// How the region may be shaped depends on how the file stores pixels,
    /// because that is what OpenImageIO itself can address:
    ///
    /// - A tiled image is read tile by tile, so each axis must start on the
    ///   tile grid and either end on it or at the edge of the data window.
    /// - A scanline image is read a whole row at a time, so the x range must
    ///   cover the full width and the region must be a single z slice.
    ///
    /// For arbitrary regions of a tiled file, use
    /// [`ImageCache::get_pixels_into`](crate::ImageCache::get_pixels_into),
    /// which assembles them from tiles.
    pub fn read_region_into_at<T: Pixel>(
        &mut self,
        subimage: u32,
        mip_level: u32,
        roi: Roi,
        pixels: &mut [T],
    ) -> Result<()> {
        let spec = self.image_spec_at(subimage, mip_level)?;
        if spec.is_deep() {
            return Err(Error::UnsupportedDeepImage);
        }
        roi.validate_within(&spec)?;
        validate_buffer_len(roi.element_count()?, pixels.len())?;

        let subimage_i32 = level_index(subimage)?;
        let mip_level_i32 = level_index(mip_level)?;
        let channels = roi.channels();
        let channel_begin = level_index(channels.start)?;
        let channel_end = level_index(channels.end)?;
        let origin = spec.origin();
        let dimensions = spec.dimensions();

        let succeeded = if spec.is_tiled() {
            let [tile_width, tile_height, tile_depth] = spec.tile_dimensions();
            validate_tile_alignment("x", &roi.x(), origin[0], dimensions[0], tile_width)?;
            validate_tile_alignment("y", &roi.y(), origin[1], dimensions[1], tile_height)?;
            validate_tile_alignment("z", &roi.z(), origin[2], dimensions[2], tile_depth.max(1))?;

            // SAFETY: Pixel is sealed to initialized scalar layouts, and the
            // shim re-derives the layout from this level's own dimensions.
            unsafe {
                sys::imageio::imageinput_read_tiles_span(
                    self.inner_mut(),
                    subimage_i32,
                    mip_level_i32,
                    roi.x().start,
                    roi.x().end,
                    roi.y().start,
                    roi.y().end,
                    roi.z().start,
                    roi.z().end,
                    channel_begin,
                    channel_end,
                    pixel::type_desc::<T>(),
                    pixel::as_bytes_mut(pixels),
                )
            }
        } else {
            let width_end = i64::from(origin[0]) + i64::from(dimensions[0]);
            if i64::from(roi.x().start) != i64::from(origin[0])
                || i64::from(roi.x().end) != width_end
            {
                return Err(Error::InvalidRegion {
                    axis: "x",
                    message: format!(
                        "a scanline image is read a whole row at a time, so the x range must \
                         cover the full width {}..{width_end}",
                        origin[0]
                    ),
                });
            }
            if roi.depth() != 1 {
                return Err(Error::InvalidRegion {
                    axis: "z",
                    message: "a scanline image is read one z slice at a time".to_owned(),
                });
            }

            // SAFETY: as in the tiled branch.
            unsafe {
                sys::imageio::imageinput_read_scanlines_span(
                    self.inner_mut(),
                    subimage_i32,
                    mip_level_i32,
                    roi.y().start,
                    roi.y().end,
                    roi.z().start,
                    channel_begin,
                    channel_end,
                    pixel::type_desc::<T>(),
                    pixel::as_bytes_mut(pixels),
                )
            }
        };

        if succeeded {
            Ok(())
        } else {
            Err(self.take_error("read region"))
        }
    }

    /// Read a deep image, where each pixel holds a list of samples.
    ///
    /// The contiguous pixel API refuses deep files, because a fixed number of
    /// values per pixel cannot describe them. This reads one instead.
    pub fn read_deep_image(&mut self) -> Result<DeepImage> {
        self.read_deep_image_at(0, 0)
    }

    /// Read a deep subimage and mip level.
    pub fn read_deep_image_at(&mut self, subimage: u32, mip_level: u32) -> Result<DeepImage> {
        let spec = self.image_spec_at(subimage, mip_level)?;
        if !spec.is_deep() {
            return Err(Error::operation(
                "read deep image",
                "this image is not deep; use read_image_into".to_owned(),
            ));
        }

        let mut deep = sys::deepdata::deepdata_default();
        let Some(pinned) = deep.as_mut() else {
            return Err(Error::operation(
                "read deep image",
                "OpenImageIO could not allocate deep data".to_owned(),
            ));
        };
        let mut error = String::new();
        let succeeded = sys::imageio::imageinput_read_native_deep_image(
            self.inner_mut(),
            level_index(subimage)?,
            level_index(mip_level)?,
            pinned,
            &mut error,
        );
        if !succeeded {
            // A non-empty `error` is the C++ boundary reporting an exception
            // it caught, which OpenImageIO never got to record. Anything else
            // is an ordinary failure on its own error channel.
            if !error.is_empty() {
                return Err(Error::operation("read deep image", error));
            }
            return Err(self.take_error("read deep image"));
        }

        DeepImage::from_parts(deep, &spec)
    }

    /// Read the base image in its declared native channel formats.
    ///
    /// Each channel keeps its declared storage format — the half/float mix
    /// a multi-AOV EXR carries — packed per pixel in channel order, with
    /// [`ImageSpec::native_pixel_bytes`] as the stride. For most formats
    /// that is byte-exact with the file's pixel data; formats packing
    /// samples below a byte or between byte sizes (1/2/4/12-bit TIFF,
    /// sub-byte PNM) declare the next whole type as native and hand back
    /// unpacked, rescaled samples, so the guarantee is the *declared*
    /// formats, not the on-disk bit packing. This is the read for
    /// value-preserving transcoding or decoding values yourself; for
    /// numbers to compute with, [`ImageInput::read_image_into`] converts
    /// instead.
    pub fn read_native_image(&mut self) -> Result<Vec<u8>> {
        self.read_native_image_at(0, 0)
    }

    /// Read a subimage and mip level exactly as the file stores it; see
    /// [`ImageInput::read_native_image`].
    pub fn read_native_image_at(&mut self, subimage: u32, mip_level: u32) -> Result<Vec<u8>> {
        const OPERATION: &str = "read native image";
        let spec = self.image_spec_at(subimage, mip_level)?;
        if spec.is_deep() {
            return Err(Error::UnsupportedDeepImage);
        }
        let expected = spec
            .pixel_count()?
            .checked_mul(spec.native_pixel_bytes()?)
            .ok_or_else(|| Error::InvalidImageSpec("the image's byte size overflows".to_owned()))?;

        let mut bytes = vec![0_u8; expected];
        let mut error = String::new();
        let succeeded = sys::imageio::imageinput_read_native_image_bytes(
            self.inner_mut(),
            level_index(subimage)?,
            level_index(mip_level)?,
            &mut bytes,
            &mut error,
        );
        if succeeded {
            Ok(bytes)
        } else {
            Err(Error::operation(OPERATION, error))
        }
    }

    /// Read a contiguous band of scanlines of a deep subimage and mip level.
    ///
    /// The returned deep image is the band: as wide as the data window, as
    /// tall as `y`, its origin at the band's top-left corner, every channel
    /// included. Bands may be read in any order.
    ///
    /// All channels are always read. OpenImageIO's channel-subset path pairs
    /// each kept channel's data with the wrong channel's name, so this crate
    /// does not offer it for deep reads.
    pub fn read_deep_scanlines_at(
        &mut self,
        subimage: u32,
        mip_level: u32,
        y: Range<i32>,
    ) -> Result<DeepImage> {
        const OPERATION: &str = "read deep scanlines";
        let spec = self.require_deep_spec(OPERATION, subimage, mip_level)?;
        if spec.is_tiled() {
            return Err(Error::InvalidImageSpec(
                "this file is tiled; use read_deep_tiles_at".to_owned(),
            ));
        }
        if spec.dimensions()[2] != 1 {
            return Err(Error::InvalidImageSpec(
                "scanline reads require a two-dimensional image".to_owned(),
            ));
        }
        let rows = validate_axis("y", &y, spec.origin()[1], spec.dimensions()[1])?;

        let mut deep = sys::deepdata::deepdata_default();
        let Some(pinned) = deep.as_mut() else {
            return Err(Error::operation(
                OPERATION,
                "OpenImageIO could not allocate deep data".to_owned(),
            ));
        };
        let mut error = String::new();
        let succeeded = sys::imageio::imageinput_read_native_deep_scanlines(
            self.inner_mut(),
            level_index(subimage)?,
            level_index(mip_level)?,
            y.start,
            y.end,
            0,
            0,
            spec.channel_count() as i32,
            pinned,
            &mut error,
        );
        if !succeeded {
            if !error.is_empty() {
                return Err(Error::operation(OPERATION, error));
            }
            return Err(self.take_error(OPERATION));
        }

        let band = ImageSpec::new(
            spec.dimensions()[0],
            rows,
            spec.channel_count(),
            spec.format(),
        )?
        .with_origin([spec.origin()[0], y.start, spec.origin()[2]]);
        DeepImage::from_parts(deep, &band)
    }

    /// Read a rectangular block of whole tiles of a deep subimage and mip
    /// level.
    ///
    /// Each range must start on a tile boundary and either end on one or end
    /// at the edge of the data window — OpenEXR locates the block by tile
    /// index, so a misaligned range would place its samples at rows and
    /// columns outside the block. The returned deep image is the block, its
    /// origin at the block's corner, every channel included (as with
    /// [`ImageInput::read_deep_scanlines_at`], OpenImageIO's channel-subset
    /// path mislabels channels, so this crate does not offer it).
    pub fn read_deep_tiles_at(
        &mut self,
        subimage: u32,
        mip_level: u32,
        x: Range<i32>,
        y: Range<i32>,
        z: Range<i32>,
    ) -> Result<DeepImage> {
        const OPERATION: &str = "read deep tiles";
        let spec = self.require_deep_spec(OPERATION, subimage, mip_level)?;
        if !spec.is_tiled() {
            return Err(Error::InvalidImageSpec(
                "tile reads require a tiled file; use read_deep_scanlines_at".to_owned(),
            ));
        }
        let [tile_width, tile_height, tile_depth] = spec.tile_dimensions();
        let origin = spec.origin();
        let dimensions = spec.dimensions();
        let width = validate_axis("x", &x, origin[0], dimensions[0])?;
        let height = validate_axis("y", &y, origin[1], dimensions[1])?;
        let depth = validate_axis("z", &z, origin[2], dimensions[2])?;
        validate_tile_alignment("x", &x, origin[0], dimensions[0], tile_width)?;
        validate_tile_alignment("y", &y, origin[1], dimensions[1], tile_height)?;
        validate_tile_alignment("z", &z, origin[2], dimensions[2], tile_depth.max(1))?;

        let mut deep = sys::deepdata::deepdata_default();
        let Some(pinned) = deep.as_mut() else {
            return Err(Error::operation(
                OPERATION,
                "OpenImageIO could not allocate deep data".to_owned(),
            ));
        };
        let mut error = String::new();
        let succeeded = sys::imageio::imageinput_read_native_deep_tiles(
            self.inner_mut(),
            level_index(subimage)?,
            level_index(mip_level)?,
            x.start,
            x.end,
            y.start,
            y.end,
            z.start,
            z.end,
            0,
            spec.channel_count() as i32,
            pinned,
            &mut error,
        );
        if !succeeded {
            if !error.is_empty() {
                return Err(Error::operation(OPERATION, error));
            }
            return Err(self.take_error(OPERATION));
        }

        let band = ImageSpec::new(width, height, spec.channel_count(), spec.format())?
            .with_depth(depth)?
            .with_origin([x.start, y.start, z.start]);
        DeepImage::from_parts(deep, &band)
    }

    /// The deep region readers' shared precondition: the subimage exists and
    /// is deep.
    fn require_deep_spec(
        &mut self,
        operation: &'static str,
        subimage: u32,
        mip_level: u32,
    ) -> Result<ImageSpec> {
        let spec = self.image_spec_at(subimage, mip_level)?;
        if !spec.is_deep() {
            return Err(Error::operation(
                operation,
                "this image is not deep; use read_image_into".to_owned(),
            ));
        }
        Ok(spec)
    }

    /// Close the file and report any delayed format or I/O errors.
    ///
    /// Dropping an `ImageInput` without calling this method still releases
    /// all native resources, but cannot report close errors.
    pub fn close(mut self) -> Result<()> {
        if sys::imageio::imageinput_close(self.inner_mut()) {
            Ok(())
        } else {
            Err(self.take_error("close image"))
        }
    }

    /// Get the current thread count.
    pub fn threads(&self) -> i32 {
        sys::imageio::imageinput_threads(self.inner())
    }

    /// Set the thread count. Zero requests OpenImageIO's default.
    pub fn set_threads(&mut self, threads: i32) {
        sys::imageio::imageinput_set_threads(self.inner_mut(), threads);
    }

    fn inner(&self) -> &sys::imageio::ImageInput {
        self.inner
            .as_ref()
            .expect("ImageInput invariant violated: null native pointer")
    }

    /// Whether this reader's format supports a named feature, such as
    /// `"mipmap"`, `"multiimage"`, `"exif"` or `"ioproxy"`.
    pub fn supports(&self, feature: &str) -> bool {
        sys::imageio::imageinput_supports(self.inner(), feature)
    }

    /// Whether another file appears readable by this reader's format.
    ///
    /// Formats with a cheap header check answer from the candidate's
    /// magic bytes; the rest fully open and close it. Either way the probe
    /// runs on a throwaway reader of the same format — OpenImageIO's own
    /// fallback would re-open and close *this* reader, silently
    /// invalidating it, which is why the shim never lets it near the live
    /// one.
    pub fn is_valid_file(&self, image_path: &Path) -> Result<bool> {
        let filename = path_to_utf8(image_path)?;
        Ok(sys::imageio::imageinput_valid_file(self.inner(), filename))
    }

    /// The raw reader handle, for wrappers whose shim takes the native
    /// pointer (`ImageOutput::copy_image_from`). `pub(crate)` so the pointer
    /// never crosses the crate boundary.
    pub(crate) fn native_mut(&mut self) -> std::pin::Pin<&mut sys::imageio::ImageInput> {
        self.inner_mut()
    }

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

    fn take_error(&mut self, operation: &'static str) -> Error {
        Error::operation(
            operation,
            sys::imageio::imageinput_geterror(self.inner_mut()),
        )
    }
}

/// An image file open for writing.
///
/// A writer is always open: [`ImageOutput::create`] selects the plugin from
/// the file name and opens the file in one step, so there is no state in which
/// a write can be attempted against an unopened file.
///
/// ```no_run
/// use oiio::{f16, ImageOutput, ImageSpec, PixelFormat};
/// use std::path::Path;
///
/// # fn main() -> oiio::Result<()> {
/// let spec = ImageSpec::new(64, 64, 3, PixelFormat::F16)?;
/// let pixels = vec![f16::ZERO; spec.element_count()?];
///
/// let mut output = ImageOutput::create(Path::new("out.exr"), &spec)?;
/// output.write_image(&pixels)?;
/// output.close()?;
/// # Ok(())
/// # }
/// ```
pub struct ImageOutput {
    inner: cxx::UniquePtr<sys::imageio::ImageOutput>,
    path: PathBuf,
    spec: ImageSpec,
    /// The next row [`ImageOutput::write_scanlines`] will accept, for formats
    /// that will only take them in order. See that method.
    next_scanline: i32,
    /// Present only for in-memory writers. Declared last so it drops after
    /// the writer that fills it.
    proxy: Option<cxx::UniquePtr<sys::filesystem::IOProxy>>,
}

// The same reasoning as `ImageInput`, with one difference that matters. A
// writer carries buffered state and a scanline cursor, and several formats
// will only take rows in order, which is why this type tracks `next_scanline`
// itself. None of that state is bound to a thread: it is members of the writer
// and of this struct, and they move together. The destructor flushes and
// closes, and flushing from a thread other than the one that opened the file
// is no different from flushing late on the same thread.
//
// `Sync` is not claimed. The whole argument above leans on no `&self` path
// reaching the writer's buffered state, the scanline cursor, or the error
// channel. The FFI declaration `imageoutput_geterror(imageoutput:
// &ImageOutput, clear: bool)` is a shared reference at the sys layer, so that
// property is enforced here and only here, by `take_error` taking `&mut self`.
// Adding a `&self` accessor that reaches any of those would break this impl.
//
// As with `ImageInput`, this covers every writer plugin, because the crate
// does not choose which one a filename produces.
unsafe impl Send for ImageOutput {}

impl ImageOutput {
    /// Record the specification the file was actually opened with.
    ///
    /// Not the caller's: `ImageOutput::check_open` rewrites it during open. It
    /// zeroes the origin for any format that does not report `origin`, fills
    /// the display window in from the data window, raises a zero depth to one,
    /// and drops per-channel formats that match the overall one. A caller who
    /// set an origin a PNG cannot carry should be able to see that it is gone,
    /// and the range checks here have to agree with the ones the shim makes
    /// against this same spec.
    fn adopt_open_spec(&mut self, fallback: &ImageSpec) {
        self.spec = ImageSpec::from_sys(sys::imageio::imageoutput_spec(self.inner()))
            .unwrap_or_else(|_| fallback.clone());
        // A fresh image, so the scanline cursor goes back to the top of its
        // data window.
        self.next_scanline = self.spec.origin()[1];
    }

    /// Create and open an image file described by `spec`.
    ///
    /// The output plugin is chosen from the file name's extension. The file is
    /// truncated if it already exists.
    pub fn create(image_path: &Path, spec: &ImageSpec) -> Result<Self> {
        let mut output = Self::open_plugin(image_path)?;
        let native_spec = spec.to_sys()?;
        Self::open_native(
            output.inner_mut(),
            path_to_utf8(image_path)?,
            &native_spec,
            sys::imageio::OpenMode::Create,
        )
        .map_err(|message| Error::OpenImage {
            path: image_path.to_path_buf(),
            message,
        })?;

        output.path = image_path.to_path_buf();
        output.adopt_open_spec(spec);
        Ok(output)
    }

    /// Create and open a multi-part file, declaring every subimage up front.
    ///
    /// Some formats — OpenEXR among them — must know all subimages when the
    /// file is opened and reject [`ImageOutput::append_subimage`]. After this
    /// call the writer is positioned on the first subimage; advance with
    /// [`ImageOutput::append_subimage`], passing the same specifications in
    /// the same order.
    pub fn create_multi_subimage(image_path: &Path, specs: &[ImageSpec]) -> Result<Self> {
        let Some(first) = specs.first() else {
            return Err(Error::InvalidImageSpec(
                "a multi-part file needs at least one subimage".to_owned(),
            ));
        };

        let mut native_specs = sys::imageio::imagespec_vector_new();
        for spec in specs {
            let native_spec = spec.to_sys()?;
            let (Some(list), Some(native_spec)) = (native_specs.as_mut(), native_spec.as_ref())
            else {
                return Err(Error::InvalidImageSpec(
                    "OpenImageIO could not allocate an image specification".to_owned(),
                ));
            };
            sys::imageio::imagespec_vector_push(list, native_spec);
        }

        let mut output = Self::open_plugin(image_path)?;
        let path_str = path_to_utf8(image_path)?;
        let opened =
            sys::imageio::imageoutput_open_specs(output.inner_mut(), path_str, &native_specs);
        if !opened {
            let message = sys::imageio::imageoutput_geterror(output.inner(), true);
            return Err(Error::OpenImage {
                path: image_path.to_path_buf(),
                message: if message.is_empty() {
                    "OpenImageIO did not provide an error message".to_owned()
                } else {
                    message
                },
            });
        }

        output.path = image_path.to_path_buf();
        output.adopt_open_spec(first);
        Ok(output)
    }

    /// Write an image into memory instead of a file.
    ///
    /// `name_hint` is never created on disk; it only selects the writer, so
    /// its extension decides the encoding. Finish with
    /// [`ImageOutput::close_into_bytes`] to take the encoded bytes.
    ///
    /// Not every format can write to memory — those that cannot are reported
    /// here rather than at close time.
    pub fn to_memory(name_hint: &str, spec: &ImageSpec) -> Result<Self> {
        let mut proxy = sys::filesystem::ioproxy_vecoutput_new();
        let Some(proxy_ref) = proxy.as_mut() else {
            return Err(Error::CreateImage {
                path: PathBuf::from(name_hint),
                message: "OpenImageIO could not allocate a memory proxy".to_owned(),
            });
        };

        // SAFETY: the proxy is owned by the value returned here and is
        // declared after the writer, so the writer drops first.
        let inner = unsafe {
            let proxy_ptr = proxy_ref.get_unchecked_mut() as *mut sys::filesystem::IOProxy;
            sys::imageio::imageoutput_create(name_hint, proxy_ptr, "")
        };
        if inner.is_null() {
            return Err(Error::CreateImage {
                path: PathBuf::from(name_hint),
                message: global_error(),
            });
        }

        let mut output = Self {
            inner,
            path: PathBuf::from(name_hint),
            spec: spec.clone(),
            next_scanline: spec.origin()[1],
            proxy: Some(proxy),
        };
        if !output.supports("ioproxy") {
            return Err(Error::CreateImage {
                path: PathBuf::from(name_hint),
                message: format!("the {} writer cannot write to memory", output.format_name()),
            });
        }

        let native_spec = spec.to_sys()?;
        Self::open_native(
            output.inner_mut(),
            name_hint,
            &native_spec,
            sys::imageio::OpenMode::Create,
        )
        .map_err(|message| Error::OpenImage {
            path: PathBuf::from(name_hint),
            message,
        })?;
        output.adopt_open_spec(spec);
        Ok(output)
    }

    /// Finish an in-memory write and take the encoded bytes.
    ///
    /// Returns [`Error::Operation`] if this writer targets a file, since there
    /// are no bytes to hand back; use [`ImageOutput::close`] for those.
    pub fn close_into_bytes(mut self) -> Result<Vec<u8>> {
        if self.proxy.is_none() {
            return Err(Error::operation(
                "take encoded bytes",
                "this writer targets a file, not memory".to_owned(),
            ));
        }
        let succeeded = sys::imageio::imageoutput_close(self.inner_mut());
        self.check("close image", succeeded)?;

        let proxy = self.proxy.as_ref().expect("checked above");
        let proxy_ref = proxy.as_ref().ok_or_else(|| {
            Error::operation(
                "take encoded bytes",
                "the memory proxy was released early".to_owned(),
            )
        })?;
        Ok(sys::filesystem::ioproxy_vecoutput_bytes(proxy_ref))
    }

    /// Ask whether the output plugin for `image_path` supports a feature,
    /// without creating the file.
    ///
    /// Features are OpenImageIO's own names, such as `"tiles"`,
    /// `"mipmap"`, `"multiimage"`, or `"deepdata"`.
    pub fn plugin_supports(image_path: &Path, feature: &str) -> Result<bool> {
        Ok(Self::open_plugin(image_path)?.supports(feature))
    }

    /// Return the output plugin's format name.
    pub fn format_name(&self) -> &str {
        sys::imageio::imageoutput_format_name(self.inner())
    }

    /// Whether the open plugin supports a named feature.
    pub fn supports(&self, feature: &str) -> bool {
        sys::imageio::imageoutput_supports(self.inner(), feature) != 0
    }

    /// The specification the file is currently open with.
    pub fn spec(&self) -> &ImageSpec {
        &self.spec
    }

    /// Write every pixel of the current subimage and mip level.
    ///
    /// The buffer length must exactly equal
    /// `width * height * depth * channels`. Values are converted to the
    /// specification's pixel format by OpenImageIO.
    pub fn write_image<T: Pixel>(&mut self, pixels: &[T]) -> Result<()> {
        self.reject_deep()?;
        let expected = self.spec.element_count()?;
        validate_buffer_len(expected, pixels.len())?;

        // SAFETY: Pixel is sealed to initialized scalar layouts, and the shim
        // re-derives the layout from the open specification before writing.
        let succeeded = unsafe {
            sys::imageio::imageoutput_write_image_span(
                self.inner_mut(),
                pixel::type_desc::<T>(),
                pixel::as_bytes(pixels),
            )
        };
        self.check("write image", succeeded)?;
        // The whole subimage is written now; advancing the scanline cursor
        // makes a later write_scanlines or write_to refuse with this crate's
        // message instead of failing format-dependently inside the writer.
        self.mark_whole_subimage_written();
        Ok(())
    }

    /// Write a contiguous range of scanlines of a two-dimensional image.
    ///
    /// The buffer length must exactly equal
    /// `width * rows * channels`, where `rows` is the length of `y`.
    ///
    /// Unless the format reports the `random_access` feature, rows must be
    /// written in order: the first call starts at the top of the data window
    /// and each one continues where the last ended. This is not a limitation of
    /// this crate but of the formats. OpenEXR's scanline writer computes a
    /// "virtual framebuffer" base by biasing the caller's pointer backwards by
    /// the requested row, then hands it to a writer that keeps its own cursor
    /// starting at the top of the data window and only ever advancing. Ask it
    /// to write rows 512..1024 first and it reads 512 scanlines *before* the
    /// buffer. `supports("random_access")` is how OpenImageIO publishes the
    /// difference. For EXR it is true only for tiled files with a random
    /// line order; several formats that buffer the whole image before
    /// writing — DPX, FITS, GIF, RLA and WebP among them — advertise it
    /// unconditionally, and genuinely accept rows in any order.
    pub fn write_scanlines<T: Pixel>(&mut self, y: Range<i32>, pixels: &[T]) -> Result<()> {
        self.reject_deep()?;
        if !self.supports("random_access") && y.start != self.next_scanline {
            return Err(Error::InvalidRegion {
                axis: "y",
                message: format!(
                    "this format writes scanlines in order: the next row is {}, not {}",
                    self.next_scanline, y.start
                ),
            });
        }
        if self.spec.dimensions()[2] != 1 {
            return Err(Error::InvalidImageSpec(
                "scanline writes require a two-dimensional image".to_owned(),
            ));
        }
        let rows = self.validate_axis("y", &y, self.spec.origin()[1], self.spec.dimensions()[1])?;
        let expected = element_count([self.spec.dimensions()[0], rows, self.spec.channel_count()])?;
        validate_buffer_len(expected, pixels.len())?;

        // SAFETY: as in `write_image`.
        let succeeded = unsafe {
            sys::imageio::imageoutput_write_scanlines_span(
                self.inner_mut(),
                y.start,
                y.end,
                pixel::type_desc::<T>(),
                pixel::as_bytes(pixels),
            )
        };
        self.check("write scanlines", succeeded)?;
        self.next_scanline = y.end;
        Ok(())
    }

    /// Write a rectangular block of whole tiles.
    ///
    /// Each range must start on a tile boundary and either end on one or end
    /// at the edge of the data window. The buffer length must exactly equal
    /// the number of scalar values the block covers.
    pub fn write_tiles<T: Pixel>(
        &mut self,
        x: Range<i32>,
        y: Range<i32>,
        z: Range<i32>,
        pixels: &[T],
    ) -> Result<()> {
        self.reject_deep()?;
        let [tile_width, tile_height, tile_depth] = self.spec.tile_dimensions();
        if !self.spec.is_tiled() {
            return Err(Error::InvalidImageSpec(
                "tile writes require a specification with a tile size".to_owned(),
            ));
        }

        let origin = self.spec.origin();
        let dimensions = self.spec.dimensions();
        let width = self.validate_axis("x", &x, origin[0], dimensions[0])?;
        let height = self.validate_axis("y", &y, origin[1], dimensions[1])?;
        let depth = self.validate_axis("z", &z, origin[2], dimensions[2])?;
        validate_tile_alignment("x", &x, origin[0], dimensions[0], tile_width)?;
        validate_tile_alignment("y", &y, origin[1], dimensions[1], tile_height)?;
        validate_tile_alignment("z", &z, origin[2], dimensions[2], tile_depth.max(1))?;

        let expected = element_count([width, height, depth, self.spec.channel_count()])?;
        validate_buffer_len(expected, pixels.len())?;

        // SAFETY: as in `write_image`.
        let succeeded = unsafe {
            sys::imageio::imageoutput_write_tiles_span(
                self.inner_mut(),
                x.start,
                x.end,
                y.start,
                y.end,
                z.start,
                z.end,
                pixel::type_desc::<T>(),
                pixel::as_bytes(pixels),
            )
        };
        self.check("write tiles", succeeded)?;
        // Tiles touched this subimage; conservatively mark it written so a
        // later write_to refuses rather than interleaving format-dependently.
        self.mark_whole_subimage_written();
        Ok(())
    }

    /// Write a deep image.
    ///
    /// The writer must have been opened with a specification marked deep, and
    /// the image must match the size and channels it declared.
    pub fn write_deep_image(&mut self, deep: &DeepImage) -> Result<()> {
        if !self.spec.is_deep() {
            return Err(Error::operation(
                "write deep image",
                "this writer was opened for flat pixels; see ImageSpec::as_deep".to_owned(),
            ));
        }
        let dimensions = self.spec.dimensions();
        if deep.dimensions() != dimensions {
            return Err(Error::InvalidImageSpec(format!(
                "the deep image is {:?} but the writer expects {dimensions:?}",
                deep.dimensions()
            )));
        }
        if deep.channel_count() != self.spec.channel_count() {
            return Err(Error::InvalidImageSpec(format!(
                "the deep image has {} channels but the writer expects {}",
                deep.channel_count(),
                self.spec.channel_count()
            )));
        }

        let succeeded = sys::imageio::imageoutput_write_deep_image(self.inner_mut(), deep.native());
        self.check("write deep image", succeeded)?;
        // The whole subimage is written; a later streaming call must not run,
        // because OpenEXR's deep scanline writer would bias the new deep
        // image's arrays by a cursor that is already past them.
        self.mark_whole_subimage_written();
        Ok(())
    }

    /// Write a contiguous band of scanlines of a deep image.
    ///
    /// The deep image must be exactly the band: as wide as the data window,
    /// as tall as `y`, one channel per declared channel. Its own origin does
    /// not matter — the samples land at `y`. Channel types that differ from
    /// the declared ones are converted by OpenImageIO.
    ///
    /// Bands must arrive in order, each starting where the previous ended:
    /// OpenEXR's deep scanline writer keeps its own advancing cursor but
    /// trusts the caller's starting row when it lays the sample arrays over
    /// the file, so an out-of-order band would be read outside its arrays.
    pub fn write_deep_scanlines(&mut self, y: Range<i32>, deep: &DeepImage) -> Result<()> {
        const OPERATION: &str = "write deep scanlines";
        self.require_deep_writer(OPERATION)?;
        if self.spec.is_tiled() {
            return Err(Error::InvalidImageSpec(
                "this file is tiled; use write_deep_tiles".to_owned(),
            ));
        }
        if self.spec.dimensions()[2] != 1 {
            return Err(Error::InvalidImageSpec(
                "scanline writes require a two-dimensional image".to_owned(),
            ));
        }
        if !self.supports("random_access") && y.start != self.next_scanline {
            return Err(Error::InvalidRegion {
                axis: "y",
                message: format!(
                    "this format writes scanlines in order: the next row is {}, not {}",
                    self.next_scanline, y.start
                ),
            });
        }
        let rows = validate_axis("y", &y, self.spec.origin()[1], self.spec.dimensions()[1])?;
        self.require_deep_band(OPERATION, deep, [self.spec.dimensions()[0], rows, 1])?;

        let succeeded = sys::imageio::imageoutput_write_deep_scanlines(
            self.inner_mut(),
            y.start,
            y.end,
            0,
            deep.native(),
        );
        self.check(OPERATION, succeeded)?;
        self.next_scanline = y.end;
        Ok(())
    }

    /// Write a rectangular block of whole tiles of a deep image.
    ///
    /// Each range must start on a tile boundary and either end on one or end
    /// at the edge of the data window — OpenEXR positions the block by tile
    /// index, so a misaligned range would place samples at rows and columns
    /// the deep image does not hold. The deep image must be exactly the
    /// block: its size equal to the ranges, one channel per declared
    /// channel; its own origin does not matter.
    pub fn write_deep_tiles(
        &mut self,
        x: Range<i32>,
        y: Range<i32>,
        z: Range<i32>,
        deep: &DeepImage,
    ) -> Result<()> {
        const OPERATION: &str = "write deep tiles";
        self.require_deep_writer(OPERATION)?;
        let [tile_width, tile_height, tile_depth] = self.spec.tile_dimensions();
        if !self.spec.is_tiled() {
            return Err(Error::InvalidImageSpec(
                "tile writes require a specification with a tile size".to_owned(),
            ));
        }

        let origin = self.spec.origin();
        let dimensions = self.spec.dimensions();
        let width = validate_axis("x", &x, origin[0], dimensions[0])?;
        let height = validate_axis("y", &y, origin[1], dimensions[1])?;
        let depth = validate_axis("z", &z, origin[2], dimensions[2])?;
        validate_tile_alignment("x", &x, origin[0], dimensions[0], tile_width)?;
        validate_tile_alignment("y", &y, origin[1], dimensions[1], tile_height)?;
        validate_tile_alignment("z", &z, origin[2], dimensions[2], tile_depth.max(1))?;
        self.require_deep_band(OPERATION, deep, [width, height, depth])?;

        let succeeded = sys::imageio::imageoutput_write_deep_tiles(
            self.inner_mut(),
            x.start,
            x.end,
            y.start,
            y.end,
            z.start,
            z.end,
            deep.native(),
        );
        self.check(OPERATION, succeeded)?;
        // Tiles touched this subimage; conservatively mark it written so a
        // later whole-image or streaming write refuses rather than
        // interleaving format-dependently.
        self.mark_whole_subimage_written();
        Ok(())
    }

    /// The two deep streaming writers' shared preconditions: a writer opened
    /// with a deep specification, on a format that reports `deepdata` —
    /// OpenImageIO's fallback for the rest fails without recording a message.
    fn require_deep_writer(&self, operation: &'static str) -> Result<()> {
        if !self.spec.is_deep() {
            return Err(Error::operation(
                operation,
                "this writer was opened for flat pixels; see ImageSpec::as_deep".to_owned(),
            ));
        }
        if !self.supports("deepdata") {
            return Err(Error::operation(
                operation,
                format!(
                    "the {} format does not support deep images",
                    self.format_name()
                ),
            ));
        }
        Ok(())
    }

    /// Check that a deep image is shaped exactly like the region a streaming
    /// write covers.
    fn require_deep_band(
        &self,
        operation: &'static str,
        deep: &DeepImage,
        expected: [u32; 3],
    ) -> Result<()> {
        if deep.dimensions() != expected {
            return Err(Error::operation(
                operation,
                format!(
                    "the deep image is {:?} but the region covers {expected:?}",
                    deep.dimensions()
                ),
            ));
        }
        if deep.channel_count() != self.spec.channel_count() {
            return Err(Error::operation(
                operation,
                format!(
                    "the deep image has {} channels but the writer expects {}",
                    deep.channel_count(),
                    self.spec.channel_count()
                ),
            ));
        }
        Ok(())
    }

    /// Attach a thumbnail to the image being written.
    ///
    /// Only formats reporting the `thumbnail` capability store one — among
    /// real formats in OpenImageIO 3.1 that is Targa alone; the `null`
    /// testing sink also claims it, then discards the call with
    /// OpenImageIO's messageless fallback — and that fallback fails without
    /// recording anything, so formats not claiming the capability are
    /// refused here with a clear message. The thumbnail's channel count must match the
    /// image's (Targa refuses a mismatch silently), and both dimensions
    /// must be under 256: the TGA postage stamp stores its size in single
    /// bytes, and through 3.1.15 OpenImageIO's own downsizing clamps to
    /// 256 — one past what the byte holds — silently writing a
    /// zero-dimension thumbnail. (3.1.16 resizes to 255 itself; the refusal
    /// here is version-independent.) Formats not reporting
    /// `thumbnail_after_write` additionally need the thumbnail set before
    /// any pixels.
    pub fn set_thumbnail(&mut self, thumbnail: &crate::ImageBuf) -> Result<()> {
        const OPERATION: &str = "set thumbnail";
        if !self.supports("thumbnail") {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "the {} format does not store thumbnails",
                    self.format_name()
                ),
            ));
        }
        if !self.supports("thumbnail_after_write") && self.next_scanline != self.spec.origin()[1] {
            return Err(Error::operation(
                OPERATION,
                "this format needs the thumbnail before any pixels are written".to_owned(),
            ));
        }
        let thumb_spec = thumbnail.spec()?;
        let [width, height, _] = thumb_spec.dimensions();
        if width == 0 || height == 0 {
            return Err(Error::operation(
                OPERATION,
                "the thumbnail has no pixels".to_owned(),
            ));
        }
        if width >= 256 || height >= 256 {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "a {width}×{height} thumbnail cannot be stored: dimensions must be \
                     under 256, and OpenImageIO's own downsizing clamps to 256 and \
                     truncates it to zero; resize it first"
                ),
            ));
        }
        if thumb_spec.channel_count() != self.spec.channel_count() {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "the thumbnail has {} channels but the image has {}",
                    thumb_spec.channel_count(),
                    self.spec.channel_count()
                ),
            ));
        }

        let succeeded =
            sys::imageio::imageoutput_set_thumbnail(self.inner_mut(), thumbnail.inner());
        self.check(OPERATION, succeeded)
    }

    /// Begin a new subimage in the same file.
    ///
    /// Only supported by formats that report the `"multiimage"` feature.
    pub fn append_subimage(&mut self, spec: &ImageSpec) -> Result<()> {
        self.append(
            spec,
            sys::imageio::OpenMode::AppendSubimage,
            "append subimage",
        )
    }

    /// Begin a new mip level of the current subimage.
    ///
    /// Only supported by formats that report the `"mipmap"` feature.
    pub fn append_mip_level(&mut self, spec: &ImageSpec) -> Result<()> {
        self.append(
            spec,
            sys::imageio::OpenMode::AppendMIPLevel,
            "append mip level",
        )
    }

    /// Get the current thread count.
    pub fn threads(&self) -> i32 {
        sys::imageio::imageoutput_threads(self.inner())
    }

    /// Set the thread count. Zero requests OpenImageIO's default.
    pub fn set_threads(&mut self, threads: i32) {
        sys::imageio::imageoutput_set_threads(self.inner_mut(), threads);
    }

    /// Finish the file and report any delayed format or I/O errors.
    ///
    /// Dropping an `ImageOutput` without calling this method still closes the
    /// file, but cannot report errors that only surface at close time.
    pub fn close(mut self) -> Result<()> {
        let succeeded = sys::imageio::imageoutput_close(self.inner_mut());
        self.check("close image", succeeded)
    }

    fn open_plugin(image_path: &Path) -> Result<Self> {
        let image_path_str = path_to_utf8(image_path)?;
        // SAFETY: a null IOProxy asks OpenImageIO to open the file itself.
        let inner =
            unsafe { sys::imageio::imageoutput_create(image_path_str, std::ptr::null_mut(), "") };
        if inner.is_null() {
            return Err(Error::CreateImage {
                path: image_path.to_path_buf(),
                message: global_error(),
            });
        }

        Ok(Self {
            inner,
            path: image_path.to_path_buf(),
            spec: ImageSpec::new(1, 1, 1, crate::PixelFormat::U8)?,
            next_scanline: 0,
            proxy: None,
        })
    }

    fn open_native(
        output: std::pin::Pin<&mut sys::imageio::ImageOutput>,
        path: &str,
        spec: &cxx::UniquePtr<sys::imageio::ImageSpec>,
        mode: sys::imageio::OpenMode,
    ) -> std::result::Result<(), String> {
        let Some(native_spec) = spec.as_ref() else {
            return Err("OpenImageIO could not allocate an image specification".to_owned());
        };
        if sys::imageio::imageoutput_open(output, path, native_spec, mode) {
            Ok(())
        } else {
            Err(String::new())
        }
    }

    fn append(
        &mut self,
        spec: &ImageSpec,
        mode: sys::imageio::OpenMode,
        operation: &'static str,
    ) -> Result<()> {
        let native_spec = spec.to_sys()?;
        let path = path_to_utf8(&self.path)?.to_owned();
        let opened = Self::open_native(self.inner_mut(), &path, &native_spec, mode);
        match opened {
            Ok(()) => {
                self.adopt_open_spec(spec);
                Ok(())
            }
            Err(message) if message.is_empty() => Err(self.take_error(operation)),
            Err(message) => Err(Error::operation(operation, message)),
        }
    }

    fn validate_axis(
        &self,
        axis: &'static str,
        range: &Range<i32>,
        origin: i32,
        size: u32,
    ) -> Result<u32> {
        validate_axis(axis, range, origin, size)
    }
}

/// Check that a coordinate range is non-empty and inside the data window on
/// one axis, and return its length.
fn validate_axis(axis: &'static str, range: &Range<i32>, origin: i32, size: u32) -> Result<u32> {
    if range.start >= range.end {
        return Err(Error::InvalidRegion {
            axis,
            message: format!(
                "range must be non-empty and increasing, got {}..{}",
                range.start, range.end
            ),
        });
    }
    let end = i64::from(origin) + i64::from(size);
    if i64::from(range.start) < i64::from(origin) || i64::from(range.end) > end {
        return Err(Error::InvalidRegion {
            axis,
            message: format!(
                "range {}..{} lies outside the data window {origin}..{end}",
                range.start, range.end
            ),
        });
    }
    Ok((i64::from(range.end) - i64::from(range.start)) as u32)
}

impl ImageOutput {
    fn reject_deep(&self) -> Result<()> {
        if self.spec.is_deep() {
            return Err(Error::UnsupportedDeepImage);
        }
        Ok(())
    }

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

    fn inner(&self) -> &sys::imageio::ImageOutput {
        self.inner
            .as_ref()
            .expect("ImageOutput invariant violated: null native pointer")
    }

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

    /// The raw writer handle, for wrappers in other modules whose shim takes
    /// the native pointer (`ImageBuf::write_to`). `pub(crate)` so the
    /// pointer never crosses the crate boundary.
    pub(crate) fn native_mut(&mut self) -> std::pin::Pin<&mut sys::imageio::ImageOutput> {
        self.inner_mut()
    }

    /// Where the in-order scanline cursor stands; equals the data window's
    /// top row while the current subimage is untouched.
    pub(crate) fn scanline_cursor(&self) -> i32 {
        self.next_scanline
    }

    /// Record that a whole-image path (`ImageBuf::write_to`) wrote every row
    /// behind the crate's cursor, so a later in-order `write_scanlines` is
    /// refused with a clear error instead of failing inside the format
    /// writer.
    pub(crate) fn mark_whole_subimage_written(&mut self) {
        let end = i64::from(self.spec.origin()[1]) + i64::from(self.spec.dimensions()[1]);
        self.next_scanline = end.min(i64::from(i32::MAX)) as i32;
    }

    /// Write an arbitrary rectangle of pixels, for formats that can place
    /// pixels at random.
    ///
    /// Only formats reporting the `rectangles` capability accept this —
    /// [`ImageOutput::supports`] tells; OpenImageIO's fallback for the rest
    /// returns failure without recording a message, which this wrapper turns
    /// into a clear error before calling. No format shipped with
    /// OpenImageIO 3.1 reports the capability, so today this is refused for
    /// every built-in writer; it exists for third-party plugins that do.
    /// The rectangle must lie inside the data window and the buffer must
    /// hold exactly its pixels. After a rectangle lands, the subimage
    /// counts as written for the in-order scanline cursor.
    pub fn write_rectangle<T: Pixel>(
        &mut self,
        x: Range<i32>,
        y: Range<i32>,
        pixels: &[T],
    ) -> Result<()> {
        self.reject_deep()?;
        if !self.supports("rectangles") {
            return Err(Error::operation(
                "write rectangle",
                format!(
                    "the {} format cannot place arbitrary rectangles; OpenImageIO's \
                     fallback fails without a message, so it is refused here",
                    self.format_name()
                ),
            ));
        }
        let origin = self.spec.origin();
        let dimensions = self.spec.dimensions();
        let width = self.validate_axis("x", &x, origin[0], dimensions[0])?;
        let height = self.validate_axis("y", &y, origin[1], dimensions[1])?;
        let expected = element_count([width, height, 1, self.spec.channel_count()])?;
        validate_buffer_len(expected, pixels.len())?;

        // SAFETY: Pixel is sealed to initialized scalar layouts, so the byte
        // view holds initialized values of the declared format.
        let succeeded = unsafe {
            sys::imageio::imageoutput_write_rectangle_span(
                self.inner_mut(),
                x.start,
                x.end,
                y.start,
                y.end,
                0,
                1,
                pixel::type_desc::<T>(),
                pixel::as_bytes(pixels),
            )
        };
        self.check("write rectangle", succeeded)?;
        self.mark_whole_subimage_written();
        Ok(())
    }

    /// Copy a reader's current subimage into this writer — the lossless
    /// transcode path `iconvert` is built on.
    ///
    /// Pixel data is carried in the file's native format wherever the
    /// formats allow, without a decode to a caller type in between; deep
    /// images are copied sample-for-sample. OpenImageIO verifies that the
    /// two specifications agree on dimensions and channel count and reports
    /// a clear error when they do not. Nothing may have been written to the
    /// current subimage yet, and the writer stays open afterwards.
    pub fn copy_image_from(&mut self, input: &mut ImageInput) -> Result<()> {
        const OPERATION: &str = "copy image from reader";
        let top = self.spec.origin()[1];
        if self.next_scanline != top {
            return Err(Error::operation(
                OPERATION,
                format!(
                    "rows {top}..{} of this subimage were already written; the copy \
                     needs an untouched subimage",
                    self.next_scanline
                ),
            ));
        }
        // SAFETY: the pointer comes from a live &mut ImageInput, is consumed
        // within this one call, and the pinned reader is not moved.
        let succeeded = unsafe {
            let in_ptr = input.native_mut().get_unchecked_mut() as *mut sys::imageio::ImageInput;
            sys::imageio::imageoutput_copy_image(self.inner_mut(), in_ptr)
        };
        if !succeeded {
            return Err(self.take_error(OPERATION));
        }
        // The whole subimage is written; the cursor keeps write_scanlines
        // and write_to honest about it.
        self.mark_whole_subimage_written();
        Ok(())
    }

    fn take_error(&mut self, operation: &'static str) -> Error {
        Error::operation(
            operation,
            sys::imageio::imageoutput_geterror(self.inner(), true),
        )
    }
}

fn validate_tile_alignment(
    axis: &'static str,
    range: &Range<i32>,
    origin: i32,
    size: u32,
    tile: u32,
) -> Result<()> {
    if tile == 0 {
        return Err(Error::InvalidImageSpec(format!(
            "tile size on the {axis} axis must be non-zero"
        )));
    }
    let tile = i64::from(tile);
    let edge = i64::from(origin) + i64::from(size);

    if (i64::from(range.start) - i64::from(origin)) % tile != 0 {
        return Err(Error::InvalidRegion {
            axis,
            message: format!("start {} is not on the {tile}-pixel tile grid", range.start),
        });
    }
    if i64::from(range.end) != edge && (i64::from(range.end) - i64::from(origin)) % tile != 0 {
        return Err(Error::InvalidRegion {
            axis,
            message: format!(
                "end {} is neither on the {tile}-pixel tile grid nor at the data window edge {edge}",
                range.end
            ),
        });
    }
    Ok(())
}

fn global_error() -> String {
    if sys::imageio::has_error() {
        sys::imageio::get_error(true)
    } else {
        "OpenImageIO did not provide an error message".to_owned()
    }
}

impl std::fmt::Debug for ImageInput {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ImageInput")
            .field("format", &self.format_name())
            .finish_non_exhaustive()
    }
}

impl std::fmt::Debug for ImageOutput {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ImageOutput")
            .field("path", &self.path)
            .field("format", &self.format_name())
            .field("dimensions", &self.spec.dimensions())
            .field("pixel_format", &self.spec.format())
            .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()))
}

pub(crate) fn validate_buffer_len(expected: usize, actual: usize) -> Result<()> {
    if expected == actual {
        Ok(())
    } else {
        Err(Error::BufferLength { expected, actual })
    }
}