Skip to main content

capsule_core/
derivative_format.rs

1//! The closed set of committed still-derivative formats, and the structural check over it.
2//!
3//! SSoT: [Thumbnails and Previews](https://docs/design/thumbnails/) — the tier table's format
4//! column *is* this enum, and "every receiver (and every federated peer) compares
5//! `DerivativeManifest.format` against this list" is
6//! [`verify_still_format`](crate::derivative_format::verify_still_format).
7//!
8//! # Why this is at the crate root and not in `capsule_core::media`
9//!
10//! It was in `media` first, and that was a placement mistake rather than a constraint. `media`
11//! is behind the `media` feature that `native` implies, so `capsule-server` and `capsule-wasm`
12//! — both `default-features = false` — cannot link it. Those are exactly the two crates that
13//! *receive* a manifest they did not author, which is where a structural rejection has to run.
14//! A closed set only a producer can evaluate is not a closed set.
15//!
16//! So it lives here, beside nothing and depending on nothing but
17//! [`crate::crypto::provenance`], which is itself unconditional for the same reason. This module
18//! is the one public path to both names: `media` does not re-export them.
19//!
20//! This mirrors [`crate::lqip`]: a contract every surface needs cannot live inside a
21//! feature-gated stack, however natural the stack looks as a home.
22
23use std::fmt;
24
25use crate::crypto::provenance::{DerivativeManifest, DerivativeRole};
26
27/// The closed set of committed still-derivative formats — the tier table's format column.
28///
29/// The wire value is [`mime`](Self::mime), carried in `DerivativeManifest.format`. A value
30/// outside this set is a structural rejection, never a "future format to ignore".
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum DerivativeFormat {
33    /// **JPEG XL** — the committed primary/master still codec. Encodable, **lossy**, only under
34    /// the opt-in `media-linked-codecs` feature: libjxl is the one JXL encoder `rawshift-image`
35    /// has, and it is a C++ build the pure-Rust builds do not carry.
36    Jxl,
37    /// **AVIF** — the universal delivery format for clients without a JXL decoder. Encodable in
38    /// every build, through gamut's pure-Rust AV1 intra encoder.
39    Avif,
40    /// **WebP** — the last-resort delivery fallback. Not encodable in this build: the crate's
41    /// WebP encoder is not enabled — see `media::StillFormat::WebP`, which cannot be linked from
42    /// here because `media` is feature-gated and this module is not.
43    WebP,
44    /// The recognised `format = "original"` sentinel: the tier **references** the original asset
45    /// rather than generating a redundant derivative, because the source is not larger than the
46    /// tier's cap. **Distinct from an absent derivative** — this is an explicit, signed marker,
47    /// where absence means "rebuildable from the original".
48    ///
49    /// A sentinel derivative carries **no bytes of its own** (`media::GeneratedDerivative::bytes`
50    /// is empty). "References" is the operative word in the contract: the signed manifest's
51    /// `ciphertext_hash` content-addresses the original, which the holder already has, so
52    /// copying the bytes under a thumbnail's name would duplicate a file sitting two directories
53    /// up *and* re-expose the original's EXIF — GPS included — as a derivative blob, where a
54    /// re-encoded thumbnail is metadata-free by construction.
55    Original,
56}
57
58impl DerivativeFormat {
59    /// The committed still formats per tier, in delivery-preference order: the JXL master, then
60    /// the AVIF -> WebP delivery variants.
61    pub const STILL_DELIVERY_ORDER: [Self; 3] = [Self::Jxl, Self::Avif, Self::WebP];
62
63    /// The exact wire string for `DerivativeManifest.format`.
64    pub const fn mime(self) -> &'static str {
65        match self {
66            Self::Jxl => "image/jxl",
67            Self::Avif => "image/avif",
68            Self::WebP => "image/webp",
69            Self::Original => "original",
70        }
71    }
72
73    /// The on-disk file extension for a persisted derivative of this format. `Original` has
74    /// none of its own — it reuses the source asset's.
75    pub const fn extension(self) -> Option<&'static str> {
76        match self {
77            Self::Jxl => Some("jxl"),
78            Self::Avif => Some("avif"),
79            Self::WebP => Some("webp"),
80            Self::Original => None,
81        }
82    }
83
84    /// Parse a `DerivativeManifest.format` value against the closed set. `None` **is** the
85    /// structural rejection.
86    pub fn parse(s: &str) -> Option<Self> {
87        match s {
88            "image/jxl" => Some(Self::Jxl),
89            "image/avif" => Some(Self::Avif),
90            "image/webp" => Some(Self::WebP),
91            "original" => Some(Self::Original),
92            _ => None,
93        }
94    }
95
96    /// Whether a `format` string names a currently-recognised still-derivative format — the
97    /// exact check a receiver runs.
98    pub fn is_recognized(s: &str) -> bool {
99        Self::parse(s).is_some()
100    }
101
102    /// Whether this build can produce bytes in this format.
103    ///
104    /// Feature-dependent on purpose: the answer is about *this build*, and the JXL encoder is
105    /// linked only by `media-linked-codecs`. The mobile FFI and the `rust-cross` targets build
106    /// without it, and there JXL is a recorded per-`(tier, format)` deferral rather than a gap.
107    pub const fn is_encodable(self) -> bool {
108        match self {
109            Self::Avif | Self::Original => true,
110            Self::Jxl => cfg!(feature = "media-linked-codecs"),
111            Self::WebP => false,
112        }
113    }
114}
115
116impl fmt::Display for DerivativeFormat {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(self.mime())
119    }
120}
121
122/// The closed-set check a receiver runs on a still-role derivative manifest.
123///
124/// Returns the parsed format for a `thumbnail` or `preview` manifest whose `format` is in the
125/// closed set. An embedding-role manifest is **not** rejected: its `format` is
126/// `embedding/{model_id}`, which this set deliberately does not model, so it is reported as
127/// [`None`] rather than as a violation.
128///
129/// # Errors
130/// `media::MediaError::UnsupportedFormat` — which carries the still format Capsule *would* have
131/// needed — is not what an unrecognised value produces, because there is no still format to name
132/// (and this module cannot reference `media` in any case: it is unconditional and `media` is
133/// not). An unrecognised still-role format is `Err(format.to_string())`.
134pub fn verify_still_format(
135    manifest: &DerivativeManifest,
136) -> Result<Option<DerivativeFormat>, String> {
137    verify_still_role_format(manifest.core.role, &manifest.core.format)
138}
139
140/// The same closed-set check over a bare `(role, format)` pair — the **key-free** entry point.
141///
142/// [`verify_still_format`] takes a signed [`DerivativeManifest`], which a key-free receiver
143/// (the server's upload gate) never holds: it sees the unencrypted envelope projection, which
144/// declares the derivative's role and format as two plain fields. Both entry points answer
145/// identically for the same pair, because [`verify_still_format`] is this function applied to
146/// the manifest's own fields — there is one closed set and one check over it.
147///
148/// # Errors
149/// An unrecognised still-role format is `Err(format.to_string())`, exactly as
150/// [`verify_still_format`] reports it.
151pub fn verify_still_role_format(
152    role: DerivativeRole,
153    format: &str,
154) -> Result<Option<DerivativeFormat>, String> {
155    match role {
156        DerivativeRole::Thumbnail | DerivativeRole::Preview => DerivativeFormat::parse(format)
157            .map(Some)
158            .ok_or_else(|| format.to_owned()),
159        // Not a still. The embedding-role format grammar belongs to `crate::ml`.
160        DerivativeRole::Embedding => Ok(None),
161    }
162}
163
164/// Whether an imported asset got thumbnail/preview derivatives — and if not, **why**
165///
166/// Capsule is a backup tool, so this never gates admission: the original is imported as a
167/// signed, encrypted, verifiable asset in every case below. What varies is only whether a
168/// thumbnail/preview and an LQIP could be produced alongside it. The point of the enum is to
169/// keep the two "no derivative" reasons apart, because one is expected and one is a bug:
170/// a missing codec is a known, deferred gap, while a *supported* format that fails to decode
171/// is a real problem someone should look at.
172///
173/// It lives beside the format set rather than with the import pipeline that produces it because
174/// a drop adoption reports it too ([`AdoptedDrop`](crate::drop::AdoptedDrop)), and the drop
175/// types are part of the stateless core.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub enum DerivativeStatus {
178    /// The still decoded: `dimensions` and `lqip` came from real pixels, and the derivatives
179    /// this build can encode were generated and signed. **Independent of how many *formats*
180    /// deferred** — a decoded still whose JXL and WebP variants have no encoder here is still
181    /// `Decoded`, because it has a renderable AVIF thumbnail. The per-format gap is counted
182    /// separately, by the import summary's deferred-format count.
183    Decoded,
184    /// **Expected deferral.** This build links no codec for the asset's format — see the media
185    /// stack's supported still formats for what it does link. The original is safely backed up;
186    /// dimensions fall back to EXIF and there is no LQIP or thumbnail until the codec lands, at
187    /// which point derivatives can be backfilled from the stored original. Counted by the import
188    /// summary's deferred-derivative count.
189    ///
190    /// What reaches here today: HEIC (refused by licence policy), WebP and the RAW families
191    /// whose decoders are not enabled, AVIF without `media-avif-decode` or on a host with no
192    /// AV1 decoder for its profile, and every video, whose derivatives no build generates yet.
193    DeferredNoCodec,
194    /// **A real problem.** The format *is* one this build can decode, but these particular
195    /// bytes did not decode — truncation, corruption, or a decoder bug. The original is still
196    /// imported (the bytes are backed up verbatim, whatever they are), but this is worth
197    /// investigating rather than shrugging at.
198    DecodeFailed,
199    /// Nothing to decode: neither the bytes' header nor the extension names a still image
200    /// Capsule models and there is no derivative to make — an XMP sidecar, an SVG, a document,
201    /// or an unknown suffix. Distinct from [`DeferredNoCodec`](Self::DeferredNoCodec), which is
202    /// a still whose codec is merely absent and whose derivatives are therefore backfillable.
203    /// A **video** is not this: its derivatives are committed to by the tier table and deferred
204    /// until their codec lands, so a video import reports `DeferredNoCodec`.
205    NotAKnownStill,
206}
207
208impl DerivativeStatus {
209    /// Whether the asset was imported *without* thumbnail/preview derivatives because no codec
210    /// exists for it — the deferred-gap count, excluding genuine decode failures and non-stills.
211    pub const fn is_deferred_for_missing_codec(self) -> bool {
212        matches!(self, Self::DeferredNoCodec)
213    }
214}
215
216#[cfg(test)]
217mod tests;