Skip to main content

capsule_core/media/
derivative.rs

1//! Still-derivative tiers, the closed format set, and the signed manifests over them.
2//!
3//! SSoT for the tiers and the formats: [Thumbnails and Previews](https://docs/design/thumbnails/).
4//! This module owns the Capsule-side half — sizing, the closed enum, and building + signing a
5//! [`DerivativeManifest`] through the same two-signature path assets use
6//! ([`DerivativeCore::sign`]) — while `rawshift-image` owns the byte encode.
7//!
8//! # The closed format set, and where it is enforced
9//!
10//! [`DerivativeFormat`] is the tier table's format column as a closed enum. `format` is a
11//! `String` in the signed struct and **stays** one, deliberately: the same field carries
12//! `embedding/{model_id}` for embedding-role manifests (`crate::ml`), so a still-only enum
13//! cannot be its type; and a `try_from` newtype would make
14//! an *older* manifest carrying a future codec fail at deserialisation, turning a policy
15//! rejection into a parse error before any signature is examined. The closed set is therefore
16//! enforced at the two boundaries the contract names:
17//!
18//! - **production** — [`generate_still_derivatives`] only ever writes
19//!   [`DerivativeFormat::mime`], so no other value can be authored here;
20//! - **verification** — [`verify_still_format`](crate::derivative_format::verify_still_format)
21//!   rejects a still-role manifest whose `format` does not parse, which is the structural
22//!   rejection the tier table specifies.
23//!
24//! Note the asymmetry in how those three are linked. Decision 24 moved all of them out of this
25//! feature-gated module so the crates that *receive* a manifest can link the check; this file
26//! then imported `DerivativeFormat`, but not the verification function, which it never calls.
27//! The function therefore has to be written out as `crate::derivative_format::…`, because a bare
28//! name for it resolves only through the `media` re-export — which holds under some feature
29//! unions and not others, so it was a live link in isolation and a broken one in the merged
30//! tree. The other two resolve through the import above, and spelling them out as well would be
31//! a redundant target.
32//!
33//! # What this build encodes
34//!
35//! It depends on the opt-in `media-linked-codecs` feature (issue #437), which links native
36//! encoders and is therefore kept out of `default` — the mobile FFI and the cross targets build
37//! without it:
38//!
39//! | Build | Tiers | Formats |
40//! | --- | --- | --- |
41//! | `media-linked-codecs` (the CLI) | thumbnail, preview | **lossy** JXL (libjxl), AVIF (gamut) |
42//! | `media` alone (mobile FFI, cross targets) | thumbnail | AVIF (gamut) |
43//!
44//! The AVIF encoder is gamut's pure-Rust AV1 intra encoder, so every `media` build writes the
45//! AVIF variant at the tier's quality. The only JPEG XL encoder `rawshift-image` has is libjxl,
46//! a C++ build, so without the feature the JXL master is not written at all and is recorded as a
47//! deferral until upstream has a pure-Rust JXL encoder (visualcommons/rawshift#80). The preview
48//! tier stays with the linked build: it encodes at source resolution, which a phone pays for in
49//! a slow pure-Rust AV1 encode of every original, and its master format is the JXL that build
50//! alone writes.
51//!
52//! WebP — the table's last-resort delivery variant — is **not enabled in either build**:
53//! `rawshift-image`'s WebP is now pure-Rust gamut, but turning it on is its own change. Each
54//! missing pair is recorded as a per-`(tier, format)` deferral on
55//! [`StillDerivatives::deferred`] and warned once, so the gap is countable rather than
56//! invisible.
57//!
58//! [`DerivativeManifest`]: crate::crypto::provenance::DerivativeManifest
59//! [`DerivativeCore::sign`]: crate::crypto::provenance::DerivativeCore::sign
60
61use std::collections::HashMap;
62use std::fmt;
63
64use rawshift_image::core::metadata::ImageMetadata;
65use rawshift_image::core::{BitDepth, ColorDescription, MetadataEmbedOptions, RgbImage};
66use rawshift_image::formats::encode_rgb_image_to_vec;
67#[cfg(feature = "media-linked-codecs")]
68use rawshift_image::formats::export::JxlEncodeConfig;
69use rawshift_image::formats::export::{AvifEncodeConfig, CommonEncodeOptions, EncodeOptions};
70use uuid::Uuid;
71
72use super::decode::DecodedImage;
73use super::error::MediaError;
74use super::resize::downscale_rgba8;
75use crate::crypto::CryptoError;
76use crate::crypto::encryption::NONCE_PREFIX_LEN;
77use crate::crypto::hash::Hash32;
78use crate::crypto::keys::{AmkVersion, Signer};
79use crate::crypto::provenance::{
80    DERIVATIVE_MANIFEST_VERSION, DerivativeCore, DerivativeManifest, DerivativeRole,
81};
82use crate::derivative_format::DerivativeFormat;
83use crate::lqip::RgbaImage;
84
85/// A derivative tier from the tier table.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87pub enum DerivativeTier {
88    /// Grid display: long edge capped at 256 px, q=50.
89    Thumbnail,
90    /// Lightbox / single-asset view: source resolution, q=70. **Generated only under
91    /// `media-linked-codecs`** — its master format is JXL, which only libjxl writes, and a
92    /// source-resolution pure-Rust AV1 encode of every original is too costly for the mobile
93    /// builds that lack it (see the module docs).
94    Preview,
95}
96
97impl DerivativeTier {
98    /// The tiers this build actually generates: both with the JXL master codec linked
99    /// (`media-linked-codecs`), the thumbnail alone without it.
100    #[cfg(feature = "media-linked-codecs")]
101    pub const GENERATED: &'static [Self] = &[Self::Thumbnail, Self::Preview];
102    /// The tiers this build actually generates: both with the JXL master codec linked
103    /// (`media-linked-codecs`), the thumbnail alone without it.
104    #[cfg(not(feature = "media-linked-codecs"))]
105    pub const GENERATED: &'static [Self] = &[Self::Thumbnail];
106
107    /// The provenance role this tier records.
108    pub const fn role(self) -> DerivativeRole {
109        match self {
110            Self::Thumbnail => DerivativeRole::Thumbnail,
111            Self::Preview => DerivativeRole::Preview,
112        }
113    }
114
115    /// The role's on-disk name — mirrors `derivative_role_name` in the upload bundle reader,
116    /// which composes a derivative's exact path from this **and** the manifest's format, so two
117    /// formats of one role stay distinguishable.
118    pub const fn role_name(self) -> &'static str {
119        match self {
120            Self::Thumbnail => "thumbnail",
121            Self::Preview => "preview",
122        }
123    }
124
125    /// Long-edge cap in pixels, or `None` to keep the source resolution. The 1080p cap in the
126    /// tier table governs the *video* preview transcode, not the still preview.
127    pub const fn max_long_edge(self) -> Option<u32> {
128        match self {
129            Self::Thumbnail => Some(256),
130            Self::Preview => None,
131        }
132    }
133
134    /// Lossy encoder quality for this tier, on the 0..=100 scale every backend here uses.
135    pub const fn quality(self) -> f32 {
136        match self {
137            Self::Thumbnail => 50.0,
138            Self::Preview => 70.0,
139        }
140    }
141}
142
143impl fmt::Display for DerivativeTier {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.write_str(self.role_name())
146    }
147}
148
149/// What a derivative's signed manifest has to commit to about its **ciphertext**.
150///
151/// Derivative bytes cross the network encrypted, exactly like the original
152/// ([Encryption](https://docs/design/cryptography/encryption/) — "every asset — original bytes,
153/// derivative bytes, metadata blob — is encrypted client-side"), so the content address a
154/// manifest signs is the address of the *ciphertext*, and the nonce prefix that produced it is
155/// signed alongside because it also selects the key.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct SealedDerivative {
158    /// SHA-256 over the derivative ciphertext.
159    pub ciphertext_hash: Hash32,
160    /// The STREAM nonce prefix the ciphertext was produced under.
161    pub nonce_prefix: [u8; NONCE_PREFIX_LEN],
162}
163
164/// The encryption seam between `media` and `lifecycle`.
165///
166/// `media` owns pixels and knows nothing about album keys; `lifecycle` owns the AMK and must
167/// not own codecs. A derivative's manifest cannot be signed until its ciphertext exists — the
168/// hash is *of* the ciphertext — so the encryption has to happen inside generation, and this is
169/// the narrowest thing that lets it: one method, no key material in any `media` signature.
170///
171/// Each call must draw a **fresh** nonce prefix, so two derivatives of one asset get distinct
172/// keys and distinct ciphertexts even when their plaintext is identical.
173pub trait DerivativeSealer {
174    /// Encrypt `plaintext` under the source asset's identity and epoch, returning what the
175    /// manifest commits to. The ciphertext itself is discarded: clients keep the plaintext
176    /// derivative locally and re-derive the ciphertext at push time from the recorded prefix,
177    /// exactly as they do for the original.
178    ///
179    /// # Errors
180    /// [`MediaError::Sign`], and only that variant. Two things can go wrong: the underlying
181    /// encryption refuses, or no unused nonce prefix can be drawn for this `file_id` inside the
182    /// implementation's retry budget. Both are **workspace** faults rather than pixel ones — a
183    /// broken signer or a broken CSPRNG, not a photo this build cannot render — so the import
184    /// path propagates them instead of degrading to a missing thumbnail. An implementation must
185    /// therefore not report either as [`MediaError::Encode`], which means a codec refused a
186    /// frame and nothing else.
187    ///
188    /// `replaces` plays no part here: a derivative supersedes nothing, so the production
189    /// implementation passes `None` and enforces non-reuse against the set of prefixes already
190    /// spent on this `file_id` instead.
191    fn seal(&self, plaintext: &[u8]) -> Result<SealedDerivative, MediaError>;
192}
193
194/// Everything the manifest signer needs that the pixels do not carry: the asset identity, the
195/// epoch/authorisation context, and the two signing keys that produce the manifest's two hybrid
196/// signatures.
197pub struct DerivativeContext<'a> {
198    /// The asset the derivatives are generated from.
199    pub source_asset_id: Uuid,
200    /// Primitive bundle in force.
201    pub crypto_suite_id: u16,
202    /// Date-based wire protocol version (matches the album pin).
203    pub protocol_version: String,
204    /// The AMK epoch whose write-tier key signs the manifests.
205    pub amk_version: AmkVersion,
206    /// Device that generated the derivatives.
207    pub generated_by_device: Uuid,
208    /// Generating client version string.
209    pub generated_by_client: String,
210    /// RFC 3339 generation time (audit-only).
211    pub generated_at: String,
212    /// The device DSK (provenance signature); may be hardware-backed.
213    pub device_signer: &'a dyn Signer,
214    /// The per-epoch write-tier key (authorisation signature).
215    pub write_tier_signer: &'a dyn Signer,
216    /// Encrypts each generated derivative so its manifest can commit to the ciphertext.
217    pub sealer: &'a dyn DerivativeSealer,
218    /// The current head of each role's derivative chain, when this asset already has one.
219    ///
220    /// A `HashMap` rather than a `BTreeMap` because [`DerivativeRole`] derives `Hash + Eq` and
221    /// not `Ord`, and adding `Ord` to a signed wire type to key a lookup would be the tail
222    /// wagging the dog. Iteration order never escapes this map — it is only ever queried by
223    /// key — so the non-determinism a `HashMap` would otherwise introduce cannot reach the
224    /// signed bytes.
225    ///
226    /// A role's manifests are append-only **across time**, not merely within one call: a
227    /// backfill that adds the AVIF variant to an asset that already has a JXL thumbnail extends
228    /// that role's chain rather than starting a second one. Empty on a create, which is why the
229    /// import path passes an empty map; a regeneration reads it off the persisted bundle.
230    pub prior_heads: &'a HashMap<DerivativeRole, Hash32>,
231    /// What the **original**'s own manifest committed to. The `original` sentinel generates no
232    /// bytes and encrypts nothing: it is a reference to the original blob, so it signs the
233    /// original's ciphertext address and the original's nonce prefix, and a receiver resolves it
234    /// against the blob it already has.
235    pub original: SealedDerivative,
236}
237
238/// One generated derivative: the encoded bytes plus its signed manifest.
239#[derive(Debug, Clone)]
240pub struct GeneratedDerivative {
241    /// Which tier this is.
242    pub tier: DerivativeTier,
243    /// Which committed format, or the `Original` sentinel.
244    pub format: DerivativeFormat,
245    /// The derivative bytes — the encoder output, and **empty** for
246    /// [`DerivativeFormat::Original`], whose manifest is a reference to the original rather than
247    /// a copy of it.
248    pub bytes: Vec<u8>,
249    /// The signed manifest binding `hash(bytes)`, the role and the format.
250    pub manifest: DerivativeManifest,
251}
252
253/// The outcome of one asset's still-derivative generation.
254///
255/// `deferred` is the per-`(tier, format)` gap the design requires: a pair with no encoder in this
256/// build is *recorded*, not collapsed into the asset-level status. The asset is still
257/// `DerivativeStatus::Decoded` — the decode succeeded and a renderable derivative exists —
258/// which is why the two live in different places.
259#[derive(Debug, Clone, Default)]
260pub struct StillDerivatives {
261    /// The derivatives that were produced, in generation order.
262    pub generated: Vec<GeneratedDerivative>,
263    /// The `(tier, format)` pairs the tier table commits to and this build did not produce:
264    /// those it links no encoder for, and those whose encoder refused (or panicked on) this
265    /// particular frame — both backfillable from the stored original.
266    pub deferred: Vec<(DerivativeTier, DerivativeFormat)>,
267}
268
269/// Generate the committed still derivatives for `decoded` across `tiers`, signing a
270/// [`DerivativeManifest`] for each.
271///
272/// Per tier:
273/// - if the tier caps the long edge and the source is **not larger** than the cap, a single
274///   `format = "original"` manifest is signed as a *reference* to the original blob (no bytes,
275///   nothing encrypted, committing to [`DerivativeContext::original`]) — the
276///   redundant-derivative sentinel from the contract, never a re-encode;
277/// - otherwise the frame is downscaled to the tier, encoded to each encodable format of
278///   [`DerivativeFormat::STILL_DELIVERY_ORDER`], and **encrypted** through
279///   [`DerivativeContext::sealer`] before its manifest is signed over the ciphertext's address;
280///   the formats with no encoder here are recorded as deferrals, and so is any single pair whose
281///   encoder refuses or panics on the frame — the tier's other formats, and the other tiers,
282///   still run.
283///
284/// Manifests of the same role are hash-chained in generation order, so a role's derivative
285/// provenance is append-only exactly like the asset's.
286///
287/// # Errors
288/// - [`MediaError::Encode`] or [`MediaError::DecoderPanic`] — a codec refused (or panicked on)
289///   the frame for **every** pair attempted, so no derivative was produced at all; the first
290///   such failure is returned. A refusal on some pairs only is a deferral, not an error.
291///   "A codec refused the frame" is the **only** thing `Encode` means here.
292/// - [`MediaError::ZeroDimension`] — the source frame has a zero dimension.
293/// - [`MediaError::Sign`] — the device signer or the epoch write-tier signer refused, or
294///   [`DerivativeContext::sealer`] failed (an encryption refusal, or an exhausted nonce-prefix
295///   draw).
296///
297/// The split is the contract rather than bookkeeping. The import path degrades the first two to
298/// "this asset has no thumbnail" and commits the original anyway; it **propagates** `Sign`,
299/// because a workspace that cannot author a signed record is broken in a way a missing
300/// derivative is not — the same fault would stop the asset's own manifest.
301#[tracing::instrument(
302    level = "debug",
303    skip_all,
304    fields(asset_id = %ctx.source_asset_id, tiers = tiers.len())
305)]
306pub fn generate_still_derivatives(
307    decoded: &DecodedImage,
308    tiers: &[DerivativeTier],
309    ctx: &DerivativeContext<'_>,
310) -> Result<StillDerivatives, MediaError> {
311    if decoded.width() == 0 || decoded.height() == 0 {
312        return Err(MediaError::ZeroDimension {
313            width: decoded.width(),
314            height: decoded.height(),
315        });
316    }
317
318    let mut out = StillDerivatives::default();
319    // The first per-pair encode failure, reported only if no derivative was produced at all.
320    let mut first_failure: Option<MediaError> = None;
321    let source_long_edge = decoded.width().max(decoded.height());
322
323    for &tier in tiers {
324        // Each tier records a distinct role, so its manifests form their own chain — continued
325        // from wherever that role left off, not restarted.
326        let mut prior: Option<Hash32> = ctx.prior_heads.get(&tier.role()).copied();
327
328        if let Some(cap) = tier.max_long_edge()
329            && source_long_edge <= cap
330        {
331            tracing::debug!(
332                asset_id = %ctx.source_asset_id,
333                %tier,
334                source_long_edge,
335                cap,
336                "media: source is within the tier cap; signing the `original` sentinel"
337            );
338            // A reference to the original blob: no bytes of its own, and **nothing encrypted**
339            // — it commits to the original's own ciphertext address and nonce prefix, and the
340            // receiver resolves it against the blob it already holds. See
341            // `DerivativeFormat::Original`.
342            out.generated.push(sign_derivative(
343                ctx,
344                tier,
345                DerivativeFormat::Original,
346                Vec::new(),
347                ctx.original,
348                &mut prior,
349            )?);
350            continue;
351        }
352
353        let work = match tier.max_long_edge() {
354            Some(cap) => downscale_rgba8(&decoded.image, cap),
355            None => decoded.image.clone(),
356        };
357        for format in DerivativeFormat::STILL_DELIVERY_ORDER {
358            if !format.is_encodable() {
359                tracing::warn!(
360                    asset_id = %ctx.source_asset_id,
361                    %tier,
362                    %format,
363                    "media: no encoder for this (tier, format) in this build; the tier still \
364                     ships its encodable variants and this pair is backfillable"
365                );
366                out.deferred.push((tier, format));
367                continue;
368            }
369            // Guarded: the encoders here are a pre-1.0 Rust crate or a C/C++ library behind
370            // a pre-1.0 binding, and a panic inside one must not abort an import that may hold the only copy of a file. The
371            // stage name makes a caught unwind attributable to the encoder rather than to the
372            // decoder that ran before it.
373            //
374            // A refusal here is **this pair's** failure, not the asset's: an AV1 encoder rejects
375            // a frame edge over 65535 px, which the decode budget admits (a wide panorama), so
376            // the source-resolution preview AVIF can fail while the JXL beside it encodes fine.
377            // The pair is recorded as a deferral — backfillable like any other — and the
378            // tier's remaining formats still run. Only a call that produced nothing at all
379            // reports the failure, below, so an asset with no renderable derivative is still
380            // counted as one somebody should look at.
381            let bytes = match super::decode::guarded("encode", || encode(&work, format, tier)) {
382                Ok(bytes) => bytes,
383                Err(error) => {
384                    tracing::warn!(
385                        asset_id = %ctx.source_asset_id,
386                        %tier,
387                        %format,
388                        width = work.width,
389                        height = work.height,
390                        %error,
391                        "media: the encoder refused this (tier, format); recording it as a \
392                         deferral and continuing with the remaining pairs"
393                    );
394                    out.deferred.push((tier, format));
395                    first_failure.get_or_insert(error);
396                    continue;
397                }
398            };
399            // Encrypt before signing: the manifest's content address is the ciphertext's, so
400            // the ciphertext has to exist first. A fresh prefix per derivative, so two
401            // derivatives of one asset never share a key even for identical plaintext.
402            let sealed = ctx.sealer.seal(&bytes)?;
403            out.generated.push(sign_derivative(
404                ctx, tier, format, bytes, sealed, &mut prior,
405            )?);
406        }
407    }
408
409    // Every pair that was attempted failed, so nothing renderable exists: that is the asset's
410    // failure, and the caller degrades it to `DecodeFailed` as before.
411    if out.generated.is_empty()
412        && let Some(error) = first_failure
413    {
414        return Err(error);
415    }
416
417    tracing::debug!(
418        asset_id = %ctx.source_asset_id,
419        generated = out.generated.len(),
420        deferred = out.deferred.len(),
421        "media: still derivatives generated"
422    );
423    Ok(out)
424}
425
426/// Encode a tier-sized RGBA8 frame to `format`.
427///
428/// **Every encode passes [`MetadataEmbedOptions::none`] and an empty [`ImageMetadata`]**, and
429/// both are load-bearing rather than tidy: the crate's own default is `all()`, so a
430/// default-configured encode copies the source's EXIF — GPS fix included — into the derivative
431/// bytes, and the JXL backend has a working `append_to_jxl` that would do exactly that. A
432/// thumbnail is the derivative most likely to be served widest, so leaking a home address into
433/// it would be the worst possible place for that default to win. Passing empty metadata means
434/// the source's block is never even read. A test asserts the absence rather than trusting this
435/// comment.
436fn encode(
437    frame: &RgbaImage,
438    format: DerivativeFormat,
439    tier: DerivativeTier,
440) -> Result<Vec<u8>, MediaError> {
441    let common = CommonEncodeOptions {
442        metadata: MetadataEmbedOptions::none(),
443        bit_depth: BitDepth::Eight,
444    };
445    let options = match format {
446        // The lossy master: libjxl, at the Butteraugli distance libjxl's own
447        // `JxlEncoderDistanceFromQuality` gives the tier's JPEG-style quality (`jxl_distance`).
448        // `lossless: false` is explicit rather than defaulted because it is the whole point of
449        // this backend. Effort 7 is libjxl's own default.
450        #[cfg(feature = "media-linked-codecs")]
451        DerivativeFormat::Jxl => EncodeOptions::Jxl(JxlEncodeConfig {
452            common,
453            lossless: false,
454            distance: jxl_distance(tier.quality()),
455            effort: 7,
456            ..JxlEncodeConfig::default()
457        }),
458        // The AVIF delivery variant, through gamut's pure-Rust AV1 intra encoder, so every
459        // `media` build writes it. `quality` is the same 0..=100 scale, so the tier's value
460        // converts exactly (50 and 70); `lossless: false` because the encoder's default is
461        // lossless.
462        DerivativeFormat::Avif => EncodeOptions::Avif(AvifEncodeConfig {
463            common,
464            lossless: false,
465            quality: tier.quality() as u8,
466        }),
467        // Unreachable: `is_encodable` gates the call, and `Original` never routes here at all
468        // (it carries no bytes). Kept as a typed refusal rather than a panic so a future
469        // widening that forgets an arm degrades to a reported failure. Reported as
470        // `Encode { format }` and not `UnsupportedFormat`, because the latter names a
471        // `StillFormat` and there is no still format at fault here — the caller asked for a
472        // *derivative* format this build cannot write, and the message has to say which.
473        #[cfg(not(feature = "media-linked-codecs"))]
474        DerivativeFormat::Jxl => {
475            return Err(MediaError::Encode {
476                format,
477                detail: "this build links no encoder for this derivative format".to_string(),
478            });
479        }
480        DerivativeFormat::WebP | DerivativeFormat::Original => {
481            return Err(MediaError::Encode {
482                format,
483                detail: "this build links no encoder for this derivative format".to_string(),
484            });
485        }
486    };
487
488    let rgb = to_rgb_u16(frame, format)?;
489    encode_rgb_image_to_vec(&rgb, &ImageMetadata::default(), &options).map_err(|e| {
490        MediaError::Encode {
491            format,
492            detail: e.to_string(),
493        }
494    })
495}
496
497/// The Butteraugli distance libjxl's `JxlEncoderDistanceFromQuality` gives a JPEG-style
498/// `quality`, since `JxlEncodeConfig` takes a distance where the 0.1.1 backend took a quality
499/// and mapped it the same way. q=50 is 4.6 and q=70 is 2.8; the result is clamped into the
500/// `(0.0, 25.0]` range the config accepts.
501#[cfg(feature = "media-linked-codecs")]
502pub(super) fn jxl_distance(quality: f32) -> f32 {
503    let distance = if quality >= 100.0 {
504        0.0
505    } else if quality >= 30.0 {
506        0.1 + (100.0 - quality) * 0.09
507    } else {
508        53.0 / 3000.0 * quality * quality - 23.0 / 20.0 * quality + 25.0
509    };
510    distance.clamp(0.01, 25.0)
511}
512
513/// Widen packed RGBA8 to the interleaved RGB `u16` the encoders take, dropping alpha.
514///
515/// `v * 257` is the crate's own widening, and the encoders narrow it back with `v >> 8`, so an
516/// 8-bit frame reaches the codec bit-for-bit. Alpha is dropped because the decode path already
517/// flattened it — every frame here is opaque.
518///
519/// # Errors
520/// [`MediaError::Encode`] when `RgbImage` refuses the buffer, which it does only for a zero
521/// dimension; [`generate_still_derivatives`] refuses those before it encodes anything.
522fn to_rgb_u16(frame: &RgbaImage, format: DerivativeFormat) -> Result<RgbImage, MediaError> {
523    let mut data = Vec::with_capacity(frame.rgba.len() / 4 * 3);
524    for px in frame.rgba.chunks_exact(4) {
525        data.push(u16::from(px[0]) * 257);
526        data.push(u16::from(px[1]) * 257);
527        data.push(u16::from(px[2]) * 257);
528    }
529    RgbImage::with_color(frame.width, frame.height, data, ColorDescription::SRGB).map_err(|e| {
530        MediaError::Encode {
531            format,
532            detail: e.to_string(),
533        }
534    })
535}
536
537/// Build, sign and chain one derivative manifest.
538///
539/// `bytes` is the **plaintext** the client keeps on disk; `sealed` is what the manifest actually
540/// commits to — the ciphertext's content address and the nonce prefix that produced it. The two
541/// are separate arguments because they are separate artefacts: only one of them ever crosses the
542/// network, and only the other is ever painted locally.
543///
544/// `pub(super)` so the module's tests can exercise the chaining directly. That is not test
545/// convenience for its own sake: a build without `media-linked-codecs` encodes exactly one still
546/// format, so there a single call to [`generate_still_derivatives`] produces one manifest per
547/// role and the multi-link case — the part of the chain that can actually be wrong — is
548/// unreachable through the public entry point.
549pub(super) fn sign_derivative(
550    ctx: &DerivativeContext<'_>,
551    tier: DerivativeTier,
552    format: DerivativeFormat,
553    bytes: Vec<u8>,
554    sealed: SealedDerivative,
555    prior: &mut Option<Hash32>,
556) -> Result<GeneratedDerivative, MediaError> {
557    let core = DerivativeCore {
558        version: DERIVATIVE_MANIFEST_VERSION.into(),
559        crypto_suite_id: ctx.crypto_suite_id,
560        protocol_version: Some(ctx.protocol_version.clone()),
561        amk_version: Some(ctx.amk_version),
562        source_asset_id: ctx.source_asset_id,
563        role: tier.role(),
564        format: format.mime().into(),
565        // The address of the **ciphertext**, not of `bytes`: `bytes` is the plaintext kept
566        // locally, and what a receiver content-addresses is what crossed the network.
567        ciphertext_hash: sealed.ciphertext_hash,
568        nonce_prefix: sealed.nonce_prefix,
569        generated_by_device: ctx.generated_by_device,
570        generated_by_client: ctx.generated_by_client.clone(),
571        model_id: None,
572        model_version: None,
573        generated_at: ctx.generated_at.clone(),
574        prior_provenance_hash: *prior,
575    };
576    let manifest = core
577        .sign(ctx.device_signer, ctx.write_tier_signer)
578        .map_err(|e: CryptoError| MediaError::Sign {
579            detail: format!("signing the derivative manifest: {e}"),
580        })?;
581    // The next manifest of this role chains to this one, by the one definition of the link
582    // that `verify_derivative` also walks the chain with.
583    *prior = Some(manifest.link_hash());
584    Ok(GeneratedDerivative {
585        tier,
586        format,
587        bytes,
588        manifest,
589    })
590}