Skip to main content

waft_embedder/
image_codecs.rs

1//! The system's image codecs, as a host hands them to the app. Not a dart:ui file: dart:ui's
2//! `instantiateImageCodec` (this crate's `image`) decodes for the framework's own drawing and
3//! answers an [`Image`](crate::Image) the renderer draws, never its pixels. These are the system's
4//! codecs as an app uses them itself, to read and write image files: Apple's Image I/O,
5//! Android's `AImageDecoder` and `AndroidBitmap_compress`, Windows' `BitmapDecoder` and
6//! `BitmapEncoder`, the web's `ImageDecoder`. They follow `wasdk:media/image-codecs` one to one,
7//! and are a module of their own, named as that interface is.
8//!
9//! Pixels are in one of two kinds of memory, and every move between them is a call of its own, so
10//! an app sees each copy it makes. An image decodes into the app's memory, a [`PixelBuffer`], on
11//! every host ([`ImageSource::decode_pixels`]), which
12//! [`Platform::import_pixels`](crate::Platform::import_pixels) uploads as an image to draw, and
13//! encodes from one ([`ImageCodecs::encode_pixels`]). Where the system can, its hardware codecs
14//! ([`HardwareImageCodecs`]) decode into GPU memory, a [`HardwareBuffer`] of the app's own, which
15//! [`Platform::import_hardware_buffer`](crate::Platform::import_hardware_buffer) draws with no
16//! copy and which holds no slot in a pool, and encode from one, a buffer the app drew or a video
17//! frame's ([`VideoFrame::hardware_buffer`](crate::VideoFrame::hardware_buffer)) among them:
18//! Apple's codecs decode into an `IOSurface`; Android's NDK decoder writes only the app's memory,
19//! so Android's host has none, a hardware bitmap being Java's `ImageDecoder`'s alone. A hardware
20//! buffer comes back to the app's memory only through [`HardwareBuffer::read_pixels`].
21//!
22//! An image is opened from its bytes, or from a file, which the system reads only as far as it
23//! needs; opening reads what the image says of itself, its format, size, orientation and metadata,
24//! and how its pictures go: one still picture, the frames of an animation played a number of times
25//! or forever, or the pages of a document, each its own picture ([`ImagePictures`]). Its pixels are
26//! decoded when asked, a picture at a time, upright, at the size asked. A photo's location
27//! is the user's location data, given as the file holds it to the app that holds the file; encoding
28//! writes no metadata, so pixels encoded again carry no location.
29//!
30//! The invariant a host keeps: each future resolves, once, whether or not the app still holds
31//! what it asked of, since the system decodes and encodes in the background.
32
33use std::any::Any;
34use std::fmt;
35use std::future::Future;
36use std::path::Path;
37use std::pin::Pin;
38use std::sync::Arc;
39use std::time::Duration;
40
41pub use valo::{AlphaType, PixelBuffer, PixelFormat, PixelLayout};
42
43use crate::{HardwareBuffer, Size};
44
45/// The system's image codecs, or `None` from
46/// [`Platform::image_codecs`](crate::Platform::image_codecs) where it has none.
47pub trait ImageCodecs {
48    /// The formats it decodes, by MIME type, such as `image/jpeg`.
49    fn decoded_formats(&self) -> Vec<String>;
50
51    /// The formats it encodes, by MIME type.
52    fn encoded_formats(&self) -> Vec<String>;
53
54    /// The image `data` encodes, read as far as its size, pictures, orientation and metadata:
55    /// [`ImageErrorKind::Unsupported`] for bytes of no format it decodes,
56    /// [`ImageErrorKind::Damaged`] for bytes it cannot read that far.
57    fn open(&self, data: Arc<[u8]>) -> ImageFuture<Box<dyn ImageSource>>;
58
59    /// The image in the file at `path`, which the system reads only as far as it needs, as a
60    /// photo's metadata or the small picture it carries: [`ImageErrorKind::NotFound`] for a path
61    /// with no file.
62    fn open_file(&self, path: &Path) -> ImageFuture<Box<dyn ImageSource>>;
63
64    /// `pixels` encoded in `format`, one of the [`encoded_formats`](Self::encoded_formats), at
65    /// `quality` from `0.0`, the smallest, to `1.0`, the best, where the format loses detail, or
66    /// the system's own where `None`: [`ImageErrorKind::Unsupported`] for a format it does not
67    /// encode.
68    fn encode_pixels(
69        &self,
70        pixels: PixelBuffer,
71        format: &str,
72        quality: Option<f32>,
73    ) -> ImageFuture<Vec<u8>>;
74
75    /// The system's hardware codecs, or `None` where it neither decodes into hardware buffers
76    /// nor encodes from them.
77    fn hardware_image_codecs(&self) -> Option<&dyn HardwareImageCodecs>;
78}
79
80/// An image opened by the system's codecs from its encoded bytes, as Apple's `CGImageSource` and
81/// Android's `ImageDecoder.Source` are: what it says of itself, read as it opened, and its
82/// pictures decoded as the app asks for them. A picture it does not have fails, as
83/// [`ImageErrorKind::Other`].
84///
85/// A host gets its own type back from an image it is given by downcasting through `Any`.
86pub trait ImageSource: Any {
87    /// Its format's MIME type, one of the [`ImageCodecs::decoded_formats`].
88    fn mime_type(&self) -> String;
89
90    /// Its size in pixels, upright, as its primary picture decodes at full size: a still image's
91    /// one, an animation's frames, which all share it, or a document's primary page.
92    fn size(&self) -> Size;
93
94    /// How its pictures go: one still picture, the frames of an animation, or the pages of a
95    /// document.
96    fn pictures(&self) -> ImagePictures;
97
98    /// How the file stores its primary picture turned from upright. It is decoded upright, and
99    /// [`size`](Self::size) is upright, so an app reads it to show it or to keep it.
100    fn orientation(&self) -> ImageOrientation;
101
102    /// What the file says of how its primary picture was taken.
103    fn metadata(&self) -> ImageMetadata;
104
105    /// Picture `index` in the app's memory, upright, scaled down to fit `max_size`, in pixels,
106    /// keeping its shape, where given; in a layout the system picks, which the buffer names. The
107    /// index is 0 for a still image, a frame's for an animation and a page's for a document
108    /// ([`pictures`](Self::pictures)).
109    fn decode_pixels(&self, index: u32, max_size: Option<Size>) -> ImageFuture<PixelBuffer>;
110}
111
112/// The system's codecs between encoded images and hardware buffers, with no copy through the
113/// app's memory, or `None` from [`ImageCodecs::hardware_image_codecs`] where it has none.
114pub trait HardwareImageCodecs {
115    /// Picture `index` of `image`, as [`ImageSource::decode_pixels`] names it, in a hardware buffer
116    /// of the app's own, for sampling, upright, scaled down to fit `max_size`, in pixels, keeping
117    /// its shape, where given:
118    /// [`ImageErrorKind::TooLarge`] where it is larger than a hardware buffer the system makes. An
119    /// image another host opened fails, as [`ImageErrorKind::Unsupported`].
120    fn decode(
121        &self,
122        image: &dyn ImageSource,
123        index: u32,
124        max_size: Option<Size>,
125    ) -> ImageFuture<Arc<dyn HardwareBuffer>>;
126
127    /// `buffer`'s pixels encoded in `format`, one of the image codecs'
128    /// [`encoded_formats`](ImageCodecs::encoded_formats), at `quality` as
129    /// [`ImageCodecs::encode_pixels`] takes it, reading what the GPU has finished writing, as
130    /// [`HardwareBuffer::read_pixels`] does: [`ImageErrorKind::Unsupported`] for a format it does
131    /// not encode, or a buffer whose pixels it does not read, such as one another host handed out.
132    fn encode(
133        &self,
134        buffer: &dyn HardwareBuffer,
135        format: &str,
136        quality: Option<f32>,
137    ) -> ImageFuture<Vec<u8>>;
138}
139
140/// How an image's pictures go together.
141#[derive(Clone, Debug, Default, PartialEq)]
142pub enum ImagePictures {
143    /// One picture.
144    #[default]
145    Still,
146    /// Frames shown one after another, as a GIF's, an animated PNG's, WebP's or a HEIF
147    /// sequence's.
148    Animation(ImageAnimation),
149    /// Pictures each of its own, as a TIFF's pages or the images of a HEIF collection.
150    Pages(ImagePages),
151}
152
153/// An animation: its frames and how many times it plays through them.
154#[derive(Clone, Debug, PartialEq, Eq)]
155pub struct ImageAnimation {
156    /// Its frames, in order; two at least.
157    pub frames: Vec<AnimationFrame>,
158    pub plays: AnimationPlays,
159}
160
161/// One frame of an animation.
162#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
163pub struct AnimationFrame {
164    /// How long it shows; `None` where the file says nothing, for which an app picks its own.
165    pub duration: Option<Duration>,
166}
167
168/// How many times an animation plays through its frames.
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub enum AnimationPlays {
171    /// This many times, one at least.
172    Times(u32),
173    Forever,
174}
175
176/// A document's pages, and which of them the file names as its main picture.
177#[derive(Clone, Debug, PartialEq)]
178pub struct ImagePages {
179    /// Its pages, in order; two at least.
180    pub pages: Vec<ImagePage>,
181    /// The index of the page the file names as its main picture: its first, except where a HEIF
182    /// names another.
183    pub primary: u32,
184}
185
186/// One page of a document, with a size and an orientation of its own.
187#[derive(Clone, Copy, Debug, PartialEq)]
188pub struct ImagePage {
189    /// Its size in pixels, upright.
190    pub size: Size,
191    pub orientation: ImageOrientation,
192}
193
194impl ImagePictures {
195    /// How many pictures the image has: one still, an animation's frames or a document's pages.
196    pub fn count(&self) -> usize {
197        match self {
198            ImagePictures::Still => 1,
199            ImagePictures::Animation(animation) => animation.frames.len(),
200            ImagePictures::Pages(pages) => pages.pages.len(),
201        }
202    }
203}
204
205/// How the picture a file stores is turned from upright: EXIF's `Orientation`, mirrored left to
206/// right where `mirrored`, then turned clockwise by `rotation`, to show it upright.
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
208pub struct ImageOrientation {
209    pub mirrored: bool,
210    pub rotation: ImageRotation,
211}
212
213/// How far a picture is turned clockwise.
214#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
215pub enum ImageRotation {
216    #[default]
217    None,
218    QuarterTurn,
219    HalfTurn,
220    ThreeQuarterTurn,
221}
222
223/// What an image's file says of how it was taken: EXIF's fields a photo app shows. A field is
224/// `None` where the file says nothing.
225#[derive(Clone, Debug, Default, PartialEq)]
226pub struct ImageMetadata {
227    /// When it was taken, as the camera's clock read it: EXIF's `DateTimeOriginal`, with its
228    /// `OffsetTimeOriginal`.
229    pub taken: Option<DateTime>,
230    /// The camera's maker, as the camera names itself: EXIF's `Make`.
231    pub camera_make: Option<String>,
232    /// The camera's model, as the camera names itself: EXIF's `Model`.
233    pub camera_model: Option<String>,
234    /// The lens, as the camera names it: EXIF's `LensModel`.
235    pub lens_model: Option<String>,
236    /// How long the shutter was open, in seconds: EXIF's `ExposureTime`.
237    pub exposure_time: Option<f64>,
238    /// The aperture, as an f-number: EXIF's `FNumber`.
239    pub f_number: Option<f64>,
240    /// The sensor's sensitivity, as an ISO speed: EXIF's `PhotographicSensitivity`.
241    pub iso: Option<u32>,
242    /// The lens's focal length, in millimetres: EXIF's `FocalLength`.
243    pub focal_length: Option<f64>,
244    /// The focal length on a 35 mm film camera with the same view, in millimetres: EXIF's
245    /// `FocalLengthIn35mmFilm`.
246    pub equivalent_focal_length: Option<f64>,
247    /// How far the exposure was set from the camera's metering, in stops: EXIF's
248    /// `ExposureBiasValue`.
249    pub exposure_bias: Option<f64>,
250    /// Whether the flash fired: EXIF's `Flash`.
251    pub flash_fired: Option<bool>,
252    /// Where it was taken: EXIF's GPS position.
253    pub location: Option<Location>,
254}
255
256/// A date and time of day as a clock read it, and how far that clock was from UTC.
257#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258pub struct DateTime {
259    pub year: i32,
260    /// From 1, January, to 12.
261    pub month: u8,
262    /// From 1.
263    pub day: u8,
264    pub hour: u8,
265    pub minute: u8,
266    pub second: u8,
267    /// Minutes ahead of UTC, negative behind it; `None` where the file does not say, so the
268    /// moment is the camera's local time, wherever it was.
269    pub utc_offset: Option<i16>,
270}
271
272/// A place on Earth, as GPS gives it: WGS 84.
273#[derive(Clone, Copy, Debug, PartialEq)]
274pub struct Location {
275    /// Degrees north of the equator, negative south of it.
276    pub latitude: f64,
277    /// Degrees east of Greenwich, negative west of it.
278    pub longitude: f64,
279    /// Metres above sea level, negative below it.
280    pub altitude: Option<f64>,
281}
282
283/// Why pixels were not read, decoded or encoded.
284#[derive(Clone, Debug, PartialEq, Eq)]
285pub struct ImageError {
286    pub kind: ImageErrorKind,
287    /// The system's own words, for logs: not for showing as they are.
288    pub message: String,
289}
290
291impl ImageError {
292    pub fn new(kind: ImageErrorKind, message: impl Into<String>) -> ImageError {
293        ImageError {
294            kind,
295            message: message.into(),
296        }
297    }
298}
299
300impl fmt::Display for ImageError {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        let kind = match self.kind {
303            ImageErrorKind::Unsupported => "unsupported",
304            ImageErrorKind::Damaged => "damaged",
305            ImageErrorKind::TooLarge => "too large",
306            ImageErrorKind::NotFound => "not found",
307            ImageErrorKind::OutOfMemory => "out of memory",
308            ImageErrorKind::Other => "failed",
309        };
310        write!(f, "image {kind}: {}", self.message)
311    }
312}
313
314impl std::error::Error for ImageError {}
315
316/// The kind of an image's failure, which an app words for its user and acts on.
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318pub enum ImageErrorKind {
319    /// A format the system does not decode or encode, or pixels in a layout it does not read.
320    Unsupported,
321    /// The bytes are of a format the system reads, and are not a whole image of it.
322    Damaged,
323    /// The image is larger than the system decodes it at into that memory; asked for at a
324    /// maximum size, it may decode.
325    TooLarge,
326    /// No file at the path.
327    NotFound,
328    /// More memory than the system has left for a hardware buffer, or than the platform lets the
329    /// app hold.
330    OutOfMemory,
331    /// Anything else the system reports.
332    Other,
333}
334
335/// What the image codecs, an image source and a hardware buffer's pixels answer.
336pub type ImageFuture<T> = Pin<Box<dyn Future<Output = Result<T, ImageError>>>>;