capsule_core/media/detect.rs
1//! Capsule's closed still-format set, its magic-byte table, and the codec-coverage predicate.
2//!
3//! # Why Capsule sniffs rather than delegating
4//!
5//! `rawshift-image` ships `detect_standard_format`, and Capsule deliberately does not use it as
6//! the primary table. Its `heic | heis | hevc | hevx` arm is `#[cfg(feature = "heic-decode")]`,
7//! so a build without the HEIC codec cannot *recognise* an Apple HEIC either — its major brand
8//! is `heic`. That would make the typed refusal for exactly the formats this build cannot decode
9//! depend on whether it can decode them: a HEIC would arrive as "not a still image" instead of
10//! "a still image with no codec here", which is the difference between a reportable,
11//! backfillable gap and an apparent non-image. Capsule's reference library is HEIC end to end,
12//! so that distinction is the whole point of this module.
13//!
14//! Two smaller reasons ride along, both about the brand table rather than a feature: the crate
15//! reads the generic HEIF brand `mif1` as **AVIF**, and it does not recognise `heix` or `msf1`
16//! under any configuration.
17//!
18//! The two tables are held together by a test rather than by hope:
19//! `capsule-core`'s `still_format_agrees_with_rawshift_detection` asserts that for every format
20//! both sides define unconditionally, Capsule's sniff and `detect_standard_format` name the same
21//! thing.
22//!
23//! # Bytes first, extension second
24//!
25//! Detection is by header, so a `.jpg` that is really a HEIC is classified as HEIC. The
26//! extension is consulted in exactly two places, both of them cases a header genuinely cannot
27//! settle:
28//!
29//! 1. **RAW refinement.** ARW, CR2, DNG and NEF are TIFF containers and CR3 is ISO-BMFF; their
30//! headers are their container's, so only the extension distinguishes a Sony ARW from a
31//! scanner's TIFF. A misrefinement costs a deferral, never wrong pixels: ARW and DNG are
32//! decoded by `rawshift-image`'s RAW reader, which identifies the file again from its own
33//! IFD0 (`DNGVersion`, then `Make`) and refuses one it cannot place as an unsupported
34//! variant, and the other RAW families do not decode at all.
35//! 2. **Fallback.** When the header sniffs to nothing at all.
36
37use std::fmt;
38
39/// The decode budget in pixels, refused **before** the decoder allocates.
40///
41/// **128 Mpx**, which admits every real camera — a 102 Mpx medium-format frame has ~25%
42/// headroom — while bounding what one still can ask the process for.
43///
44/// The bound is worth stating honestly, because the naive figure is a large understatement. A
45/// frame at this ceiling costs, in sequence and with overlap: 0.77 GB for the decoder's `u16`
46/// samples, another 0.77 GB where it reallocates to drop an alpha channel, 0.51 GB for
47/// Capsule's RGBA8 copy, and 0.77 GB again when the encode path widens a tier-sized frame back
48/// to RGB `u16`. Peak is on the order of **2.5 GB**, not the ~1 GB a single buffer suggests.
49/// Since `media` is implied by `native`, that peak happens on a phone as well as a workstation,
50/// where it is an OOM kill rather than an error — which is the reason this is not simply set as
51/// high as an allocation bomb would require.
52pub const MAX_DECODE_PIXELS: u64 = 128_000_000;
53
54/// The closed set of still-image formats Capsule models.
55///
56/// Closed on purpose: a still Capsule cannot name is not a still it silently ignores, it is a
57/// [`MediaError::NotAStillImage`](super::MediaError::NotAStillImage). Membership here says
58/// "Capsule knows this is a photo"; [`is_decodable`](Self::is_decodable) says whether *this
59/// build* can read its pixels. The two are deliberately separate — that gap is what
60/// `DerivativeStatus::DeferredNoCodec` reports.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum StillFormat {
63 /// JPEG / JFIF. Decoded by `gamut-jpeg`.
64 Jpeg,
65 /// PNG. Decoded by `gamut-png`; alpha is flattened at the decode boundary.
66 Png,
67 /// WebP. **Recognised, not decoded.** `rawshift-image`'s WebP is pure-Rust `gamut-webp` at
68 /// the pinned revision, so it would build for every target, but its `webp-decode` feature is
69 /// not enabled here: turning a format on is its own change, with its own fixtures.
70 WebP,
71 /// JPEG XL. Decoded by `gamut-jxl` (jxl-rs). Encode needs C++ libjxl (`media-linked-codecs`).
72 Jxl,
73 /// TIFF. Decoded by the `tiff` crate. Also the container of most RAW families.
74 Tiff,
75 /// GIF. Decoded by `gif`; the first frame only.
76 Gif,
77 /// Netpbm (P5/P6/P7/PFM). Recognised, not decoded: the `ppm-decode` backend is deliberately
78 /// not enabled. Netpbm is an intermediate and test-fixture format rather than something a
79 /// photo library holds, so recognising it and deferring is the honest outcome — and it costs
80 /// one fewer dependency than a codec nobody's library needs.
81 Ppm,
82 /// AVIF. Decoded by `gamut-avif` under the opt-in `media-avif-decode` feature, its AV1
83 /// codestream through a hardware decoder where the host has one; recognised and refused
84 /// without the feature, and deferred at decode on a host with no AV1 decoder or whose
85 /// hardware decoder refuses the codestream's profile.
86 Avif,
87 /// HEIC / HEIF. Recognised, never decoded: libheif and its HEVC decoder libde265 are
88 /// LGPL-3.0, which licence policy excludes (issue #588).
89 Heic,
90 /// Sony ARW. Decoded by `rawshift-image`'s RAW pipeline (issue #589) where the raw frame is
91 /// lossless JPEG (compression 7, Sony's "lossless compressed" mode on current bodies); the
92 /// uncompressed and lossy "compressed RAW" modes have no upstream decoder and defer as an
93 /// unsupported variant.
94 Arw,
95 /// Canon CR2.
96 Cr2,
97 /// Canon CR3.
98 Cr3,
99 /// Canon CRW.
100 Crw,
101 /// Adobe DNG (including Apple ProRAW). Decoded by `rawshift-image`'s RAW pipeline (issue
102 /// #589) where the raw IFD is uncompressed, lossless JPEG or JPEG XL (ProRAW); a DNG with
103 /// a Deflate image defers as an unsupported variant until upstream bounds its inflate
104 /// (visualcommons/rawshift#82).
105 Dng,
106 /// Nikon NEF.
107 Nef,
108 /// Fujifilm RAF.
109 Raf,
110}
111
112/// Every format this build can read pixels out of — the codec-coverage table, in one place.
113///
114/// Logged verbatim on a deferral so the gap is legible in the field rather than only in a doc.
115/// AVIF is a member only under the opt-in `media-avif-decode` feature, which the mobile FFI and
116/// the cross builds do not enable; even with it, its pixels decode only on a host with a
117/// hardware AV1 decoder, and anywhere else decode defers it (`media::decode`). ARW and DNG
118/// are the two RAW families upstream calls `raw-stabilizing`, pure Rust and so in every `media`
119/// build; the `raw-incomplete` five (CR2, CR3, CRW, NEF, RAF) stay recognised and refused.
120pub const SUPPORTED_STILL_FORMATS: &[StillFormat] = &[
121 StillFormat::Jpeg,
122 StillFormat::Png,
123 StillFormat::Jxl,
124 StillFormat::Tiff,
125 StillFormat::Gif,
126 StillFormat::Arw,
127 StillFormat::Dng,
128 #[cfg(feature = "media-avif-decode")]
129 StillFormat::Avif,
130];
131
132/// The RAW families, all of them recognised. ARW and DNG decode; the rest are refused.
133const RAW_FORMATS: &[StillFormat] = &[
134 StillFormat::Arw,
135 StillFormat::Cr2,
136 StillFormat::Cr3,
137 StillFormat::Crw,
138 StillFormat::Dng,
139 StillFormat::Nef,
140 StillFormat::Raf,
141];
142
143impl StillFormat {
144 /// Whether *this build* can read pixels out of the format — the single codec-coverage
145 /// predicate, and the gate the decode path checks before touching a decoder.
146 pub fn is_decodable(self) -> bool {
147 SUPPORTED_STILL_FORMATS.contains(&self)
148 }
149
150 /// Whether the format is one of the RAW families, which decode through `rawshift-image`'s RAW
151 /// pipeline rather than its standard-image one. Their container is TIFF or ISO-BMFF, so the
152 /// extension is what names the family. Only ARW and DNG are also
153 /// [decodable](Self::is_decodable).
154 pub fn is_raw(self) -> bool {
155 RAW_FORMATS.contains(&self)
156 }
157
158 /// The canonical media type — what the sidecar's `content_type` carries when detection
159 /// succeeded.
160 pub const fn mime(self) -> &'static str {
161 match self {
162 Self::Jpeg => "image/jpeg",
163 Self::Png => "image/png",
164 Self::WebP => "image/webp",
165 Self::Jxl => "image/jxl",
166 Self::Tiff => "image/tiff",
167 Self::Gif => "image/gif",
168 Self::Ppm => "image/x-portable-anymap",
169 Self::Avif => "image/avif",
170 Self::Heic => "image/heic",
171 Self::Arw => "image/x-sony-arw",
172 Self::Cr2 => "image/x-canon-cr2",
173 Self::Cr3 => "image/x-canon-cr3",
174 Self::Crw => "image/x-canon-crw",
175 Self::Dng => "image/x-adobe-dng",
176 Self::Nef => "image/x-nikon-nef",
177 Self::Raf => "image/x-fuji-raf",
178 }
179 }
180
181 /// The lowercase extension table — the *fallback*, used only where a header cannot settle
182 /// the question (see the module docs). Extensions arrive lowercased.
183 pub fn from_extension(ext: &str) -> Option<Self> {
184 Some(match ext {
185 "jpg" | "jpeg" | "jpe" | "jfif" => Self::Jpeg,
186 "png" => Self::Png,
187 "webp" => Self::WebP,
188 "jxl" => Self::Jxl,
189 "tif" | "tiff" => Self::Tiff,
190 "gif" => Self::Gif,
191 "ppm" | "pgm" | "pnm" | "pfm" => Self::Ppm,
192 "avif" | "avifs" => Self::Avif,
193 "heic" | "heif" | "hif" => Self::Heic,
194 "arw" => Self::Arw,
195 "cr2" => Self::Cr2,
196 "cr3" => Self::Cr3,
197 "crw" => Self::Crw,
198 "dng" => Self::Dng,
199 "nef" | "nrw" => Self::Nef,
200 "raf" => Self::Raf,
201 _ => return None,
202 })
203 }
204
205 /// Sniff the format from the file header alone.
206 ///
207 /// `None` means "no still image Capsule models starts like this" — a video, an SVG, an XMP
208 /// sidecar, or noise. A RAW file sniffs to its *container* here ([`Tiff`](Self::Tiff), or
209 /// `None` for CR3's unrecognised `ftyp` brand); [`detect`](Self::detect) is what refines it.
210 ///
211 /// Each signature carries **its own** length requirement rather than sharing one floor: a
212 /// Netpbm header is eleven bytes and a JPEG's SOI three, so a blanket minimum would report
213 /// a perfectly well-formed short file as "not an image".
214 pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
215 let at = |start: usize, needle: &[u8]| -> bool {
216 bytes
217 .get(start..start + needle.len())
218 .is_some_and(|window| window == needle)
219 };
220
221 if at(0, b"GIF87a") || at(0, b"GIF89a") {
222 return Some(Self::Gif);
223 }
224 if at(0, b"\xFF\xD8\xFF") {
225 return Some(Self::Jpeg);
226 }
227 if at(0, b"\x89PNG\r\n\x1a\n") {
228 return Some(Self::Png);
229 }
230 if at(0, b"RIFF") && at(8, b"WEBP") {
231 return Some(Self::WebP);
232 }
233 // Bare JXL codestream, then the ISO-BMFF-wrapped form.
234 if at(0, b"\xFF\x0A") {
235 return Some(Self::Jxl);
236 }
237 if at(4, b"JXL ") {
238 return Some(Self::Jxl);
239 }
240 if at(0, b"II\x2A\x00") || at(0, b"MM\x00\x2A") {
241 return Some(Self::Tiff);
242 }
243 if at(4, b"ftyp")
244 && let Some(brand) = bytes.get(8..12)
245 {
246 return Self::from_isobmff_brand(brand);
247 }
248 // Netpbm: 'P' + a binary version + whitespace. P1-P4 are excluded because the
249 // `zune-ppm` backend does not decode them, matching `rawshift-image`.
250 if let Some(&[b'P', version, space]) = bytes.get(..3)
251 && matches!(version, b'5' | b'6' | b'7' | b'F' | b'f')
252 && space.is_ascii_whitespace()
253 {
254 return Some(Self::Ppm);
255 }
256 None
257 }
258
259 /// The ISO-BMFF `ftyp` brand table.
260 ///
261 /// `mif1` is the generic HEIF brand and is claimed in practice by both HEIC and AVIF
262 /// writers. Capsule reads it as HEIC because the reference library is HEIC end to end;
263 /// `rawshift-image` reads it as AVIF. The divergence is cosmetic while neither decodes —
264 /// both produce the same
265 /// [`UnsupportedFormat`](super::MediaError::UnsupportedFormat) refusal and the same
266 /// `DeferredNoCodec` status — and it is a log-label difference, never a pixel difference.
267 fn from_isobmff_brand(brand: &[u8]) -> Option<Self> {
268 Some(match brand {
269 b"avif" | b"avis" => Self::Avif,
270 b"heic" | b"heix" | b"heis" | b"hevc" | b"hevx" | b"msf1" | b"mif1" => Self::Heic,
271 b"crx " => Self::Cr3,
272 _ => return None,
273 })
274 }
275
276 /// Identify a still: header first, extension only where a header cannot settle it.
277 ///
278 /// `ext` is the source file's lowercase extension without the dot (`""` when it has none).
279 /// The two extension-consulting cases are documented on the module.
280 pub fn detect(bytes: &[u8], ext: &str) -> Option<Self> {
281 match Self::from_bytes(bytes) {
282 // A TIFF header is also every TIFF-based RAW's header. Refine on the extension, and
283 // only ever *into* a RAW family — a `.tif` stays TIFF.
284 Some(Self::Tiff) => match Self::from_extension(ext) {
285 Some(raw) if raw.is_raw() => Some(raw),
286 _ => Some(Self::Tiff),
287 },
288 Some(format) => Some(format),
289 None => Self::from_extension(ext),
290 }
291 }
292}
293
294impl fmt::Display for StillFormat {
295 /// The format's media type — what a log line and an error message both want.
296 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
297 f.write_str(self.mime())
298 }
299}