alpha2_model/provider.rs
1//! Sources whose media an extension provider supplies.
2
3use alpha2_time::FrameRate;
4use serde::{Deserialize, Serialize};
5
6use crate::{MAX_TEXT_CONTENT_BYTES, MediaKind, Rgba};
7
8/// Most frames an image sequence lists.
9pub const MAX_SEQUENCE_FRAMES: usize = 100_000;
10
11/// Largest dotLottie package a provider reads, in bytes, refusing larger files unread. Only the
12/// shown animation (within [`MAX_LOTTIE_DOCUMENT_BYTES`]) and its images are unpacked.
13pub const MAX_PROVIDER_DOCUMENT_BYTES: usize = 256 * 1024 * 1024;
14
15/// Largest Lottie animation a provider reads, in bytes (a JSON file or an unpacked dotLottie
16/// animation). Parsing can take about 45 times the document size, so this caps it near
17/// 750 MiB; larger documents are refused before parsing.
18pub const MAX_LOTTIE_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
19
20/// Largest SVG document a provider reads, in bytes. Parsing can take about 30 times the
21/// document size, so this caps it near 960 MiB; larger documents are refused before parsing.
22pub const MAX_SVG_DOCUMENT_BYTES: usize = 32 * 1024 * 1024;
23
24/// Longest LaTeX formula a source holds, in bytes.
25pub const MAX_LATEX_BYTES: usize = MAX_TEXT_CONTENT_BYTES;
26
27/// Largest LaTeX font size, in pixels per em.
28pub const MAX_LATEX_FONT_SIZE: f32 = 1_024.0;
29
30/// Largest PDF document a provider reads, in bytes. Larger files are refused before reading.
31pub const MAX_PDF_DOCUMENT_BYTES: usize = 256 * 1024 * 1024;
32
33/// Most pages a PDF document a provider reads may have.
34pub const MAX_PDF_PAGES: u32 = 10_000;
35
36/// A source whose media an extension provider supplies, not the host's video and image decoders.
37///
38/// A host picks the provider by probing the bytes at import, never by file name, and records
39/// it here so every host opens the source the same way. The engine does not read it.
40#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
41#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
42#[serde(tag = "format", rename_all = "snake_case", from = "ProviderSourceWire")]
43#[non_exhaustive]
44pub enum ProviderSource {
45 /// A static SVG document, rasterized at its shown size. The source's kind is `image`.
46 Svg,
47 /// A GIF, animated WebP, or APNG: one cycle of frames, each with its own duration.
48 /// Repetition is the clip's. The source's kind is `video`.
49 AnimatedImage,
50 /// A Lottie animation (JSON file or dotLottie package), evaluated at its own frames. The
51 /// source's kind is `video`.
52 Lottie {
53 /// The dotLottie animation shown, by ID. Absent means the package's first; always absent
54 /// for a Lottie JSON file.
55 #[serde(default, skip_serializing_if = "Option::is_none")]
56 animation: Option<String>,
57 },
58 /// Still images played in order at a fixed rate. The source's kind is `video`.
59 ImageSequence {
60 /// Each frame's locator, in play order. `null` marks a missing number, allowed only when
61 /// `missing` says how to show it.
62 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SEQUENCE_FRAMES)))]
63 frames: Vec<Option<String>>,
64 /// The rate the frames play at.
65 frame_rate: FrameRate,
66 /// The number of the first frame, as its file was numbered.
67 #[serde(default)]
68 start_number: u64,
69 /// How a missing frame is shown.
70 #[serde(default)]
71 missing: MissingFrames,
72 /// The primaries of OpenEXR frames' linear RGB, overriding the first frame's
73 /// chromaticities. Only for OpenEXR frames.
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 primaries: Option<LinearPrimaries>,
76 },
77 /// A still OpenEXR image: linear-light RGB(A), read at half precision. The source's kind is
78 /// `image`.
79 Exr {
80 /// The primaries of its linear RGB, overriding the file's chromaticities (BT.709 when the
81 /// file has none, as OpenEXR defines).
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 primaries: Option<LinearPrimaries>,
84 },
85 /// A LaTeX math formula typeset with the bundled STIX Two Math font. The source's kind is
86 /// `image`, and it has no locator or fingerprint since it reads no file. A formula that uses
87 /// a character the font lacks, such as Hangul in `\text`, does not open.
88 Latex {
89 /// Math-mode LaTeX without `$` delimiters. Non-empty, at most [`MAX_LATEX_BYTES`] bytes.
90 latex: String,
91 /// Pixels per em, above `0` and at most [`MAX_LATEX_FONT_SIZE`].
92 font_size: f32,
93 /// The ink where the formula sets no `\color` of its own. White when absent.
94 #[serde(default = "white")]
95 color: Rgba,
96 /// Display style, with large operators and limits above and below, or text style when
97 /// `false`. Display when absent.
98 #[serde(default = "display_style")]
99 display: bool,
100 },
101 /// One page of a PDF document. The source's kind is `image`.
102 Pdf {
103 /// The page shown, counted from `1`, at most [`MAX_PDF_PAGES`]. The first when absent.
104 #[serde(default = "first_page")]
105 page: u32,
106 /// Painted under the page, which is itself transparent. White paper when absent.
107 #[serde(default = "white")]
108 background: Rgba,
109 },
110}
111
112/// The wire form of [`ProviderSource`].
113///
114/// serde lets an internally tagged unit variant ignore extra fields even with
115/// `deny_unknown_fields`; empty struct variants reject them, as the published schema does.
116#[derive(Deserialize)]
117#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
118#[cfg_attr(feature = "schema", schemars(rename = "ProviderSource"))]
119#[serde(tag = "format", rename_all = "snake_case", deny_unknown_fields)]
120pub(crate) enum ProviderSourceWire {
121 /// A static SVG document, rasterized at its shown size. The source's kind is `image`.
122 Svg {},
123 /// A GIF, animated WebP, or APNG: one cycle of frames, each with its own duration.
124 /// Repetition is the clip's. The source's kind is `video`.
125 AnimatedImage {},
126 /// A Lottie animation (JSON file or dotLottie package), evaluated at its own frames. The
127 /// source's kind is `video`.
128 Lottie {
129 /// The dotLottie animation shown, by ID. Absent means the package's first; always absent
130 /// for a Lottie JSON file.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 animation: Option<String>,
133 },
134 /// Still images played in order at a fixed rate. The source's kind is `video`.
135 ImageSequence {
136 /// Each frame's locator, in play order. `null` marks a missing number, allowed only when
137 /// `missing` says how to show it.
138 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SEQUENCE_FRAMES }>")]
139 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SEQUENCE_FRAMES)))]
140 frames: Vec<Option<String>>,
141 /// The rate the frames play at.
142 frame_rate: FrameRate,
143 /// The number of the first frame, as its file was numbered.
144 #[serde(default)]
145 start_number: u64,
146 /// How a missing frame is shown.
147 #[serde(default)]
148 missing: MissingFrames,
149 /// The primaries of OpenEXR frames' linear RGB, overriding the first frame's
150 /// chromaticities. Only for OpenEXR frames.
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 primaries: Option<LinearPrimaries>,
153 },
154 /// A still OpenEXR image: linear-light RGB(A), read at half precision. The source's kind is
155 /// `image`.
156 Exr {
157 /// The primaries of its linear RGB, overriding the file's chromaticities (BT.709 when the
158 /// file has none, as OpenEXR defines).
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 primaries: Option<LinearPrimaries>,
161 },
162 /// A LaTeX math formula typeset with the bundled STIX Two Math font. The source's kind is
163 /// `image`, and it has no locator or fingerprint since it reads no file. A formula that uses
164 /// a character the font lacks, such as Hangul in `\text`, does not open.
165 Latex {
166 /// Math-mode LaTeX without `$` delimiters. Non-empty, at most [`MAX_LATEX_BYTES`] bytes.
167 latex: String,
168 /// Pixels per em, above `0` and at most [`MAX_LATEX_FONT_SIZE`].
169 font_size: f32,
170 /// The ink where the formula sets no `\color` of its own. White when absent.
171 #[serde(default = "white")]
172 color: Rgba,
173 /// Display style, with large operators and limits above and below, or text style when
174 /// `false`. Display when absent.
175 #[serde(default = "display_style")]
176 display: bool,
177 },
178 /// One page of a PDF document. The source's kind is `image`.
179 Pdf {
180 /// The page shown, counted from `1`, at most [`MAX_PDF_PAGES`]. The first when absent.
181 #[serde(default = "first_page")]
182 page: u32,
183 /// Painted under the page, which is itself transparent. White paper when absent.
184 #[serde(default = "white")]
185 background: Rgba,
186 },
187}
188
189impl From<ProviderSourceWire> for ProviderSource {
190 fn from(wire: ProviderSourceWire) -> Self {
191 match wire {
192 ProviderSourceWire::Svg {} => Self::Svg,
193 ProviderSourceWire::AnimatedImage {} => Self::AnimatedImage,
194 ProviderSourceWire::Lottie { animation } => Self::Lottie { animation },
195 ProviderSourceWire::ImageSequence {
196 frames,
197 frame_rate,
198 start_number,
199 missing,
200 primaries,
201 } => Self::ImageSequence {
202 frames,
203 frame_rate,
204 start_number,
205 missing,
206 primaries,
207 },
208 ProviderSourceWire::Exr { primaries } => Self::Exr { primaries },
209 ProviderSourceWire::Latex {
210 latex,
211 font_size,
212 color,
213 display,
214 } => Self::Latex {
215 latex,
216 font_size,
217 color,
218 display,
219 },
220 ProviderSourceWire::Pdf { page, background } => Self::Pdf { page, background },
221 }
222 }
223}
224
225const fn white() -> Rgba {
226 Rgba::new(1.0, 1.0, 1.0, 1.0)
227}
228
229const fn display_style() -> bool {
230 true
231}
232
233const fn first_page() -> u32 {
234 1
235}
236
237/// Named RGB primaries linear-light media may be in, each with its own white point.
238#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
239#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
240#[serde(rename_all = "snake_case")]
241pub enum LinearPrimaries {
242 /// ITU-R BT.709 and sRGB, D65 white.
243 Bt709,
244 /// ITU-R BT.2020, D65 white.
245 Bt2020,
246 /// DCI-P3 primaries with a D65 white, as Display P3.
247 P3D65,
248 /// ACES AP0 (SMPTE ST 2065-1), the ACES white.
249 AcesAp0,
250 /// ACES AP1 (ACEScg), the ACES white.
251 AcesAp1,
252}
253
254/// How an image sequence shows a frame missing from its numbering.
255#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
256#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
257#[serde(rename_all = "snake_case")]
258pub enum MissingFrames {
259 /// A sequence with a missing frame is refused.
260 #[default]
261 Reject,
262 /// The frame before it is shown.
263 Hold,
264 /// Nothing is shown: a transparent frame.
265 Blank,
266}
267
268impl ProviderSource {
269 /// The kind of source the provider's media is.
270 #[must_use]
271 pub const fn kind(&self) -> MediaKind {
272 match self {
273 Self::Svg | Self::Exr { .. } | Self::Latex { .. } | Self::Pdf { .. } => {
274 MediaKind::Image
275 }
276 Self::AnimatedImage | Self::Lottie { .. } | Self::ImageSequence { .. } => {
277 MediaKind::Video
278 }
279 }
280 }
281
282 /// Whether the provider reads a file of the source's own. One that does not, such as LaTeX,
283 /// holds its content in these settings, so its source has no locator or fingerprint.
284 #[must_use]
285 pub const fn reads_file(&self) -> bool {
286 !matches!(self, Self::Latex { .. })
287 }
288
289 /// Whether the settings are coherent and within the limits each variant's fields state.
290 #[must_use]
291 pub fn is_valid(&self) -> bool {
292 match self {
293 Self::Lottie {
294 animation: Some(animation),
295 } => return !animation.is_empty(),
296 Self::Latex {
297 latex,
298 font_size,
299 color,
300 ..
301 } => {
302 return !latex.is_empty()
303 && latex.len() <= MAX_LATEX_BYTES
304 && *font_size > 0.0
305 && *font_size <= MAX_LATEX_FONT_SIZE
306 && color.is_valid();
307 }
308 Self::Pdf { page, background } => {
309 return (1..=MAX_PDF_PAGES).contains(page) && background.is_valid();
310 }
311 _ => {}
312 }
313 let Self::ImageSequence {
314 frames, missing, ..
315 } = self
316 else {
317 return true;
318 };
319 let present = frames.iter().flatten().collect::<Vec<_>>();
320 let unique = present
321 .iter()
322 .collect::<std::collections::HashSet<_>>()
323 .len()
324 == present.len();
325 !frames.is_empty()
326 && frames.len() <= MAX_SEQUENCE_FRAMES
327 && frames[0].is_some()
328 && unique
329 && present.iter().all(|locator| !locator.is_empty())
330 && (present.len() == frames.len() || *missing != MissingFrames::Reject)
331 }
332}