capsule_core/media/decode.rs
1//! The decode seam: bytes in, orientation-applied RGBA8 out.
2//!
3//! # The pipeline, and why each step is here
4//!
5//! 1. **Identify** ([`StillFormat::detect`]) — header first, so a `.jpg` that is really a HEIC
6//! is classified as HEIC.
7//! 2. **Gate** ([`StillFormat::is_decodable`]) — refuse with a typed
8//! [`MediaError::UnsupportedFormat`] *before* touching a decoder, so a HEIC never reaches a
9//! stub that would return a less informative error.
10//! 3. **Budget** ([`MAX_DECODE_PIXELS`]) — a header-only
11//! [`probe`](Decoder::probe) refuses an oversized frame before the decoder allocates. It has
12//! to be pre-decode: `rawshift-image` decodes to interleaved RGB `u16`, so the bomb is
13//! inside the decoder, not in Capsule's copy of the result. An AVIF's header size is its
14//! `ispe` box, a claim the AV1 frame need not honour, and `rawshift-image` takes no
15//! frame-size limit for the AV1 decoder (visualcommons/rawshift#79), so an AVIF is bounded
16//! by its `ispe` before decode and by its decoded frame after it, not by its coded frame.
17//! 4. **Decode**, then **apply the EXIF orientation** to the pixels, so the frame this module
18//! returns is always upright and its dimensions are the ones a viewer shows.
19//! 5. **Normalise** to packed RGBA8, which is what [`crate::lqip`] and the downscale both take.
20//!
21//! # RAW: the same five steps through a different reader
22//!
23//! ARW and DNG (issue #589) do not go through `decode_standard_image`. They go through
24//! `rawshift-image`'s `RawFile::open(..)` and `process(..)`, which runs black level, white
25//! balance, demosaic, colour matrix, tone mapping, the file's default crop **and the EXIF
26//! orientation** itself, then tags the result display-referred sRGB. So the RAW path differs at
27//! three steps:
28//!
29//! - **Budget.** For an ARW, `RawFile::open` parses the IFDs and reads no pixels, so the probe
30//! *is* the open. The budget is checked against every frame the pipeline will allocate from
31//! the file's own claims — the sensor, the active area, the default crop and each tile — and
32//! every strip and tile byte range must lie inside the file, because the reader allocates each
33//! one at the length the file states before it reads a byte. The work is bounded as well as
34//! each allocation: a tile or strip must fit inside the sensor, and the file may list no more
35//! of them than the sensor's grid holds. A DNG's `open` instead decodes the whole raw image
36//! through gamut, which borrows each range in place, refuses one outside the file, a strip
37//! list longer than the rows, a tile list that is not the grid and a JPEG XL tile (ProRAW)
38//! whose codestream is not its tile's size, but allocates the image and each tile at their
39//! stated sizes. So before a DNG is opened, every image and tile any of its IFDs states is held
40//! to the budget, and after it the sensor, active area and crop are held as for an ARW. The
41//! eager reader decodes and keeps every other image IFD too, so their pixels are summed
42//! against the same budget, `SamplesPerPixel` is held to 4, and a lossless-JPEG chunk whose
43//! own header states more samples than its strip or tile is refused before the reader
44//! allocates for it (visualcommons/rawshift#82). Before either is opened, a no-allocation
45//! walk of the IFD chain (`tiff_bounds`, issue #644) refuses as [`MediaError::Decode`] any
46//! entry whose value needs more bytes than the file holds, and (issue #647) any IFD nested
47//! deeper than a recursive reader can safely follow. The same walk (issue #1324) holds the
48//! directories and values, the strips and tiles, and the pointers a file states to work
49//! budgets proportional to its length, and refuses a black-level pattern or a bad-pixel list
50//! stating more than a reader can hold it to. The DNG bounds apply to every file whose IFD0
51//! states `DNGVersion`, because the reader opens any such file as a DNG whatever its name.
52//! - **Orientation** is applied by `process`, so it is reported in `orientation_applied` and
53//! never applied a second time here.
54//! - **Unsupported variants defer.** Upstream decodes Sony lossless-JPEG ARW and uncompressed,
55//! lossless-JPEG or JPEG XL DNG. It decodes Deflate DNG too, but inflates each chunk with no
56//! output bound, so Capsule defers a DNG with a Deflate image until upstream bounds it
57//! (visualcommons/rawshift#82). Any other ARW compression, a camera its reader does
58//! not place, or a TIFF that is not a RAW at all is `RawError::Unsupported`, and that is mapped
59//! to
60//! [`MediaError::UnsupportedFormat`] — `DeferredNoCodec`, backfillable when upstream grows the
61//! decoder — rather than [`MediaError::Decode`], which would report a known gap as a broken file.
62//!
63//! The processing options are upstream's defaults (as-shot white balance, the file's or the
64//! camera database's colour matrix, the default tone curve) except the demosaic, which is
65//! **bilinear** rather than the AMaZE that `DemosaicMethod::Auto` picks. AMaZE holds nine
66//! full-frame `f32`/`i32` planes alongside the raw and RGB buffers, about 44 bytes a pixel, which
67//! on a 61 Mpx frame is ~2.7 GB on a phone; bilinear holds none. Every frame this module produces
68//! feeds a downscaled derivative or the LQIP, where bilinear's edge artefacts do not survive the
69//! resample.
70//!
71//! # Two lossy edges, both deliberate and both asserted
72//!
73//! - **Alpha is lost.** `rawshift-image`'s decode target is interleaved RGB `u16` with no alpha
74//! channel, and `decode_png` drops the alpha channel outright. Every frame this module
75//! returns is therefore opaque. Nothing downstream needs alpha — the LQIP is an opaque
76//! placeholder and the thumbnail is composited onto a grid — but a caller must not *assume*
77//! transparency survived, so a test pins the flattening rather than leaving it to be
78//! discovered.
79//! - **16-bit is narrowed to 8.** `(sample >> 8) as u8` is the exact inverse of the crate's own
80//! `u8_to_u16` widening (`v * 257`), so an 8-bit source round-trips bit-exactly and only a
81//! genuinely deeper source loses its low byte. That is the same narrowing every encode
82//! backend in the crate performs anyway.
83//!
84//! # The panic guard
85//!
86//! [`decode_guarded`] wraps a [`Decoder`] call in [`std::panic::catch_unwind`]. It is a free
87//! function over the trait rather than a detail inside [`RawshiftDecoder`] for one reason: a
88//! test has to be able to prove the guard holds, and it can only do that by injecting a
89//! [`Decoder`] that panics.
90
91use std::io::Cursor;
92use std::panic::{AssertUnwindSafe, catch_unwind};
93
94use rawshift_image::core::{ColorDescription, ColourPrimaries, RgbImage};
95use rawshift_image::error::{FormatError, RawError};
96use rawshift_image::formats::{
97 RawFile, StandardFormat, decode_standard_image, probe_standard_image,
98 read_standard_image_metadata,
99};
100use rawshift_image::processing::{BayerAlgorithm, DemosaicMethod, ProcessingOptions};
101use rawshift_image::transforms::orientation::apply_orientation;
102
103use super::detect::{MAX_DECODE_PIXELS, StillFormat};
104use super::error::{FormatOp, MediaError};
105use super::tiff_bounds::{IfdRefusal, IfdWalk, MAX_IFD_DEPTH, check_ifd_bounds};
106use crate::lqip::{Gamut, RgbaImage};
107
108/// The EXIF orientation value meaning "already upright".
109const ORIENTATION_NORMAL: u16 = 1;
110
111/// What a header-only probe can say about a still, normalised onto Capsule's own types.
112///
113/// This is the "metadata normalisation" half of the module: `rawshift-image` reports a format,
114/// a size, an optional bit depth and a colour space, plus (from a separate EXIF read) an
115/// orientation. None of those types may appear in Capsule's public surface — they belong to a
116/// pre-1.0 dependency — so each is mapped onto a Capsule type here, once.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct MediaMetadata {
119 /// The identified format.
120 pub format: StillFormat,
121 /// Dimensions **as stored**, i.e. before the EXIF orientation is applied. A probe reads the
122 /// codec header, which knows nothing about the orientation tag; the upright dimensions are
123 /// what [`DecodedImage`] carries.
124 pub stored_dimensions: (u32, u32),
125 /// The EXIF orientation tag (1..=8), where the format carries one and it was readable.
126 pub orientation: Option<u16>,
127 /// Bits per channel, where the header exposes it cheaply.
128 pub bit_depth: Option<u8>,
129 /// The gamut [`crate::lqip::Lqip::encode`] is told to interpret the samples in.
130 ///
131 /// **Always [`Gamut::Srgb`] in this build, and that is upstream's doing rather than a
132 /// choice made here.** `probe_standard_image` hard-codes `ColorDescription::SRGB` into every
133 /// `ImageProbe` it returns, and `decode_standard_image` likewise tags every decoded frame
134 /// sRGB without converting — so `rawshift-image` reports no source gamut for a
135 /// standard format at all, whatever the file's ICC profile says. The consequence is a
136 /// fidelity limitation, not a correctness bug: a Display P3 source gets a placeholder
137 /// interpreted as sRGB, i.e. slightly under-saturated, which is the safer direction
138 /// when one has to be picked. This module's private `gamut_of` is kept as the single
139 /// mapping point for when
140 /// the crate does start reporting it. A RAW frame is sRGB for a better reason: its colour
141 /// matrix converts camera RGB to sRGB primaries, so sRGB is what the samples really are.
142 pub gamut: Gamut,
143}
144
145impl MediaMetadata {
146 /// The dimensions a viewer shows: the stored ones, transposed when the orientation tag is
147 /// one of the four quarter-turns (5, 6, 7, 8).
148 pub const fn upright_dimensions(&self) -> (u32, u32) {
149 let (width, height) = self.stored_dimensions;
150 match self.orientation {
151 Some(5..=8) => (height, width),
152 _ => (width, height),
153 }
154 }
155}
156
157/// A decoded still: upright, opaque, packed RGBA8.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct DecodedImage {
160 /// The pixels, `width * height * 4` bytes, alpha uniformly `255`.
161 ///
162 /// [`crate::lqip::RgbaImage`] rather than a new buffer type: it is already the shape
163 /// [`crate::lqip::Lqip::encode`] and [`downscale_rgba8`](super::downscale_rgba8) take, and
164 /// it is unconditional, so no `media`-only type reaches the LQIP contract.
165 pub image: RgbaImage,
166 /// The source colour space this frame's samples are in.
167 pub gamut: Gamut,
168 /// The EXIF orientation value that was **consumed** — the transform is already applied to
169 /// `image`, so a renderer that rotates again is double-applying. `1` when the source
170 /// carried no tag.
171 pub orientation_applied: u16,
172 /// The format the pixels came out of.
173 pub format: StillFormat,
174}
175
176impl DecodedImage {
177 /// Frame width in pixels, upright.
178 pub const fn width(&self) -> u32 {
179 self.image.width
180 }
181
182 /// Frame height in pixels, upright.
183 pub const fn height(&self) -> u32 {
184 self.image.height
185 }
186}
187
188/// The still-decode seam.
189///
190/// A trait with exactly one production implementation ([`RawshiftDecoder`]), and that is the
191/// point: the failure modes worth testing — a panicking decoder, a decoder that reports
192/// dimensions its buffer does not match — cannot be produced from real bytes on demand, so they
193/// are injected.
194pub trait Decoder {
195 /// Read the format, dimensions and orientation from the header without decoding pixels.
196 ///
197 /// # Errors
198 /// [`MediaError::NotAStillImage`] when nothing recognisable is there,
199 /// [`MediaError::UnsupportedFormat`] when the format has no decoder in this build, and
200 /// [`MediaError::PixelBudgetExceeded`] when the header claims more than
201 /// [`MAX_DECODE_PIXELS`].
202 fn probe(&self, bytes: &[u8], ext: &str) -> Result<MediaMetadata, MediaError>;
203
204 /// Decode to upright, packed RGBA8. Probes first, so every [`probe`](Self::probe) error is
205 /// also a `decode` error.
206 ///
207 /// # Errors
208 /// As [`probe`](Self::probe), plus [`MediaError::Decode`] when a supported format's bytes
209 /// do not decode and [`MediaError::BufferLengthMismatch`] / [`MediaError::ZeroDimension`]
210 /// when the decoder's own output is inconsistent.
211 fn decode(&self, bytes: &[u8], ext: &str) -> Result<DecodedImage, MediaError>;
212}
213
214/// The `rawshift-image`-backed [`Decoder`] — the only production implementation.
215#[derive(Debug, Clone, Copy, Default)]
216pub struct RawshiftDecoder;
217
218impl Decoder for RawshiftDecoder {
219 #[tracing::instrument(level = "debug", skip_all, fields(bytes = bytes.len(), ext))]
220 fn probe(&self, bytes: &[u8], ext: &str) -> Result<MediaMetadata, MediaError> {
221 let format = gate(bytes, ext, FormatOp::Decode)?;
222 if format.is_raw() {
223 return open_raw(bytes, format).map(|(_, metadata)| metadata);
224 }
225 let probe = probe_standard_image(bytes).map_err(|e| MediaError::Decode {
226 format,
227 detail: format!("header probe: {e}"),
228 })?;
229 let (width, height) = (probe.size.width, probe.size.height);
230 if width == 0 || height == 0 {
231 return Err(MediaError::ZeroDimension { width, height });
232 }
233 let pixels = u64::from(width) * u64::from(height);
234 if pixels > MAX_DECODE_PIXELS {
235 tracing::warn!(
236 %format,
237 width,
238 height,
239 pixels,
240 limit = MAX_DECODE_PIXELS,
241 "media: refusing an oversized still before the decoder allocates"
242 );
243 return Err(MediaError::PixelBudgetExceeded {
244 pixels,
245 limit: MAX_DECODE_PIXELS,
246 });
247 }
248 let metadata = MediaMetadata {
249 format,
250 stored_dimensions: (width, height),
251 orientation: orientation_of(bytes, format),
252 bit_depth: probe.bit_depth,
253 gamut: gamut_of(probe.color_space),
254 };
255 tracing::debug!(
256 %format,
257 width,
258 height,
259 orientation = ?metadata.orientation,
260 bit_depth = ?metadata.bit_depth,
261 gamut = ?metadata.gamut,
262 "media: probed a still"
263 );
264 Ok(metadata)
265 }
266
267 #[tracing::instrument(level = "debug", skip_all, fields(bytes = bytes.len(), ext))]
268 fn decode(&self, bytes: &[u8], ext: &str) -> Result<DecodedImage, MediaError> {
269 let format = gate(bytes, ext, FormatOp::Decode)?;
270 if format.is_raw() {
271 return decode_raw(bytes, format);
272 }
273 let probed = self.probe(bytes, ext)?;
274 let format = probed.format;
275 let mut rgb = decode_standard_image(bytes, standard_format(format))
276 .map_err(|e| standard_error(format, e))?;
277 check_rgb_buffer(&rgb, format)?;
278 // The probe held the header's size to the budget, but a header can understate its frame
279 // (an AVIF's `ispe` is only a claim about its AV1 frame), so the decoded frame is held to
280 // it too before Capsule copies or resamples it.
281 check_frame_budget(format, rgb.width(), rgb.height(), MAX_DECODE_PIXELS)?;
282
283 let orientation = probed.orientation.unwrap_or(ORIENTATION_NORMAL);
284 if orientation != ORIENTATION_NORMAL {
285 apply_orientation(&mut rgb, orientation);
286 check_rgb_buffer(&rgb, format)?;
287 }
288
289 let image = to_rgba8(&rgb);
290 tracing::debug!(
291 %format,
292 width = image.width,
293 height = image.height,
294 orientation,
295 "media: decoded a still"
296 );
297 Ok(DecodedImage {
298 image,
299 gamut: probed.gamut,
300 orientation_applied: orientation,
301 format,
302 })
303 }
304}
305
306/// Run `decoder.decode` with the unwind boundary an import needs.
307///
308/// A pre-1.0 decoder fed untrusted bytes is exactly where a panic is plausible, and a missing
309/// thumbnail must never be able to abort an import that has already written signed, encrypted
310/// bytes. A caught unwind becomes [`MediaError::DecoderPanic`] — reported, not swallowed.
311pub fn decode_guarded(
312 decoder: &dyn Decoder,
313 bytes: &[u8],
314 ext: &str,
315) -> Result<DecodedImage, MediaError> {
316 guarded("decode", || decoder.decode(bytes, ext))
317}
318
319/// Run any fallible step of the still pipeline behind the same unwind boundary.
320///
321/// Public because its one caller, the derivative pipeline in `capsule-library`'s `lifecycle`, is
322/// in another crate; the `catch_unwind` itself stays here, the one module the stateless core
323/// sanctions it in.
324///
325/// Not just for `decode` — that is not the only third-party code the import path runs over pixels:
326/// the placeholder goes through `chromahash` (also pre-1.0) and the derivative through the
327/// encoder, and the module's promise is that *none* of them can abort an import — not that the
328/// decoder specifically cannot. `stage` names the step in the warning so a caught panic is
329/// attributable.
330///
331/// `AssertUnwindSafe` is sound for the callers here: each closure borrows shared slices and
332/// stateless values, so a caught unwind cannot leave a Capsule-owned invariant torn.
333pub fn guarded<T>(
334 stage: &'static str,
335 step: impl FnOnce() -> Result<T, MediaError>,
336) -> Result<T, MediaError> {
337 if let Ok(result) = catch_unwind(AssertUnwindSafe(step)) {
338 return result;
339 }
340 tracing::warn!(
341 stage,
342 "media: a third-party codec panicked; the original is imported without a derivative"
343 );
344 Err(MediaError::DecoderPanic)
345}
346
347/// Identify a still and refuse anything this build has no codec for, before any decoder runs.
348fn gate(bytes: &[u8], ext: &str, op: FormatOp) -> Result<StillFormat, MediaError> {
349 let Some(format) = StillFormat::detect(bytes, ext) else {
350 return Err(MediaError::NotAStillImage);
351 };
352 if !format.is_decodable() {
353 return Err(MediaError::UnsupportedFormat { format, op });
354 }
355 Ok(format)
356}
357
358/// Refuse a decoded frame of more than `limit` pixels.
359fn check_frame_budget(
360 format: StillFormat,
361 width: u32,
362 height: u32,
363 limit: u64,
364) -> Result<(), MediaError> {
365 let pixels = u64::from(width) * u64::from(height);
366 if pixels > limit {
367 tracing::warn!(
368 %format,
369 width,
370 height,
371 pixels,
372 limit,
373 "media: refusing a decoded frame larger than its header claimed and the budget allows"
374 );
375 return Err(MediaError::PixelBudgetExceeded { pixels, limit });
376 }
377 Ok(())
378}
379
380/// [`check_frame_budget`] over a decoded still, with the budget as a parameter so a test can
381/// exceed it with a small frame.
382#[cfg(test)]
383pub(super) fn check_decoded_budget(decoded: &DecodedImage, limit: u64) -> Result<(), MediaError> {
384 check_frame_budget(decoded.format, decoded.width(), decoded.height(), limit)
385}
386
387/// Map a standard-format decode error onto Capsule's, keeping a missing decoder apart from a
388/// broken file.
389///
390/// `RawError::HwDecoderUnavailable` is upstream saying this host has no decoder for the
391/// codestream inside a container it parsed: an AVIF's AV1, which `rawshift-image` decodes only
392/// through a hardware backend until it gains a software fallback
393/// (visualcommons/rawshift#78). That is a codec this host lacks, not a broken file, so it
394/// becomes the backfillable [`MediaError::UnsupportedFormat`], exactly like a build that links
395/// no AVIF decoder at all.
396///
397/// A hardware decoder that is present but refuses the codestream defers the same way: a VAAPI
398/// host decodes AV1 Profile 0 only, so a sound 4:4:4 (Profile 1) AVIF is a codec this host
399/// lacks, not a broken file. Upstream reports that refusal as an AVIF `ImageDecode` error rather
400/// than as `HwDecoderUnavailable` (visualcommons/rawshift#78), so it is recognised by the
401/// message upstream builds for it ([`is_hardware_av1_refusal`]). Everything else is a real
402/// decode failure.
403pub(super) fn standard_error(format: StillFormat, error: RawError) -> MediaError {
404 let defer = || MediaError::UnsupportedFormat {
405 format,
406 op: FormatOp::Decode,
407 };
408 match error {
409 RawError::HwDecoderUnavailable { codec, reason } => {
410 tracing::warn!(
411 %format,
412 codec,
413 %reason,
414 "media: this host has no decoder for the codestream; deferring"
415 );
416 defer()
417 }
418 RawError::Format(FormatError::ImageDecode {
419 format: "AVIF",
420 ref message,
421 }) if format == StillFormat::Avif && is_hardware_av1_refusal(message) => {
422 tracing::warn!(
423 %format,
424 %message,
425 "media: this host's hardware AV1 decoder refused the codestream; deferring"
426 );
427 defer()
428 }
429 other => MediaError::Decode {
430 format,
431 detail: other.to_string(),
432 },
433 }
434}
435
436/// Whether an AVIF decode message is the hardware AV1 decoder declining the codestream, rather
437/// than the container or the decoded frame being broken: `rawshift-image`'s AVIF reader reports
438/// a backend that accepted the job and failed as `hardware AV1 decode failed: …`
439/// (`HwDecodeError::Decode`), and 4:2:2 or 4:4:4 content its 4:2:0 surface cannot carry as
440/// `… outside the hardware decode scope …`.
441///
442/// A corrupt AV1 payload the backend fails on is deferred too, since nothing tells it apart
443/// from a refused profile; a deferral is backfilled from the stored original once upstream
444/// decodes AV1 in software (visualcommons/rawshift#78), which then reports it on its own
445/// terms, whereas a sound file marked as a decode failure would never be retried.
446fn is_hardware_av1_refusal(message: &str) -> bool {
447 message.contains("hardware AV1 decode failed")
448 || message.contains("outside the hardware decode scope")
449}
450
451/// A RAW file opened over the caller's bytes.
452type OpenRaw<'a> = RawFile<Cursor<&'a [u8]>>;
453
454/// The options every RAW decode runs with: upstream's defaults, demosaicked bilinearly. The
455/// module docs say why bilinear rather than `DemosaicMethod::Auto`'s AMaZE.
456fn raw_processing_options() -> ProcessingOptions {
457 ProcessingOptions::new().demosaic(DemosaicMethod::Bayer(BayerAlgorithm::Bilinear))
458}
459
460/// What a RAW file's own metadata claims about the buffers decoding it will allocate.
461///
462/// Gathered once per family, from the crate's per-family metadata rather than its unified
463/// `ImageMetadata` (which carries no sensor size and no strip or tile layout), so the budget,
464/// the byte-range check and the probe all read the same numbers.
465#[derive(Debug)]
466struct RawLayout {
467 /// The full sensor frame `decode_raw` allocates.
468 sensor: (u32, u32),
469 /// The active area (`x`, `y`, `w`, `h`) the demosaic allocates and indexes the sensor by.
470 active: (u32, u32, u32, u32),
471 /// The default crop (`x`, `y`, `w`, `h`), relative to the active area, that `process`
472 /// applies when it fits.
473 crop: Option<(u32, u32, u32, u32)>,
474 /// The frame each range decodes into, as the file declares it: the tile size, or a strip's
475 /// sensor width by its rows per strip (the whole sensor where it states none). The reader
476 /// places range `i` on this grid, so the grid also bounds how many ranges there can be.
477 unit_size: (u32, u32),
478 /// `"strip"` or `"tile"`: what [`ranges`](Self::ranges) holds, for the error detail.
479 unit: &'static str,
480 /// Every strip or tile as `(offset, length)`, each of which the reader allocates at the
481 /// stated length before it reads. Empty for a DNG, whose reader no longer reports its ranges
482 /// and checks them itself without allocating them (see [`raw_layout`]).
483 ranges: Vec<(u64, u64)>,
484 /// Whether the reader checks the ranges itself rather than reporting them: true for the DNG
485 /// reader, whichever extension the file came with.
486 reader_checks_ranges: bool,
487 bit_depth: u8,
488 orientation: Option<u16>,
489}
490
491impl RawLayout {
492 /// The frame `process` returns before orienting it: the active area, or the default crop
493 /// where it fits inside it. This is what [`MediaMetadata::stored_dimensions`] reports for a
494 /// RAW, because the sensor's masked border is never shown.
495 fn rendered(&self) -> (u32, u32) {
496 let (_, _, width, height) = self.active;
497 match self.crop {
498 Some((x, y, w, h))
499 if u64::from(x) + u64::from(w) <= u64::from(width)
500 && u64::from(y) + u64::from(h) <= u64::from(height) =>
501 {
502 (w, h)
503 }
504 _ => (width, height),
505 }
506 }
507}
508
509/// Read the layout out of whichever family `RawFile::open` identified.
510///
511/// The match is exhaustive over the families this build enables (`arw-decode`, `dng-decode`),
512/// with no wildcard, on purpose: enabling another family is then a compile error here until its
513/// layout — and so its budget — is written.
514///
515/// `max_tile` is the IFD walk's [`IfdWalk::max_tile`](super::tiff_bounds::IfdWalk::max_tile),
516/// which stands in for the DNG tile size the reader no longer reports.
517fn raw_layout(
518 raw: &OpenRaw<'_>,
519 format: StillFormat,
520 max_tile: (u64, u64),
521) -> Result<RawLayout, MediaError> {
522 let missing = || MediaError::Decode {
523 format,
524 detail: "RAW reader returned no metadata".to_owned(),
525 };
526 let pairs = |offsets: &[u64], lengths: &[u64]| -> Vec<(u64, u64)> {
527 offsets
528 .iter()
529 .copied()
530 .zip(lengths.iter().copied())
531 .collect()
532 };
533 Ok(match raw {
534 RawFile::Arw(arw) => {
535 let m = arw.metadata().ok_or_else(missing)?;
536 let tiled = !m.tile_offsets.is_empty() && m.tile_width > 0 && m.tile_height > 0;
537 RawLayout {
538 sensor: (m.sensor_size.width, m.sensor_size.height),
539 active: (
540 m.active_area.origin.x,
541 m.active_area.origin.y,
542 m.active_area.size.width,
543 m.active_area.size.height,
544 ),
545 // ARW's crop tags *are* its active area; `process` applies no second crop.
546 crop: None,
547 // An untiled ARW is one LJPEG stream covering the whole sensor.
548 unit_size: if tiled {
549 (m.tile_width, m.tile_height)
550 } else {
551 (m.sensor_size.width, m.sensor_size.height)
552 },
553 unit: if tiled { "tile" } else { "strip" },
554 ranges: if tiled {
555 pairs(&m.tile_offsets, &m.tile_byte_counts)
556 } else {
557 vec![(m.raw_data_offset, m.raw_data_size)]
558 },
559 reader_checks_ranges: false,
560 bit_depth: m.bit_depth,
561 orientation: m.orientation,
562 }
563 }
564 RawFile::Dng(dng) => {
565 let m = dng.metadata().ok_or_else(missing)?;
566 // `DngMetadata` no longer reports the strip or tile layout: gamut's DNG reader
567 // resolves it at decode, refusing a range outside the file, a strip list longer than
568 // the rows and a tile list that does not match the grid, and borrowing each range
569 // rather than allocating it. What it does not bound is a tile's own size, which it
570 // decodes into before placing it, so the tile size is taken from the IFD walk's
571 // largest stated `TileWidth` and `TileLength` and held to the sensor below. A
572 // stripped DNG's strips are at most the sensor's width by its height.
573 let (tile_w, tile_h) = max_tile;
574 let tiled = tile_w > 0 || tile_h > 0;
575 let clamp = |v: u64| u32::try_from(v).unwrap_or(u32::MAX);
576 let (sensor_w, sensor_h) = (m.sensor_size.width, m.sensor_size.height);
577 RawLayout {
578 sensor: (sensor_w, sensor_h),
579 active: m.active_area.map_or((0, 0, sensor_w, sensor_h), |area| {
580 (
581 area.origin.x,
582 area.origin.y,
583 area.size.width,
584 area.size.height,
585 )
586 }),
587 crop: m
588 .default_crop_origin
589 .zip(m.default_crop_size)
590 .map(|((x, y), (w, h))| (x, y, w, h)),
591 unit_size: if tiled {
592 (clamp(tile_w), clamp(tile_h))
593 } else {
594 (sensor_w, sensor_h)
595 },
596 unit: if tiled { "tile" } else { "strip" },
597 // Upstream checks the ranges themselves; see above.
598 ranges: Vec::new(),
599 reader_checks_ranges: true,
600 bit_depth: m.bit_depth,
601 orientation: m.orientation,
602 }
603 }
604 })
605}
606
607/// Hold a DNG's stated frames to the budget before `RawFile::open`, which for a DNG decodes the
608/// whole raw image (gamut's reader is eager) and so allocates for the image and each tile at
609/// the sizes the file states before Capsule can read a layout back.
610///
611/// The bound is taken from the IFD walk rather than from the reader: the largest image any IFD
612/// states, and the largest tile width and length any IFD states. Every IFD's image is held, the
613/// raw one among them, because which IFD is the raw image is the reader's choice. ARW's reader
614/// reads no pixels at open, so its layout is checked after it, by [`check_raw_layout`].
615///
616/// The reader also decodes and keeps every other IFD that locates strips or tiles, at
617/// `SamplesPerPixel` `u16` samples a pixel, so those pixels together are held to the same budget
618/// and `SamplesPerPixel` to [`MAX_DNG_SAMPLES_PER_PIXEL`]: what the reader keeps is then at most
619/// the budget at four samples a pixel. Two compressions allocate past any stated size before the
620/// reader checks it (visualcommons/rawshift#82): a Deflate chunk inflates with no output bound,
621/// so a DNG holding one defers as [`MediaError::UnsupportedFormat`], as it did before rawshift
622/// decoded Deflate; and a lossless-JPEG chunk is allocated at its own SOF3 header's size, so a
623/// header stating more samples than its strip or tile holds is refused. A real file never states
624/// one, and the reader would refuse it after decoding.
625///
626/// Applied to every file the reader opens as a DNG, which is any whose IFD0 states `DNGVersion`
627/// ([`IfdWalk::dng`]) whatever its extension, as well as to every `.dng`: a DNG named `.arw` is
628/// opened by the eager reader all the same.
629fn check_eager_raw_frames(
630 format: StillFormat,
631 walk: &IfdWalk,
632 limit: u64,
633) -> Result<(), MediaError> {
634 if format != StillFormat::Dng && !walk.dng {
635 return Ok(());
636 }
637 let clamp = |v: u64| u32::try_from(v).unwrap_or(u32::MAX);
638 let (width, height) = walk.max_image;
639 if (width, height) != (0, 0) {
640 check_raw_frame(format, "image", (clamp(width), clamp(height)), limit)?;
641 }
642 let (tile_w, tile_h) = walk.max_tile;
643 if tile_w > 0 || tile_h > 0 {
644 check_raw_frame(format, "tile", (clamp(tile_w), clamp(tile_h)), limit)?;
645 }
646 if walk.max_samples_per_pixel > MAX_DNG_SAMPLES_PER_PIXEL {
647 tracing::warn!(
648 %format,
649 samples_per_pixel = walk.max_samples_per_pixel,
650 max = MAX_DNG_SAMPLES_PER_PIXEL,
651 "media: refusing a DNG image stating more samples a pixel than any DNG image holds"
652 );
653 return Err(MediaError::Decode {
654 format,
655 detail: format!(
656 "RAW image states {} samples per pixel, past the {MAX_DNG_SAMPLES_PER_PIXEL} a \
657 DNG image holds",
658 walk.max_samples_per_pixel
659 ),
660 });
661 }
662 if walk.decode_pixels > limit {
663 tracing::warn!(
664 %format,
665 pixels = walk.decode_pixels,
666 limit,
667 "media: refusing a DNG whose images together exceed the decode budget before the \
668 eager reader allocates them"
669 );
670 return Err(MediaError::PixelBudgetExceeded {
671 pixels: walk.decode_pixels,
672 limit,
673 });
674 }
675 if walk.deflate {
676 tracing::warn!(
677 %format,
678 "media: deferring a Deflate DNG, whose chunks the reader inflates without an output \
679 bound (visualcommons/rawshift#82)"
680 );
681 return Err(MediaError::UnsupportedFormat {
682 format,
683 op: FormatOp::Decode,
684 });
685 }
686 if let Some(overrun) = walk.ljpeg_overrun {
687 tracing::warn!(
688 %format,
689 ifd_offset = overrun.ifd_offset,
690 chunk = overrun.chunk,
691 samples = overrun.samples,
692 capacity = overrun.capacity,
693 "media: refusing a DNG whose lossless-JPEG chunk header states more samples than its \
694 strip or tile holds"
695 );
696 return Err(MediaError::Decode {
697 format,
698 detail: format!("RAW {overrun}"),
699 });
700 }
701 Ok(())
702}
703
704/// The most `SamplesPerPixel` a DNG image IFD may state: a CFA raw holds 1, a linear raw or an
705/// RGB preview 3, and a lossless-JPEG stream carries at most 4 components.
706const MAX_DNG_SAMPLES_PER_PIXEL: u64 = 4;
707
708/// Refuse a frame the RAW pipeline would allocate for that is empty or over `limit` pixels.
709fn check_raw_frame(
710 format: StillFormat,
711 frame: &'static str,
712 (width, height): (u32, u32),
713 limit: u64,
714) -> Result<(), MediaError> {
715 if width == 0 || height == 0 {
716 return Err(MediaError::ZeroDimension { width, height });
717 }
718 let pixels = u64::from(width) * u64::from(height);
719 if pixels > limit {
720 tracing::warn!(
721 %format,
722 frame,
723 width,
724 height,
725 pixels,
726 limit,
727 "media: refusing an oversized RAW frame before the decoder allocates"
728 );
729 return Err(MediaError::PixelBudgetExceeded { pixels, limit });
730 }
731 Ok(())
732}
733
734/// Hold a RAW layout to the decode budget and to the bytes actually present.
735///
736/// Every check here is against a claim the file makes and the reader would otherwise trust:
737/// it allocates the sensor, the active area, each tile and each strip or tile read buffer at
738/// the size the file states, and an allocation failure aborts rather than unwinds, so
739/// [`decode_guarded`] cannot catch it. Indexing faults (an active area outside the sensor) do
740/// unwind, but are refused here too so they report as a decode failure rather than a panic.
741///
742/// The number of decodes is held too, not only the size of each: every strip or tile must fit
743/// the sensor, and there may be no more of them than the sensor's grid of that size holds.
744fn check_raw_layout(
745 bytes: &[u8],
746 format: StillFormat,
747 layout: &RawLayout,
748 limit: u64,
749) -> Result<(), MediaError> {
750 let (x, y, width, height) = layout.active;
751 check_raw_frame(format, "sensor", layout.sensor, limit)?;
752 check_raw_frame(format, "active area", (width, height), limit)?;
753 if let Some((_, _, crop_w, crop_h)) = layout.crop {
754 check_raw_frame(format, "default crop", (crop_w, crop_h), limit)?;
755 }
756 check_raw_frame(format, layout.unit, layout.unit_size, limit)?;
757 let (sensor_w, sensor_h) = layout.sensor;
758 let unit = layout.unit;
759 let (unit_w, unit_h) = layout.unit_size;
760 if unit_w > sensor_w || unit_h > sensor_h {
761 return Err(MediaError::Decode {
762 format,
763 detail: format!(
764 "{unit} size {unit_w}x{unit_h} exceeds the {sensor_w}x{sensor_h} sensor"
765 ),
766 });
767 }
768 // The reader places range `i` at column `i % across`, row `i / across`; anything past the
769 // grid is a range it would decode in full and then place nowhere (or underflow on).
770 let grid = u64::from(sensor_w.div_ceil(unit_w)) * u64::from(sensor_h.div_ceil(unit_h));
771 let count = layout.ranges.len() as u64;
772 if count > grid {
773 return Err(MediaError::Decode {
774 format,
775 detail: format!(
776 "{count} {unit}s listed, but a {sensor_w}x{sensor_h} sensor holds at most \
777 {grid} {unit}s of {unit_w}x{unit_h}"
778 ),
779 });
780 }
781 if u64::from(x) + u64::from(width) > u64::from(sensor_w)
782 || u64::from(y) + u64::from(height) > u64::from(sensor_h)
783 {
784 return Err(MediaError::Decode {
785 format,
786 detail: format!(
787 "active area {width}x{height} at ({x}, {y}) lies outside the \
788 {sensor_w}x{sensor_h} sensor"
789 ),
790 });
791 }
792 // A DNG's ranges are its reader's to check (see `raw_layout`), so only the families that
793 // report them can be refused for listing none. Which reader that was is the reader's choice,
794 // not the extension's: a DNG named `.arw` is read as a DNG.
795 if layout.ranges.is_empty() && !layout.reader_checks_ranges {
796 return Err(MediaError::Decode {
797 format,
798 detail: "RAW file locates no strip or tile data".to_owned(),
799 });
800 }
801 let file_len = bytes.len() as u64;
802 // A JPEG XL tile (ProRAW) is a DNG's, whose ranges its reader checks: it refuses a
803 // codestream whose header is not its tile's size before decoding it.
804 for (index, &(offset, length)) in layout.ranges.iter().enumerate() {
805 if offset.checked_add(length).is_none_or(|end| end > file_len) {
806 return Err(MediaError::Decode {
807 format,
808 detail: format!(
809 "{unit} {index} ({length} bytes at {offset}) runs past the {file_len}-byte file"
810 ),
811 });
812 }
813 }
814 Ok(())
815}
816
817/// Map a RAW reader error onto Capsule's, keeping a known gap apart from a broken file.
818///
819/// `RawError::Unsupported` is upstream saying it has no decoder for this variant — an
820/// unimplemented compression, a camera it cannot place, a TIFF that is no RAW at all — so it
821/// becomes the backfillable [`MediaError::UnsupportedFormat`]. Upstream also uses it for a few
822/// truncated-strip cases; those then defer rather than fail, and a backfill retries them, which
823/// costs a decode and nothing else. Everything else is a real decode failure.
824fn raw_error(format: StillFormat, stage: &'static str, error: RawError) -> MediaError {
825 match error {
826 RawError::Unsupported(reason) => {
827 tracing::warn!(
828 %format,
829 stage,
830 %reason,
831 "media: rawshift-image has no decoder for this RAW variant; deferring"
832 );
833 MediaError::UnsupportedFormat {
834 format,
835 op: FormatOp::Decode,
836 }
837 }
838 other => MediaError::Decode {
839 format,
840 detail: format!("RAW {stage}: {other}"),
841 },
842 }
843}
844
845/// Probe a RAW still against an arbitrary pixel budget.
846///
847/// `pub(super)` so the tests can drive the budget with a limit a small fixture can exceed, the
848/// way they drive `check_avif_frames`; production always goes through [`open_raw`] at
849/// [`MAX_DECODE_PIXELS`].
850#[cfg(test)]
851pub(super) fn probe_raw(
852 bytes: &[u8],
853 format: StillFormat,
854 limit: u64,
855) -> Result<MediaMetadata, MediaError> {
856 open_raw_within(bytes, format, limit).map(|(_, metadata)| metadata)
857}
858
859/// Open a RAW still and probe it: parse the IFDs, read the layout, and hold it to the budget.
860/// Reads no pixels. The opened file is returned so [`decode_raw`] does not parse it twice.
861fn open_raw(bytes: &[u8], format: StillFormat) -> Result<(OpenRaw<'_>, MediaMetadata), MediaError> {
862 open_raw_within(bytes, format, MAX_DECODE_PIXELS)
863}
864
865/// [`open_raw`] with the budget as a parameter.
866fn open_raw_within(
867 bytes: &[u8],
868 format: StillFormat,
869 limit: u64,
870) -> Result<(OpenRaw<'_>, MediaMetadata), MediaError> {
871 // Before `open`, because `open` allocates each IFD entry's value at the count the entry
872 // claims, and recurses into nested IFDs with no depth limit; see `tiff_bounds`.
873 let walk = check_ifd_bounds(bytes).map_err(|refusal| {
874 match &refusal {
875 IfdRefusal::Oversized(oversized) => tracing::warn!(
876 %format,
877 ifd_offset = oversized.ifd_offset,
878 tag = oversized.tag,
879 data_type = oversized.data_type,
880 count = oversized.count,
881 file_len = oversized.file_len,
882 "media: refused a RAW still whose IFD entry claims more than the file holds"
883 ),
884 IfdRefusal::TooDeep(deep) => tracing::warn!(
885 %format,
886 ifd_offset = deep.ifd_offset,
887 depth = deep.depth,
888 max_depth = MAX_IFD_DEPTH,
889 "media: refused a RAW still whose IFDs nest past the depth bound"
890 ),
891 IfdRefusal::ScanBudget(scan) => tracing::warn!(
892 %format,
893 ifd_offset = scan.ifd_offset,
894 chunk = scan.chunk,
895 budget = scan.budget,
896 "media: refused a RAW still whose lossless-JPEG chunks exhaust the header scan's \
897 budget"
898 ),
899 IfdRefusal::Exhausted(exhausted) => tracing::warn!(
900 %format,
901 budget = ?exhausted.budget,
902 at = exhausted.at,
903 limit = exhausted.limit,
904 "media: refused a RAW still whose directories, image data or pointers exhaust \
905 the IFD walk's work budget"
906 ),
907 IfdRefusal::Unbounded(unbounded) => tracing::warn!(
908 %format,
909 ifd_offset = unbounded.ifd_offset,
910 tag = unbounded.tag,
911 stated = unbounded.stated,
912 limit = unbounded.limit,
913 "media: refused a RAW still stating a count its reader would allocate from \
914 without bound"
915 ),
916 }
917 MediaError::Decode {
918 format,
919 detail: format!("RAW IFD bounds: {refusal}"),
920 }
921 })?;
922 tracing::trace!(
923 %format,
924 ifds = walk.ifds,
925 entries = walk.entries,
926 depth = walk.depth,
927 "media: RAW IFD value counts are within the file and its IFDs within the depth bound"
928 );
929 check_eager_raw_frames(format, &walk, limit)?;
930 let raw = RawFile::open(Cursor::new(bytes)).map_err(|e| raw_error(format, "open", e))?;
931 let layout = raw_layout(&raw, format, walk.max_tile)?;
932 check_raw_layout(bytes, format, &layout, limit)?;
933 let metadata = MediaMetadata {
934 format,
935 stored_dimensions: layout.rendered(),
936 // The same filter as the standard path: `process` no-ops an out-of-range tag, so
937 // reporting it would claim a transform that never happened.
938 orientation: layout.orientation.filter(|o| (1..=8).contains(o)),
939 bit_depth: Some(layout.bit_depth),
940 gamut: Gamut::Srgb,
941 };
942 tracing::debug!(
943 %format,
944 sensor = ?layout.sensor,
945 stored = ?metadata.stored_dimensions,
946 unit = layout.unit,
947 units = layout.ranges.len(),
948 orientation = ?metadata.orientation,
949 bit_depth = layout.bit_depth,
950 "media: probed a RAW still"
951 );
952 Ok((raw, metadata))
953}
954
955/// Decode a RAW still to upright, packed RGBA8 through the crate's full processing pipeline.
956fn decode_raw(bytes: &[u8], format: StillFormat) -> Result<DecodedImage, MediaError> {
957 let (mut raw, probed) = open_raw(bytes, format)?;
958 let rgb = raw
959 .process(&raw_processing_options())
960 .map_err(|e| raw_error(format, "process", e))?;
961 check_rgb_buffer(&rgb, format)?;
962 // `process` has already applied the orientation; this only reports it.
963 let orientation = probed.orientation.unwrap_or(ORIENTATION_NORMAL);
964 let image = to_rgba8(&rgb);
965 tracing::debug!(
966 %format,
967 width = image.width,
968 height = image.height,
969 orientation,
970 "media: decoded a RAW still"
971 );
972 Ok(DecodedImage {
973 image,
974 gamut: probed.gamut,
975 orientation_applied: orientation,
976 format,
977 })
978}
979
980/// A RAW file's embedded, camera-rendered JPEG, extracted without developing the RAW.
981///
982/// SSoT: [Thumbnails — Embedded Previews](https://docs/design/thumbnails/#embedded-previews).
983/// Local only: it is read from an original this device holds and is never uploaded, signed or
984/// listed as a tier. Its dimensions are what the render ladder places it by.
985#[derive(Clone, PartialEq, Eq)]
986pub struct EmbeddedPreview {
987 /// The JPEG exactly as the RAW file carries it.
988 pub jpeg: Vec<u8>,
989 /// Width in pixels **upright**, i.e. after [`orientation`](Self::orientation) is applied.
990 pub width: u32,
991 /// Height in pixels upright.
992 pub height: u32,
993 /// The EXIF orientation (1..=8) a renderer applies to `jpeg`'s stored pixels: the JPEG's own
994 /// tag where it carries one, else the RAW's, since a camera writes the orientation into the
995 /// RAW's IFD0 and usually leaves the preview unrotated and untagged. `1` when neither does.
996 /// [`decode_embedded_preview`] applies it; a platform decoder handed `jpeg` must apply it
997 /// itself, and must not apply the JPEG's own tag a second time.
998 pub orientation: u16,
999}
1000
1001impl std::fmt::Debug for EmbeddedPreview {
1002 // The JPEG never reaches the log.
1003 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1004 f.debug_struct("EmbeddedPreview")
1005 .field("bytes", &self.jpeg.len())
1006 .field("width", &self.width)
1007 .field("height", &self.height)
1008 .field("orientation", &self.orientation)
1009 .finish()
1010 }
1011}
1012
1013/// Extract the embedded preview of a RAW still, behind the pixel budget and the unwind guard.
1014///
1015/// `Ok(None)` when the bytes are a still that is not RAW, or a RAW that carries no embedded
1016/// JPEG. Reads no sensor data, so it works for a RAW variant whose pixels this build cannot
1017/// decode, provided the family is one it decodes.
1018///
1019/// The bounds are the ones every input gets: the IFD walk before `RawFile::open`, and before the
1020/// thumbnail read, the walk's largest stated JPEG length held to the file's own length (the
1021/// reader allocates it before it reads); then the JPEG's header is probed and its frame held to
1022/// [`MAX_DECODE_PIXELS`], so a renderer that decodes it allocates no more than any other still.
1023///
1024/// # Errors
1025///
1026/// [`MediaError::NotAStillImage`] and [`MediaError::UnsupportedFormat`] as [`Decoder::probe`],
1027/// [`MediaError::PixelBudgetExceeded`] for a preview frame over budget, [`MediaError::Decode`]
1028/// for a RAW or a preview that does not read, and [`MediaError::DecoderPanic`] when the reader
1029/// panics. Every one leaves the rung to the next source.
1030#[tracing::instrument(level = "debug", skip_all, fields(bytes = bytes.len(), ext))]
1031pub fn extract_embedded_preview(
1032 bytes: &[u8],
1033 ext: &str,
1034) -> Result<Option<EmbeddedPreview>, MediaError> {
1035 let format = gate(bytes, ext, FormatOp::Decode)?;
1036 if !format.is_raw() {
1037 return Ok(None);
1038 }
1039 guarded("embedded preview", || {
1040 embedded_preview_within(bytes, format, MAX_DECODE_PIXELS)
1041 })
1042}
1043
1044/// [`extract_embedded_preview`] for a RAW `format`, with the budget as a parameter so a test can
1045/// exceed it with a small fixture.
1046pub(super) fn embedded_preview_within(
1047 bytes: &[u8],
1048 format: StillFormat,
1049 limit: u64,
1050) -> Result<Option<EmbeddedPreview>, MediaError> {
1051 let walk = check_ifd_bounds(bytes).map_err(|refusal| MediaError::Decode {
1052 format,
1053 detail: format!("RAW IFD bounds: {refusal}"),
1054 })?;
1055 let file_len = bytes.len() as u64;
1056 if walk.max_jpeg_length > file_len {
1057 tracing::warn!(
1058 %format,
1059 stated = walk.max_jpeg_length,
1060 file_len,
1061 "media: refused an embedded preview longer than its file"
1062 );
1063 return Err(MediaError::Decode {
1064 format,
1065 detail: format!(
1066 "embedded preview claims {} bytes, more than the {file_len}-byte file holds",
1067 walk.max_jpeg_length
1068 ),
1069 });
1070 }
1071 // A DNG's open decodes its raw image, so the preview extraction pays the same pre-open bound.
1072 check_eager_raw_frames(format, &walk, limit)?;
1073 let mut raw = RawFile::open(Cursor::new(bytes)).map_err(|e| raw_error(format, "open", e))?;
1074 let raw_orientation = raw_layout(&raw, format, walk.max_tile)
1075 .ok()
1076 .and_then(|layout| layout.orientation)
1077 .filter(|o| (1..=8).contains(o));
1078 let Some(jpeg) = raw
1079 .thumbnail()
1080 .map_err(|e| raw_error(format, "embedded preview", e))?
1081 else {
1082 tracing::debug!(%format, "media: the RAW carries no embedded preview");
1083 return Ok(None);
1084 };
1085 let not_jpeg = || MediaError::Decode {
1086 format,
1087 detail: "embedded preview is not a JPEG".to_owned(),
1088 };
1089 if StillFormat::from_bytes(&jpeg) != Some(StillFormat::Jpeg) {
1090 return Err(not_jpeg());
1091 }
1092 let probe = probe_standard_image(&jpeg).map_err(|e| MediaError::Decode {
1093 format,
1094 detail: format!("embedded preview header: {e}"),
1095 })?;
1096 let stored = (probe.size.width, probe.size.height);
1097 check_raw_frame(format, "embedded preview", stored, limit)?;
1098 let orientation = orientation_of(&jpeg, StillFormat::Jpeg)
1099 .or(raw_orientation)
1100 .unwrap_or(ORIENTATION_NORMAL);
1101 let (width, height) = match orientation {
1102 5..=8 => (stored.1, stored.0),
1103 _ => stored,
1104 };
1105 tracing::debug!(
1106 %format,
1107 bytes = jpeg.len(),
1108 width,
1109 height,
1110 orientation,
1111 "media: extracted an embedded preview"
1112 );
1113 Ok(Some(EmbeddedPreview {
1114 jpeg,
1115 width,
1116 height,
1117 orientation,
1118 }))
1119}
1120
1121/// Decode an [`EmbeddedPreview`] to upright, packed RGBA8, behind the unwind guard.
1122///
1123/// Its own orientation is the one applied — the RAW's where the JPEG carries none — never the
1124/// JPEG's tag on top of it.
1125///
1126/// # Errors
1127///
1128/// As [`Decoder::decode`] for a JPEG.
1129#[tracing::instrument(level = "debug", skip_all, fields(bytes = preview.jpeg.len()))]
1130pub fn decode_embedded_preview(preview: &EmbeddedPreview) -> Result<DecodedImage, MediaError> {
1131 guarded("embedded preview decode", || {
1132 let format = StillFormat::Jpeg;
1133 let probed = RawshiftDecoder.probe(&preview.jpeg, "jpg")?;
1134 if probed.format != format {
1135 return Err(MediaError::Decode {
1136 format: probed.format,
1137 detail: "embedded preview is not a JPEG".to_owned(),
1138 });
1139 }
1140 let mut rgb = decode_standard_image(&preview.jpeg, StandardFormat::Jpeg).map_err(|e| {
1141 MediaError::Decode {
1142 format,
1143 detail: e.to_string(),
1144 }
1145 })?;
1146 check_rgb_buffer(&rgb, format)?;
1147 if preview.orientation != ORIENTATION_NORMAL {
1148 apply_orientation(&mut rgb, preview.orientation);
1149 check_rgb_buffer(&rgb, format)?;
1150 }
1151 Ok(DecodedImage {
1152 image: to_rgba8(&rgb),
1153 gamut: probed.gamut,
1154 orientation_applied: preview.orientation,
1155 format,
1156 })
1157 })
1158}
1159
1160/// Map Capsule's format onto the crate's standard-image formats.
1161///
1162/// Only the decodable set reaches here through [`gate`], which refuses the rest first, and the
1163/// decodable RAW families are routed to [`decode_raw`] before it — of the grouped arms below,
1164/// `Tiff` is the sole reachable one. The unreachable variants are still mapped to the container
1165/// the crate would actually see (a TIFF-based RAW *is* a TIFF to it, and a CR3 is an ISO-BMFF
1166/// file it can only reach through its HEIC arm) rather than panicking, so a future routing or
1167/// `is_decodable` change that forgets this table degrades to a decode error instead of aborting
1168/// an import.
1169fn standard_format(format: StillFormat) -> StandardFormat {
1170 match format {
1171 StillFormat::Jpeg => StandardFormat::Jpeg,
1172 StillFormat::Png => StandardFormat::Png,
1173 StillFormat::WebP => StandardFormat::WebP,
1174 StillFormat::Jxl => StandardFormat::Jxl,
1175 StillFormat::Gif => StandardFormat::Gif,
1176 StillFormat::Ppm => StandardFormat::Ppm,
1177 StillFormat::Avif => StandardFormat::Avif,
1178 // `Tiff` is reachable and is the reason this arm exists; the RAW families ride along
1179 // because a TIFF-based RAW is a TIFF to the crate.
1180 StillFormat::Tiff
1181 | StillFormat::Arw
1182 | StillFormat::Cr2
1183 | StillFormat::Crw
1184 | StillFormat::Dng
1185 | StillFormat::Nef
1186 | StillFormat::Raf => StandardFormat::Tiff,
1187 StillFormat::Heic | StillFormat::Cr3 => StandardFormat::Heic,
1188 }
1189}
1190
1191/// The EXIF orientation tag, where the format carries one. Only JPEG, TIFF, WebP, PNG and AVIF
1192/// have an EXIF block the crate's parser reads; the others return `None` rather than guessing.
1193fn orientation_of(bytes: &[u8], format: StillFormat) -> Option<u16> {
1194 let metadata = read_standard_image_metadata(bytes, standard_format(format));
1195 // Only the eight defined values are honoured. `apply_orientation` warns and no-ops on
1196 // anything else, which would leave `orientation_applied` claiming a transform that never
1197 // happened — so an out-of-range tag is dropped here instead.
1198 metadata.image.orientation.filter(|o| (1..=8).contains(o))
1199}
1200
1201/// Map the crate's colour description onto the gamut the LQIP encoder takes.
1202///
1203/// Only the CICP primaries matter: the transfer function names no gamut. BT.709 (sRGB and linear
1204/// sRGB alike) and unspecified primaries both become [`Gamut::Srgb`], since sRGB primaries are
1205/// the only safe assumption for an untagged source (over-saturating is worse than
1206/// under-saturating). Adobe RGB and ProPhoto RGB have no CICP code point, so upstream tags them
1207/// unspecified and leaves their truth in the ICC profile; they map to sRGB here too.
1208///
1209/// **The wide-gamut arms are unreachable today**, because `probe_standard_image` hard-codes
1210/// `ColorDescription::SRGB` for every format (see [`MediaMetadata::gamut`]). They are here as the
1211/// one place that has to change when the crate starts reporting a source gamut, rather than as a
1212/// claim that it already does.
1213fn gamut_of(color: ColorDescription) -> Gamut {
1214 match color.primaries {
1215 ColourPrimaries::DisplayP3 => Gamut::DisplayP3,
1216 ColourPrimaries::Bt2020 => Gamut::Bt2020,
1217 // BT.709, unspecified, and — because `ColourPrimaries` is `#[non_exhaustive]` — any code
1218 // point a future release adds. One wildcard, since the answer is the same: sRGB is the
1219 // conservative default.
1220 _ => Gamut::Srgb,
1221 }
1222}
1223
1224/// Refuse a decoder result whose buffer does not match the dimensions it reports.
1225///
1226/// `RgbImage` now validates its length against its dimensions at every construction (it wraps
1227/// gamut's `ImageBuf`), so this cannot fire against the pinned revision. It stays because the
1228/// very next thing Capsule does is index that buffer by those dimensions, and a pre-1.0
1229/// dependency's invariant is cheaper to recheck than to trust across every bump of the pin.
1230fn check_rgb_buffer(rgb: &RgbImage, format: StillFormat) -> Result<(), MediaError> {
1231 let (width, height) = (rgb.width(), rgb.height());
1232 if width == 0 || height == 0 {
1233 return Err(MediaError::ZeroDimension { width, height });
1234 }
1235 let expected = u128::from(width) * u128::from(height) * 3;
1236 let actual = rgb.data().len() as u128;
1237 if expected != actual {
1238 return Err(MediaError::BufferLengthMismatch {
1239 format,
1240 width,
1241 height,
1242 expected,
1243 actual,
1244 });
1245 }
1246 Ok(())
1247}
1248
1249/// Narrow interleaved RGB `u16` to packed, opaque RGBA8.
1250///
1251/// `sample >> 8` is the exact inverse of the crate's `v * 257` widening, so an 8-bit source is
1252/// reproduced bit-for-bit.
1253fn to_rgba8(rgb: &RgbImage) -> RgbaImage {
1254 let mut rgba = Vec::with_capacity(rgb.data().len() / 3 * 4);
1255 for px in rgb.data().chunks_exact(3) {
1256 rgba.push((px[0] >> 8) as u8);
1257 rgba.push((px[1] >> 8) as u8);
1258 rgba.push((px[2] >> 8) as u8);
1259 rgba.push(u8::MAX);
1260 }
1261 RgbaImage {
1262 width: rgb.width(),
1263 height: rgb.height(),
1264 rgba,
1265 }
1266}