plumers 1.0.2

Multi-format image library with first-class support for paletted images
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
//! The meat of this crate.

use std::{marker::PhantomData, mem::MaybeUninit, num::NonZeroUsize};

use crate::color::ColorFmt;

mod frame;
pub use frame::{Frame, FrameMut, Frames};
mod load;
use load::PaletteMode;
pub use load::{max_nb_pixels, ImageSource, Input, LoadFlags, PaletteSort};
mod metadata;
use metadata::{Metadata, MetadataMut};
mod raw;
use raw::PlumWrapper;
mod store;
pub use store::{ImageDest, Output};

/// An image whose pixels all directly contain their colour.
///
/// Most of this type's API is provided by the [`Image`] trait.
#[derive(Debug, Clone)]
pub struct DirectImage<Fmt: ColorFmt>(raw::ImgWrapper, PhantomData<Fmt>);
// Convenience aliases for the supported color formats.
/// `DirectImage<Rgb16>`
pub type DirectImage16 = DirectImage<crate::color::Rgb16>;
/// `DirectImage<Rgb32>`
pub type DirectImage32 = DirectImage<crate::color::Rgb32>;
/// `DirectImage<Rgb32X>`
pub type DirectImage32X = DirectImage<crate::color::Rgb32X>;
/// `DirectImage<Rgb64>`
pub type DirectImage64 = DirectImage<crate::color::Rgb64>;

/// An image whose pixels are all indices into a shared palette.
///
/// Most of this type's API is provided by the [`Image`] trait.
#[derive(Debug, Clone)]
pub struct PalettedImage<Fmt: ColorFmt>(raw::ImgWrapper, PhantomData<Fmt>);
// Convenience aliases for the supported color formats.
/// `PalettedImage<Rgb16>`
pub type PalettedImage16 = PalettedImage<crate::color::Rgb16>;
/// `PalettedImage<Rgb32>`
pub type PalettedImage32 = PalettedImage<crate::color::Rgb32>;
/// `PalettedImage<Rgb32X>`
pub type PalettedImage32X = PalettedImage<crate::color::Rgb32X>;
/// `PalettedImage<Rgb64>`
pub type PalettedImage64 = PalettedImage<crate::color::Rgb64>;

/// Either a [`DirectImage`], or a [`PalettedImage`].
///
/// Like both of these types, most of `DynImage`'s API is provided by the [`Image`] trait.
#[derive(Debug, Clone)]
pub enum DynImage<Fmt: ColorFmt> {
    /// The image is not paletted.
    Direct(DirectImage<Fmt>),
    /// The image is paletted.
    Paletted(PalettedImage<Fmt>),
}
// Convenience aliases for the supported color formats.
/// `DynImage<Rgb16>`
pub type DynImage16 = DynImage<crate::color::Rgb16>;
/// `DynImage<Rgb32>`
pub type DynImage32 = DynImage<crate::color::Rgb32>;
/// `DynImage<Rgb32X>`
pub type DynImage32X = DynImage<crate::color::Rgb32X>;
/// `DynImage<Rgb64>`
pub type DynImage64 = DynImage<crate::color::Rgb64>;

/// Common API between [`DirectImage`], [`PalettedImage`], and [`DynImage`].
///
/// This trait is [sealed], it cannot be implemented outside of this crate.
///
/// [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
pub trait Image<Fmt: ColorFmt>: PlumWrapper<Fmt> {
    /// Returns how many frames the image contains.
    ///
    /// [`frames()`][Self::frames()] and [`foreach_frame_mut()`][Self::foreach_frame_mut()] will both iterate exactly this many times.
    fn nb_frames(&self) -> usize;
    /// Returns how many pixels wide the image is.
    ///
    /// Note that all frames have the same size.
    fn width(&self) -> usize;
    /// Returns how many pixels tall the image is.
    ///
    /// Note that all frames have the same size.
    fn height(&self) -> usize;
    /// How many pixels are in each frame.
    fn nb_pixels(&self) -> usize {
        self.height() * self.width()
    }
    /// The image's format (PNG, JPEG...).
    ///
    /// This is set when it is loaded, and is also used to determine the format it should be stored as.
    fn format(&self) -> ImageFormat;
    /// Sets a different format to store the image as.
    fn set_format(&mut self, format: ImageFormat);
    /// The image's alpha mode.
    ///
    /// This is set when it is loaded, and is also used to determine how it should be stored.
    fn alpha_mode(&self) -> AlphaMode;
    /// Sets a different alpha mode to store the image as.
    ///
    /// Note that this does **not** alter the pixel data!
    /// Simply setting this without modifying the image's pixel data will effectively invert the alpha channel for the entire image.
    fn set_alpha_mode(&mut self, mode: AlphaMode);

    /// Retrieves the image's embedded colour palette, if there is one.
    fn palette(&self) -> Option<&[Fmt]>;
    /// Retrieves the pixel at the given position in the image.
    ///
    /// See also [`Frame::pixel()`], or consider indexing into a [`Frame`].
    ///
    /// # Panics
    ///
    /// This function panics if any of `frame_idx`, `x`, or `y` is out of range.
    fn pixel(&self, frame_idx: usize, x: usize, y: usize) -> Fmt;
    /// Retrieves the pixel at the given position in the image.
    ///
    /// Consider also indexing into a [`FrameMut`].
    ///
    /// # Paletted images
    ///
    /// Be careful: for paletted images, the reference returned is to the palette, so modifying it will alter **all** corresponding pixels in the image, across all frames.
    ///
    /// # Panics
    ///
    /// This function panics if any of `frame_idx`, `x`, or `y` is out of range.
    fn pixel_mut(&mut self, frame_idx: usize, x: usize, y: usize) -> &mut Fmt;

    /// Provides more convenient access to a specific frame of the image's.
    ///
    /// To use this with `&dyn Image`, consider using [`Frame::new`] instead.
    ///
    /// # Panics
    ///
    /// This function panics if `frame_idx` is out of range.
    fn frame(&self, frame_idx: usize) -> Frame<'_, Fmt, Self>
    where
        Self: Sized,
    {
        Frame::new(self, frame_idx)
    }
    /// Provides more convenient access to a specific frame of the image's.
    ///
    /// To use this with `&dyn Image`, consider using [`FrameMut::new`] instead.
    ///
    /// # Panics
    ///
    /// This function panics if `frame_idx` is out of range.
    fn frame_mut(&mut self, frame_idx: usize) -> FrameMut<'_, Fmt, Self>
    where
        Self: Sized,
    {
        FrameMut::new(self, frame_idx)
    }

    /// Iterates through the image's frames.
    fn frames(&self) -> Frames<'_, Fmt, Self>
    where
        Self: Sized,
    {
        Frames {
            img: self,
            begin: 0,
            end: self.nb_frames(),
            _pix_fmt: PhantomData,
        }
    }
    /// Iterates through the image's frames, with a callback that is allowed to mutate the image.
    ///
    /// An [`Iterator`] cannot be provided, because the returned [`FrameMut`]s may not outlive each iteration.
    fn foreach_frame_mut<F: FnMut(FrameMut<'_, Fmt, Self>)>(&mut self, mut f: F)
    where
        Self: Sized,
    {
        for i in 0..self.nb_frames() {
            f(self.frame_mut(i))
        }
    }
    /// Iterates through the image's frames, with a faillible callback that is allowed to mutate the image.
    ///
    /// An [`Iterator`] cannot be provided, because the returned [`FrameMut`]s may not outlive each iteration.
    fn try_foreach_frame_mut<E, F: FnMut(FrameMut<'_, Fmt, Self>) -> Result<(), E>>(
        &mut self,
        mut f: F,
    ) -> Result<(), E>
    where
        Self: Sized,
    {
        for i in 0..self.nb_frames() {
            f(self.frame_mut(i))?
        }
        Ok(())
    }

    /// Iterates through the image's metadata nodes.
    fn metadata(&self) -> Metadata<'_>;
    /// Iterates through the image's metadata nodes, allowing in-place modification of them.
    fn metadata_mut(&mut self) -> MetadataMut<'_>;

    /// Stores the image to [an image destination][ImageDest].
    fn store<Dest: ImageDest>(&self, output: Dest) -> std::io::Result<NonZeroUsize>
    where
        Self: Sized;
}

/// Controls the meaning of an image's alpha channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum AlphaMode {
    /// `0` = opaque, `<T>::MAX` = transparent
    ///
    /// This is less conventional, but can be useful for applications that ignore alpha,
    /// since e.g. `new_zeroed` returns a fully opaque image instead of fully transparent.
    #[default]
    ZeroIsOpaque,
    /// `0` = transparent, `<T>::MAX` = opaque
    ///
    /// This is the conventional meaning of "alpha".
    ZeroIsTransparent,
}

/// Indicates the file format the image used (when loading it) or will use (when storing it).
///
/// For more information, see the libplum's [Supported file formats](http://github.com/aaaaaa123456789/libplum/blob/v1.2/docs/formats.md) page.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive] // libplum itself can add new formats without breaking semver, let's do the same.
pub enum ImageFormat {
    /// No image type.
    ///
    /// Used by an image for which an image type hasn't been specified, such as one just created by [`DirectImage::new_zeroed()`].
    /// It may also be used as an explicit "no type" designator.
    None = libplum_sys::PLUM_IMAGE_NONE as isize,
    /// BMP (Windows Bitmap) file.
    Bmp = libplum_sys::PLUM_IMAGE_BMP as isize,
    /// GIF (CompuServe's Graphics Interchange Format) format, including both static images and animations.
    Gif = libplum_sys::PLUM_IMAGE_GIF as isize,
    /// PNG (Portable Network Graphics) file.
    Png = libplum_sys::PLUM_IMAGE_PNG as isize,
    /// Animated PNG file.
    ///
    /// Treated as a separate format because it is not actually compatible with PNG (due to using ancillary chunks to store critical animation information), which will cause APNG-unaware viewers and editors to handle it incorrectly.
    Apng = libplum_sys::PLUM_IMAGE_APNG as isize,
    /// JPEG (Joint Photographers Expert Group) file.
    Jpeg = libplum_sys::PLUM_IMAGE_JPEG as isize,
    /// netpbm's PNM (Portable Anymap) format.
    ///
    /// When loading, it represents any possible PNM file; however, only PPM and PAM files will be written.
    Pnm = libplum_sys::PLUM_IMAGE_PNM as isize,
}

impl<Fmt: ColorFmt> DirectImage<Fmt> {
    /// Creates a new image, setting all of its pixel data to zeroes.
    ///
    /// Note that this will make the image all-opaque or all-transparent, depending on `alpha_mode`.
    pub fn new_zeroed(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
    ) -> Self {
        let wrapper = raw::ImgWrapper::new_zeroed::<Fmt>(
            nb_frames.try_into().unwrap(),
            width.try_into().unwrap(),
            height.try_into().unwrap(),
        );
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        this
    }

    /// Creates a new image, setting all of its pixel data by repeatedly calling a function.
    ///
    /// The function is passed the coordinates (frame, x, y) of the pixel it should init, every time it is called.
    pub fn from_fn<F: FnMut(usize, usize, usize) -> Fmt>(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
        mut init: F,
    ) -> Self {
        // SAFETY: the loop walks over every pixel, as is guaranteed by the assertion.
        let wrapper = unsafe {
            raw::ImgWrapper::new(
                nb_frames.try_into().unwrap(),
                width.try_into().unwrap(),
                height.try_into().unwrap(),
                |pixels| {
                    debug_assert_eq!(nb_frames * height * width, pixels.len());

                    for frame in 0..nb_frames {
                        for y in 0..height {
                            for x in 0..width {
                                pixels[(frame * height + y) * width + x].write(init(frame, x, y));
                            }
                        }
                    }
                },
            )
        };
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        this
    }

    /// Creates a new image, initializing its pixel data in an user-defined way.
    ///
    /// This can be used if [`from_fn`][Self::from_fn]'s init order is not suitable; for example,
    /// if you'd like to paint the image non-linearly to improve cache locality and thus performance.
    ///
    /// # Safety
    ///
    /// The `init` function must initialize the whole provided slice.
    pub unsafe fn new<F: FnOnce(&mut [MaybeUninit<Fmt>])>(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
        init: F,
    ) -> Self {
        // SAFETY: deferred to the caller.
        let wrapper = unsafe {
            raw::ImgWrapper::new::<Fmt, _>(
                nb_frames.try_into().unwrap(),
                width.try_into().unwrap(),
                height.try_into().unwrap(),
                init,
            )
        };
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        this
    }

    /// Loads an image from [an image source][ImageSource].
    ///
    /// This will convert any image stored as paletted into a direct-color image.
    ///
    /// See [`DynImage::load`] if you don't want that.
    pub fn load<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
    ) -> std::io::Result<Self> {
        Self::load_limited(input, flags, alpha_mode, max_nb_pixels::<Fmt>())
    }

    /// Loads an image from [an image source][ImageSource], limiting the amount of memory that can
    /// be allocated.
    ///
    /// This will convert any image stored as paletted into a direct-color image.
    ///
    /// See [`DynImage::load`] if you don't want that.
    ///
    /// ## Memory limit
    ///
    /// Note that the `nb_pixels_max` argument only limits how much memory is allocated for the pixel
    /// data itself, not for the entire image or for temporary buffers.
    ///
    /// The image struct, as well as the metadata nodes and other bookkeeping, can push the total
    /// allocation a little higher than that, though not much.
    pub fn load_limited<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
        nb_pixels_max: usize,
    ) -> std::io::Result<Self> {
        let image = input.load::<Fmt>(flags, alpha_mode, PaletteMode::None, nb_pixels_max)?;
        let wrapper = raw::ImgWrapper::from(image);
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());
        Ok(Self(wrapper, PhantomData))
    }

    /// Retrieves the pixel at the given position in the image.
    ///
    /// Consider also indexing into a [`Frame<DirectImage>`].
    pub fn pixel_at(&self, frame: usize, x: usize, y: usize) -> &Fmt {
        let height = self.height();
        let width = self.width();
        // SAFETY: this is a direct image, so the backing array is of `Fmt`s.
        &(unsafe { self.pix_array::<Fmt>() })[(frame * height + y) * width + x]
    }

    /// Retrieves the pixel at the given position in the image.
    ///
    /// Consider also indexing into a [`FrameMut<DirectImage>`].
    pub fn pixel_at_mut(&mut self, frame: usize, x: usize, y: usize) -> &mut Fmt {
        let height = self.height();
        let width = self.width();
        // SAFETY: this is a direct image, so the backing array is of `Fmt`s.
        &mut (unsafe { self.pix_array_mut::<Fmt>() })[(frame * height + y) * width + x]
    }
}

impl<Fmt: ColorFmt> PalettedImage<Fmt> {
    /// Creates a new image, setting all of its pixel data to zeroes.
    ///
    /// Note that this will make the image all-opaque or all-transparent, depending on `alpha_mode`.
    ///
    /// This function can fail if the palette ends up being more than 256 items long; in that case, the length is returned as an error.
    pub fn new_zeroed<It: IntoIterator<Item = Fmt>>(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
        palette: It,
    ) -> Result<Self, usize> {
        let mut wrapper = raw::ImgWrapper::new_zeroed::<Fmt>(
            nb_frames.try_into().unwrap(),
            width.try_into().unwrap(),
            height.try_into().unwrap(),
        );
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let palette_ptr = wrapper.collect(palette);
        wrapper.palette = palette_ptr.as_ptr().cast();

        // SAFETY: `collect` returns a pointer to a properly initialized slice of elements.
        let slice_len = unsafe { palette_ptr.as_ref() }.len();
        let Some(max_index) = slice_len.checked_sub(1).and_then(|max| max.try_into().ok()) else {
            return Err(slice_len);
        };
        wrapper.max_palette_index = max_index;

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        Ok(this)
    }

    /// Creates a new image, setting all of its pixel data by repeatedly calling a function.
    ///
    /// The function is passed the coordinates (frame, x, y) of the pixel it should init, every time it is called.
    ///
    /// This function can fail if the palette ends up being more than 256 items long; in that case, the length is returned as an error.
    pub fn from_fn<F: FnMut(usize, usize, usize) -> Fmt, It: IntoIterator<Item = Fmt>>(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
        mut init: F,
        palette: It,
    ) -> Result<Self, usize> {
        // SAFETY: the loop walks over every pixel, as is guaranteed by the assertion.
        let mut wrapper = unsafe {
            raw::ImgWrapper::new(
                nb_frames.try_into().unwrap(),
                width.try_into().unwrap(),
                height.try_into().unwrap(),
                |pixels| {
                    debug_assert_eq!(nb_frames * height * width, pixels.len());

                    for frame in 0..nb_frames {
                        for y in 0..height {
                            for x in 0..width {
                                pixels[(frame * height + y) * width + x].write(init(frame, x, y));
                            }
                        }
                    }
                },
            )
        };
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let palette_ptr = wrapper.collect(palette);
        wrapper.palette = palette_ptr.as_ptr().cast();

        // SAFETY: `collect` returns a pointer to a properly initialized slice of elements.
        let slice_len = unsafe { palette_ptr.as_ref() }.len();
        let Some(max_index) = slice_len.checked_sub(1).and_then(|max| max.try_into().ok()) else {
            return Err(slice_len);
        };
        wrapper.max_palette_index = max_index;

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        Ok(this)
    }

    /// Creates a new image, initializing its pixel data in an user-defined way.
    ///
    /// This can be used if [`from_fn`][Self::from_fn]'s init order is not suitable; for example,
    /// if you'd like to paint the image non-linearly to improve cache locality and thus performance.
    ///
    /// This function can fail if the palette ends up being more than 256 items long; in that case, the length is returned as an error.
    ///
    /// # Safety
    ///
    /// The `init` function must initialize the whole provided slice.
    pub unsafe fn new<F: FnOnce(&mut [MaybeUninit<Fmt>]), It: IntoIterator<Item = Fmt>>(
        format: ImageFormat,
        alpha_mode: AlphaMode,
        nb_frames: usize,
        width: usize,
        height: usize,
        init: F,
        palette: It,
    ) -> Result<Self, usize> {
        // SAFETY: deferred to the caller.
        let mut wrapper = unsafe {
            raw::ImgWrapper::new::<Fmt, _>(
                nb_frames.try_into().unwrap(),
                width.try_into().unwrap(),
                height.try_into().unwrap(),
                init,
            )
        };
        debug_assert_eq!(wrapper.palette, std::ptr::null_mut());

        let palette_ptr = wrapper.collect(palette);
        wrapper.palette = palette_ptr.as_ptr().cast();

        // SAFETY: `collect` returns a pointer to a properly initialized slice of elements.
        let slice_len = unsafe { palette_ptr.as_ref() }.len();
        let Some(max_index) = slice_len.checked_sub(1).and_then(|max| max.try_into().ok()) else {
            return Err(slice_len);
        };
        wrapper.max_palette_index = max_index;

        let mut this = Self(wrapper, PhantomData);
        this.set_format(format);
        this.set_alpha_mode(alpha_mode);
        Ok(this)
    }

    /// Loads an image from [an image source][ImageSource].
    ///
    /// This will attempt to generate a palette from direct-color images, and error out if palette generation fails (typically because the image contains more than 256 unique colors).
    ///
    /// See [`DynImage::load`] if you don't want that.
    pub fn load<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
    ) -> std::io::Result<Self> {
        Self::load_limited(input, flags, alpha_mode, max_nb_pixels::<Fmt>())
    }

    /// Loads an image from [an image source][ImageSource], limiting the amount of memory that can
    /// be allocated.
    ///
    /// This will attempt to generate a palette from direct-color images, and error out if palette generation fails (typically because the image contains more than 256 unique colors).
    ///
    /// See [`DynImage::load`] if you don't want that.
    ///
    /// ## Memory limit
    ///
    /// Note that the `nb_pixels_max` argument only limits how much memory is allocated for the pixel
    /// data itself, not for the entire image or for temporary buffers.
    ///
    /// The image struct, as well as the metadata nodes and other bookkeeping, can push the total
    /// allocation a little higher than that, though not much.
    pub fn load_limited<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
        nb_pixels_max: usize,
    ) -> std::io::Result<Self> {
        let image = input.load::<Fmt>(flags, alpha_mode, PaletteMode::Force, nb_pixels_max)?;
        let wrapper = raw::ImgWrapper::from(image);
        debug_assert_ne!(wrapper.palette, std::ptr::null_mut());
        Ok(Self(wrapper, PhantomData))
    }

    /// Returns the image's palette.
    pub fn palette(&self) -> &[Fmt] {
        debug_assert_ne!(self.as_img().palette, std::ptr::null_mut());
        // SAFETY: all `ColorFmt`s are `#[repr(transparent)]` and contain a single int, so casting is okay.
        let ptr = self.as_img().palette.cast();
        let len = usize::from(self.as_img().max_palette_index) + 1;
        // SAFETY: the slice is guaranteed to be correctly initialized, aligned, etc by libplum and other Rust code.
        unsafe { std::slice::from_raw_parts(ptr, len) }
    }

    /// Returns the image's palette, for in-place modification.
    pub fn palette_mut(&mut self) -> &mut [Fmt] {
        debug_assert_ne!(self.as_img().palette, std::ptr::null_mut());
        // SAFETY: all `ColorFmt`s are `#[repr(transparent)]` and contain a single int, so casting is okay.
        let ptr = self.as_img().palette.cast();
        let len = usize::from(self.as_img().max_palette_index) + 1;
        // SAFETY: the slice is guaranteed to be correctly initialized, aligned, etc by libplum and other Rust code.
        unsafe { std::slice::from_raw_parts_mut(ptr, len) }
    }

    /// Retrieves a reference to the index at the given coordinates.
    ///
    /// Consider also indexing into a [`Frame<PalettedImage>`].
    pub fn index_at(&self, frame: usize, x: usize, y: usize) -> &u8 {
        let height = self.height();
        let width = self.width();
        // SAFETY: this is an indexed image, so the backing array is of `u8`s.
        &(unsafe { self.pix_array::<u8>() })[(frame * height + y) * width + x]
    }

    /// Retrieves a mutable reference to the index at the given coordinates.
    ///
    /// Consider also indexing into a [`FrameMut<PalettedImage>`].
    pub fn index_at_mut(&mut self, frame: usize, x: usize, y: usize) -> &mut u8 {
        let height = self.height();
        let width = self.width();
        // SAFETY: this is an indexed image, so the backing array is of `u8`s.
        &mut (unsafe { self.pix_array_mut::<u8>() })[(frame * height + y) * width + x]
    }
}

impl<Fmt: ColorFmt> DynImage<Fmt> {
    /// Loads an image from [an image source][ImageSource].
    ///
    /// If `prefer_palette` is `true`, this will attempt to generate a palette from a direct-color image; however, failure to do so (typically because the image contains more than 256 colours) is not considered an error, and instead returns a [`DirectImage`].
    ///
    /// If you don't want to deal with the overhead of checking which image type is contained each time, consider either [`DirectImage::load()`] or [`PalettedImage::load()`].
    pub fn load<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
        prefer_palette: bool,
    ) -> std::io::Result<Self> {
        Self::load_limited(
            input,
            flags,
            alpha_mode,
            prefer_palette,
            max_nb_pixels::<Fmt>(),
        )
    }

    /// Loads an image from [an image source][ImageSource], limiting the amount of memory that can
    /// be allocated.
    ///
    /// If `prefer_palette` is `true`, this will attempt to generate a palette from a direct-color image; however, failure to do so (typically because the image contains more than 256 colours) is not considered an error, and instead returns a [`DirectImage`].
    ///
    /// ## Memory limit
    ///
    /// Note that the `nb_pixels_max` argument only limits how much memory is allocated for the pixel
    /// data itself, not for the entire image or for temporary buffers.
    ///
    /// The image struct, as well as the metadata nodes and other bookkeeping, can push the total
    /// allocation a little higher than that, though not much.
    pub fn load_limited<Src: ImageSource>(
        input: Src,
        flags: LoadFlags,
        alpha_mode: AlphaMode,
        prefer_palette: bool,
        nb_pixels_max: usize,
    ) -> std::io::Result<Self> {
        let image = input.load::<Fmt>(
            flags,
            alpha_mode,
            if prefer_palette {
                PaletteMode::Generate
            } else {
                PaletteMode::Load
            },
            nb_pixels_max,
        );
        image.map(|img| {
            let wrapper = raw::ImgWrapper::from(img);
            if wrapper.palette.is_null() {
                DirectImage(wrapper, PhantomData).into()
            } else {
                PalettedImage(wrapper, PhantomData).into()
            }
        })
    }

    /// Returns a trait object for accessing the [`Image`] API of the underlying image.
    ///
    /// Using this instead of simply casting `self as &dyn Image<Fmt>` is a little faster, because it inspects the enumeration only once instead of at every method call.
    pub fn as_dyn_image(&self) -> &dyn Image<Fmt> {
        match self {
            DynImage::Direct(img) => img,
            DynImage::Paletted(img) => img,
        }
    }

    /// Returns a trait object for accessing the [`Image`] API of the underlying image.
    ///
    /// Using this instead of simply casting `self as &mut dyn Image<Fmt>` is a little faster, because it inspects the enumeration only once instead of at every method call.
    pub fn as_mut_dyn_image(&mut self) -> &mut dyn Image<Fmt> {
        match self {
            DynImage::Direct(img) => img,
            DynImage::Paletted(img) => img,
        }
    }
}
impl<Fmt: ColorFmt> From<DirectImage<Fmt>> for DynImage<Fmt> {
    fn from(value: DirectImage<Fmt>) -> Self {
        Self::Direct(value)
    }
}
impl<Fmt: ColorFmt> From<PalettedImage<Fmt>> for DynImage<Fmt> {
    fn from(value: PalettedImage<Fmt>) -> Self {
        Self::Paletted(value)
    }
}
// TODO(?)
// impl<Fmt: ColorFmt> From<DynImage<Fmt>> for DirectImage<Fmt> {}
// impl<Fmt: ColorFmt> TryFrom<DynImage<Fmt>> for PalettedImage<Fmt> {}