capsule_core/lqip/mod.rs
1//! LQIP — the low-quality image placeholder carried in every asset's signed sidecar.
2//!
3//! SSoT: [Thumbnails — LQIP](https://docs/design/thumbnails/#lqip).
4//!
5//! # Why this module exists at the crate root
6//!
7//! The placeholder is produced by the import pipeline, read by the native apps through the
8//! app FFI, and read by the browser through `capsule-wasm`. A placeholder that differed by
9//! which client imported the photo would be a visible defect, so there is exactly **one**
10//! implementation and it must be reachable from all three. That rules out
11//! `capsule_core::media`, the retired decode/encode stack that lives in `legacy-review/`
12//! and is `native`-only wherever it is restored. It equally rules out
13//! Rawshift, which `.claude/rules/capsule-core.md` forbids from wrapping Chromahash —
14//! Capsule imports it directly.
15//!
16//! This module is therefore **unconditional**: no feature gate, no `native`, and it compiles
17//! for `wasm32-unknown-unknown` (chromahash has zero runtime dependencies and ships a
18//! `simd128` backend). The one part that cannot be unconditional is the bridge to the sidecar
19//! record, because `crate::sidecar` is itself `native`-gated; that lives in
20//! [`sidecar`](crate::lqip::sidecar), behind the same gate, over this same encoder.
21//!
22//! # The contract
23//!
24//! Encoding is [Chromahash](https://crates.io/crates/chromahash) at
25//! [`chromahash::DEFAULT_TIER`] — **exactly 32 bytes**. Capsule does not vary the tier per
26//! asset, and four chromahash calls carry the whole contract; this module deliberately uses no
27//! more than these:
28//!
29//! | Call | Role here |
30//! | --- | --- |
31//! | `encode(w, h, &rgba, gamut)` | [`Lqip::encode`](crate::lqip::Lqip::encode) — generation at the default tier. |
32//! | `decode_capped(max_w, max_h)` | [`Lqip::decode_capped`](crate::lqip::Lqip::decode_capped) — the band-limited render. |
33//! | `average_color()` | [`Lqip::dominant_color`](crate::lqip::Lqip::dominant_color) — the DC-only fallback fill. |
34//! | `from_bytes` / `as_bytes` | [`Lqip::from_bytes`](crate::lqip::Lqip::from_bytes) / [`Lqip::as_bytes`](crate::lqip::Lqip::as_bytes) — the sidecar round trip. |
35//!
36//! Notably absent: any pre-resize of the source. The 100 px downscale the retired ThumbHash
37//! implementation performed before hashing was a ThumbHash artifact — chromahash takes the full
38//! RGBA frame and band-limits on the *read* side via `decode_capped`, so pre-resizing here
39//! would silently cap fidelity that the format is able to carry.
40//!
41//! # Versioned fallback
42//!
43//! [`LQIP_FORMAT_V1`](crate::lqip::LQIP_FORMAT_V1) tags the payload inside the sidecar. A reader
44//! that does not recognize the version — or that holds bytes `from_bytes` rejects — paints the
45//! solid `dominant_color` fill instead of misrendering (see [`render`](crate::lqip::render)).
46//! That is the mechanism that makes a future chromahash revision a versioned change rather than a
47//! silent break, and it is also what makes any stale non-chromahash payload degrade to a flat
48//! colour rather than to noise.
49
50use thiserror::Error;
51
52// The sidecar bridge, and only the bridge, is `native`-gated — because `crate::sidecar` is.
53// The encoder above stays unconditional, which is what keeps `capsule-wasm` and the native
54// surfaces on one implementation.
55#[cfg(feature = "native")]
56pub mod sidecar;
57
58/// The LQIP chromahash format version written into the sidecar.
59///
60/// This is Capsule's *sidecar* format version, not chromahash's own wire-format generation
61/// (`chromahash::FORMAT_VERSION`, which is self-describing inside the payload's first byte).
62/// It stays `1`: the sidecar schema has always declared this field as `Lqip.chromahash` and
63/// version 1 as the chromahash format version. The ThumbHash payloads the interim
64/// implementation wrote were an undeclared stand-in for a dependency that had not shipped, not
65/// the declared encoding — so writing real chromahash under version 1 makes the code match a
66/// contract that never changed.
67///
68/// That is legitimate **only** while the migration is total, i.e. no persisted sidecar carries
69/// a ThumbHash payload under version 1. ThumbHash payloads are shorter than 32 bytes but
70/// overlap the lower chromahash tiers in length, so byte length alone cannot discriminate a
71/// stale one. Should such a sidecar ever exist, the fix is a *new* format version — never a
72/// redefinition of this one.
73pub const LQIP_FORMAT_V1: u16 = 1;
74
75/// The source colour space an [`Lqip::encode`] call is told to interpret its pixels in.
76///
77/// A deliberate mirror of [`chromahash::Gamut`] rather than a re-export: this is a public
78/// Capsule type that crosses the FFI and the wasm boundary, so a pre-1.0 dependency must not be
79/// able to reshape it. The mapping is exhaustive in both directions and [`From`] keeps it
80/// compile-checked.
81///
82/// **The gamut is an encode-side input only.** The sidecar stores the payload, the format
83/// version and the fallback colour — it does not store the gamut, and chromahash does not carry
84/// it in the payload either. Once encoded, the source gamut is not recoverable from the
85/// sidecar; the decode side always renders to sRGB.
86#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
87pub enum Gamut {
88 /// sRGB / Rec. 709 primaries — the default and the only safe assumption for an
89 /// untagged source.
90 #[default]
91 Srgb,
92 /// Display P3 (DCI-P3 primaries, sRGB transfer) — the common wide-gamut capture space.
93 DisplayP3,
94 /// Adobe RGB (1998).
95 AdobeRgb,
96 /// ITU-R BT.2020 — the ultra-wide gamut used by HDR sources.
97 Bt2020,
98 /// ProPhoto RGB (ROMM RGB) — the widest of the raw-editing spaces.
99 ProPhotoRgb,
100}
101
102impl From<Gamut> for chromahash::Gamut {
103 fn from(gamut: Gamut) -> Self {
104 match gamut {
105 Gamut::Srgb => chromahash::Gamut::Srgb,
106 Gamut::DisplayP3 => chromahash::Gamut::DisplayP3,
107 Gamut::AdobeRgb => chromahash::Gamut::AdobeRgb,
108 Gamut::Bt2020 => chromahash::Gamut::Bt2020,
109 Gamut::ProPhotoRgb => chromahash::Gamut::ProPhotoRgb,
110 }
111 }
112}
113
114/// A decoded placeholder: packed RGBA8, `width * height * 4` bytes.
115///
116/// Deliberately a bare owned triple rather than `media::image::buffer::ImageBuffer`. That type
117/// is inside the retiring `media` stack and carries `PixelFormat` / `ComponentType` /
118/// `ColorSpace` discriminants this module has no use for — a placeholder is always packed
119/// RGBA8 in sRGB. Depending on it would re-gate this module behind `media` (and therefore
120/// `native`), which is precisely the coupling the slice exists to break; introducing a *second*
121/// general-purpose buffer type outside `media` would instead pre-empt whatever the Rawshift
122/// rebuild lands. The narrowest thing that carries the whole result is the right seam, and the
123/// `media`-side adapter converts it back to an `ImageBuffer` for as long as that stack lives.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct RgbaImage {
126 /// Width in pixels; always at least 1.
127 pub width: u32,
128 /// Height in pixels; always at least 1.
129 pub height: u32,
130 /// Packed RGBA8 samples, `width * height * 4` bytes long.
131 pub rgba: Vec<u8>,
132}
133
134impl RgbaImage {
135 /// The 1x1 opaque solid fill used as the versioned fallback.
136 fn solid([r, g, b]: [u8; 3]) -> Self {
137 Self {
138 width: 1,
139 height: 1,
140 rgba: vec![r, g, b, 255],
141 }
142 }
143}
144
145/// Why an LQIP could not be produced or parsed.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
147pub enum LqipError {
148 /// The source frame has a zero dimension. Guarded here because `chromahash::encode`
149 /// *panics* on it, and an undecodable still must degrade to "no LQIP", never to a crash in
150 /// the import pipeline.
151 #[error("LQIP source has a zero dimension ({width}x{height})")]
152 ZeroDimension {
153 /// The width that was passed.
154 width: u32,
155 /// The height that was passed.
156 height: u32,
157 },
158 /// The RGBA buffer length does not match the stated dimensions. Also a `chromahash::encode`
159 /// panic, so it is a checked error here.
160 #[error("LQIP source is {actual} bytes; {width}x{height} RGBA8 needs {expected}")]
161 PixelCountMismatch {
162 /// The width that was passed.
163 width: u32,
164 /// The height that was passed.
165 height: u32,
166 /// The buffer length `width * height * 4` implies. `u128` because that product
167 /// overflows `u64` at the top of the `u32` dimension range, and an error path must not
168 /// panic on the very input it exists to reject.
169 expected: u128,
170 /// The buffer length that was actually passed.
171 actual: u128,
172 },
173 /// The bytes are not a structurally valid chromahash payload. Callers holding sidecar
174 /// bytes should prefer [`render`], which turns this into the `dominant_color` fill.
175 #[error("not a valid chromahash payload: {0}")]
176 InvalidHash(chromahash::ChromaHashError),
177}
178
179/// A chromahash LQIP payload — 32 bytes at [`chromahash::DEFAULT_TIER`].
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct Lqip(chromahash::ChromaHash);
182
183impl Lqip {
184 /// Encode a full-resolution RGBA8 frame at the committed default tier.
185 ///
186 /// `rgba` must be exactly `width * height * 4` bytes of packed RGBA8, interpreted in
187 /// `gamut`. The frame is **not** pre-resized: chromahash consumes the whole thing and
188 /// band-limits at [`decode_capped`](Self::decode_capped) time.
189 ///
190 /// Bit-exact for a given `(width, height, rgba, gamut)` on every platform chromahash
191 /// supports, which is what lets the CLI, the FFI and `capsule-wasm` agree byte-for-byte.
192 pub fn encode(width: u32, height: u32, rgba: &[u8], gamut: Gamut) -> Result<Self, LqipError> {
193 if width == 0 || height == 0 {
194 return Err(LqipError::ZeroDimension { width, height });
195 }
196 // `u32 * u32 * 4` overflows `u64` near the top of the range, so the comparison is done
197 // in `u128`, where it cannot.
198 let expected = u128::from(width) * u128::from(height) * 4;
199 let actual = rgba.len() as u128;
200 if expected != actual {
201 return Err(LqipError::PixelCountMismatch {
202 width,
203 height,
204 expected,
205 actual,
206 });
207 }
208
209 let hash = chromahash::ChromaHash::encode(width, height, rgba, gamut.into());
210 tracing::trace!(
211 width,
212 height,
213 ?gamut,
214 bytes = hash.as_bytes().len(),
215 "encoded LQIP chromahash"
216 );
217 Ok(Self(hash))
218 }
219
220 /// Parse sidecar bytes back into a payload, validating version, tier, reserved bits and
221 /// length. An `Ok` value is guaranteed to decode.
222 pub fn from_bytes(bytes: &[u8]) -> Result<Self, LqipError> {
223 chromahash::ChromaHash::from_bytes(bytes)
224 .map(Self)
225 .map_err(LqipError::InvalidHash)
226 }
227
228 /// The raw payload — what the sidecar's `lqip.chromahash` field carries.
229 pub fn as_bytes(&self) -> &[u8] {
230 self.0.as_bytes()
231 }
232
233 /// The average colour as opaque RGB — the `dominant_color` fallback fill, read straight
234 /// from the DC coefficients without a full decode.
235 pub fn dominant_color(&self) -> [u8; 3] {
236 let [r, g, b, _a] = self.0.average_color();
237 [r, g, b]
238 }
239
240 /// The average colour as RGBA, alpha included.
241 pub fn average_rgba(&self) -> [u8; 4] {
242 self.0.average_color()
243 }
244
245 /// Decode to a placeholder no larger than `max_width` x `max_height` — a band-limited,
246 /// alias-free render of exactly the box being painted, rather than a full-size decode the
247 /// caller then scales down.
248 ///
249 /// A zero bound is raised to 1: chromahash would otherwise return an empty buffer, and
250 /// every caller of this is about to paint something.
251 pub fn decode_capped(&self, max_width: u32, max_height: u32) -> RgbaImage {
252 let (width, height, rgba) = self.0.decode_capped(max_width.max(1), max_height.max(1));
253 RgbaImage {
254 width,
255 height,
256 rgba,
257 }
258 }
259}
260
261/// Render a stored placeholder record, honouring the versioned fallback.
262///
263/// The happy path is a recognized [`LQIP_FORMAT_V1`] payload that parses: it is decoded,
264/// band-limited to `max_width` x `max_height`. Anything else — an unknown future version, or
265/// bytes `from_bytes` rejects (a corrupt payload, or a stale non-chromahash one) — returns the
266/// 1x1 solid `dominant_color` fill. A reader must never misrender a payload it does not
267/// understand.
268pub fn render(
269 format_version: u16,
270 chromahash: &[u8],
271 dominant_color: [u8; 3],
272 max_width: u32,
273 max_height: u32,
274) -> RgbaImage {
275 if format_version != LQIP_FORMAT_V1 {
276 tracing::debug!(
277 format_version,
278 known = LQIP_FORMAT_V1,
279 "unrecognized LQIP format version; painting the dominant-color fill"
280 );
281 return RgbaImage::solid(dominant_color);
282 }
283 match Lqip::from_bytes(chromahash) {
284 Ok(hash) => hash.decode_capped(max_width, max_height),
285 Err(error) => {
286 tracing::debug!(
287 %error,
288 len = chromahash.len(),
289 "undecodable LQIP payload; painting the dominant-color fill"
290 );
291 RgbaImage::solid(dominant_color)
292 }
293 }
294}
295
296#[cfg(test)]
297mod tests;