Skip to main content

capsule_sdk/fetch/
ladder.rs

1//! The **render ladder**: which representation a surface shows now, and what to obtain next
2//! (SSoT: [Download — Render Ladder]).
3//!
4//! The order is computed here, once, and every native app reaches it through the FFI
5//! (`capsule_sdk::ffi::render_step`); an app renders the [`Rendition`] it names and keeps no ladder
6//! of its own. It extends the [`Representation`] degrade ladder with what is already on the
7//! device: a RAW original's [embedded preview], which stands in for a rung until that rung's
8//! encoded tier is held.
9//!
10//! # One pure function
11//!
12//! [`render_step`] takes the surface's request, what it already shows, what the device holds and
13//! what the server lists, and answers what to show and what to obtain next. It holds no state:
14//! the surface keeps the [`Rendition`] it shows and passes it back on the next call, which is how
15//! a view **upgrades in place** as a better rung arrives and never downgrades one it has shown.
16//! Falling back below what is shown (a held rung that was evicted or would not open — the
17//! [fallback ladder]) is the same call with nothing shown.
18//!
19//! # Where the halves live
20//!
21//! The local half is a value: [`LocalHoldings`] says which encoded tiers and whether the original
22//! are held, and the embedded preview's size, which the caller reads from the original through
23//! `capsule_core::media::extract_embedded_preview`. The fetched half is the set of
24//! representations the server lists ([`AssetBlobs::blob_for`](super::AssetBlobs::blob_for)).
25//! Neither needs `capsule-library` state, so the ladder sits beside [`Representation`] rather than
26//! in the library.
27//!
28//! [Download — Render Ladder]: https://docs/design/transfer/download/#render-ladder
29//! [embedded preview]: https://docs/design/thumbnails/#embedded-previews
30//! [fallback ladder]: https://docs/design/transfer/download/#fallback-ladder
31
32use std::cmp::Ordering;
33use std::collections::BTreeSet;
34
35use capsule_core::media::DerivativeTier;
36
37use super::Representation;
38
39/// A size in device pixels.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
41pub struct PixelSize {
42    /// Width in pixels.
43    pub width: u32,
44    /// Height in pixels.
45    pub height: u32,
46}
47
48impl PixelSize {
49    /// The longer of the two edges.
50    #[must_use]
51    pub const fn long_edge(self) -> u32 {
52        if self.width >= self.height {
53            self.width
54        } else {
55            self.height
56        }
57    }
58
59    /// Whether a frame of this size covers `surface`: fitting it inside the surface, aspect
60    /// preserved, needs no upscaling. That is the case exactly when it reaches the surface's
61    /// width or its height, because the fit scale is the smaller of the two ratios. An empty
62    /// surface is covered by anything.
63    #[must_use]
64    pub const fn covers(self, surface: Self) -> bool {
65        self.width >= surface.width || self.height >= surface.height
66    }
67}
68
69/// Where the pixels of a shown rung come from.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
71pub enum RungSource {
72    /// The LQIP from the metadata blob, or its dominant colour where it does not decode.
73    Lqip,
74    /// A RAW original's embedded preview, standing in for the rung's encoded tier.
75    Embedded,
76    /// The rung's encoded tier (thumbnail or preview derivative).
77    Encoded,
78    /// The original, decoded.
79    Original,
80}
81
82/// What a surface shows: a rung, and the source that fills it.
83///
84/// Ordered by fidelity: by rung, and within a rung the encoded tier above the embedded preview
85/// that stands in for it.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Rendition {
88    /// The rung shown.
89    pub rung: Representation,
90    /// What fills it.
91    pub source: RungSource,
92}
93
94impl Rendition {
95    /// The bottom of the ladder, always present.
96    pub const LQIP: Self = Self {
97        rung: Representation::Lqip,
98        source: RungSource::Lqip,
99    };
100}
101
102impl Ord for Rendition {
103    fn cmp(&self, other: &Self) -> Ordering {
104        (self.rung, self.source).cmp(&(other.rung, other.source))
105    }
106}
107
108impl PartialOrd for Rendition {
109    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
110        Some(self.cmp(other))
111    }
112}
113
114/// What a surface asks the ladder for.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct RenderRequest {
117    /// The rung the surface's intent needs: the grid asks for
118    /// [`Thumbnail`](Representation::Thumbnail), the single-asset view for
119    /// [`Preview`](Representation::Preview), a full-fidelity view for
120    /// [`Original`](Representation::Original).
121    pub intent: Representation,
122    /// The surface's size in device pixels **when the view opened**. An embedded preview fills
123    /// Preview only if it covers this; a view that later grows keeps passing the size it opened
124    /// at, so it keeps the embedded preview rather than dropping a rung.
125    pub surface: PixelSize,
126}
127
128/// What this device holds for one asset.
129#[derive(Debug, Clone, Default, PartialEq, Eq)]
130pub struct LocalHoldings {
131    /// The representations held locally: the encoded [`Thumbnail`](Representation::Thumbnail)
132    /// and [`Preview`](Representation::Preview) tiers and the
133    /// [`Original`](Representation::Original). The LQIP is always held and need not be listed.
134    pub held: BTreeSet<Representation>,
135    /// The size of the original's embedded preview, upright, where this device holds a RAW
136    /// original that carries one which extracted.
137    pub embedded_preview: Option<PixelSize>,
138}
139
140/// How to obtain the next rung.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum NextStep {
143    /// Fetch this representation from the server ([`super::open_representation`]).
144    Fetch(Representation),
145    /// Produce this rung on the device from the original it holds.
146    Generate(Representation),
147}
148
149/// The answer to one [`render_step`].
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct RenderStep {
152    /// What to show now.
153    pub show: Rendition,
154    /// Whether `show` differs from what the surface already showed: a better rung arrived, or
155    /// nothing was shown yet.
156    pub changed: bool,
157    /// What to obtain next to reach the intent, or `None` when the intent is met or nothing can
158    /// raise it.
159    pub next: Option<NextStep>,
160}
161
162/// The long edge an embedded preview must reach to fill the Thumbnail rung: the Thumbnail
163/// tier's own.
164#[must_use]
165pub fn thumbnail_long_edge() -> u32 {
166    DerivativeTier::Thumbnail
167        .max_long_edge()
168        .unwrap_or(u32::MAX)
169}
170
171/// The best rendition held at or below `request.intent`.
172fn best_held(request: &RenderRequest, local: &LocalHoldings) -> Rendition {
173    let intent = request.intent;
174    let encoded = |rung: Representation| {
175        (rung <= intent && local.held.contains(&rung)).then_some(Rendition {
176            rung,
177            source: if rung == Representation::Original {
178                RungSource::Original
179            } else {
180                RungSource::Encoded
181            },
182        })
183    };
184    let embedded = local.embedded_preview.and_then(|size| {
185        let preview = Representation::Preview;
186        let thumbnail = Representation::Thumbnail;
187        let rung = if preview <= intent && size.covers(request.surface) {
188            preview
189        } else if thumbnail <= intent && size.long_edge() >= thumbnail_long_edge() {
190            thumbnail
191        } else {
192            return None;
193        };
194        Some(Rendition {
195            rung,
196            source: RungSource::Embedded,
197        })
198    });
199    [
200        encoded(Representation::Thumbnail),
201        encoded(Representation::Preview),
202        encoded(Representation::Original),
203        embedded,
204    ]
205    .into_iter()
206    .flatten()
207    .fold(Rendition::LQIP, Ord::max)
208}
209
210/// What to obtain next so `show` reaches the intent.
211///
212/// - The intent's encoded tier (or, for Original, the original) is shown, or a rung above the
213///   intent is shown from any source: nothing.
214/// - The intent rung is filled by the embedded preview: fetch the encoded tier where the server
215///   lists it, since it replaces the camera's rendering; never generate it here, which is the
216///   import's work.
217/// - Otherwise fetch it where the server lists it, else generate it from a held original. The
218///   fetch is preferred: an encoded tier is small, and generating one can mean developing a RAW.
219///   The original itself is only ever fetched, and only when it is the intent.
220fn next_step(
221    request: &RenderRequest,
222    show: Rendition,
223    local: &LocalHoldings,
224    fetchable: &BTreeSet<Representation>,
225) -> Option<NextStep> {
226    let intent = request.intent;
227    if intent == Representation::Lqip {
228        return None;
229    }
230    // A rung above the intent (a surface passing back what a larger view showed) already
231    // outranks the intent's encoded tier, whatever fills it: obtaining that tier could never
232    // change what is shown, so only an embedded preview exactly at the intent asks for it.
233    if show.rung > intent {
234        return None;
235    }
236    let filled = show.rung == intent;
237    if filled && show.source != RungSource::Embedded {
238        return None;
239    }
240    if fetchable.contains(&intent) {
241        return Some(NextStep::Fetch(intent));
242    }
243    let generatable = intent != Representation::Original
244        && local.held.contains(&Representation::Original)
245        && !filled;
246    generatable.then_some(NextStep::Generate(intent))
247}
248
249/// One step of the render ladder: what to show, and what to obtain next.
250///
251/// `shown` is what the surface shows now, `None` when it shows nothing yet or is falling back.
252/// The answer never shows less than `shown`: a rung below it is kept off screen until the
253/// surface itself falls back, by calling with `None`.
254///
255/// `fetchable` is the representations the server lists for the asset
256/// ([`AssetBlobs::blob_for`](super::AssetBlobs::blob_for) returns `Some`) and this device can
257/// still fetch.
258#[must_use]
259#[tracing::instrument(level = "trace", skip(local, fetchable), ret)]
260pub fn render_step(
261    request: &RenderRequest,
262    shown: Option<Rendition>,
263    local: &LocalHoldings,
264    fetchable: &BTreeSet<Representation>,
265) -> RenderStep {
266    let best = best_held(request, local);
267    let show = shown.map_or(best, |shown| shown.max(best));
268    let next = next_step(request, show, local, fetchable);
269    RenderStep {
270        show,
271        changed: shown != Some(show),
272        next,
273    }
274}
275
276#[cfg(test)]
277mod tests;