alpha2_extensions/budget.rs
1//! Limits every provider checks before it reads, decodes, or draws a source. A source past one
2//! is refused with [`ExtensionError::Budget`], natively and in the browser alike.
3//!
4//! The limits cover document size ([`document_limit`]), canvas size ([`check_canvas`]), decoded
5//! pixels ([`MAX_ANIMATION_PIXELS`], [`MAX_SOURCE_IMAGE_PIXELS`], [`DEFAULT_FRAME_BUDGET`]) and
6//! drawing cost ([`MAX_DRAWING`]). Format-specific counts (SVG elements, Lottie draws, dotLottie
7//! files) live next to each parser.
8
9use alpha2_model::{
10 MAX_LOTTIE_DOCUMENT_BYTES, MAX_PDF_DOCUMENT_BYTES, MAX_PROVIDER_DOCUMENT_BYTES,
11 MAX_SVG_DOCUMENT_BYTES, ProviderSource,
12};
13
14use crate::api::ExtensionError;
15
16/// Largest canvas side a provider opens, in pixels.
17pub const MAX_CANVAS_SIDE: u32 = 16_384;
18/// Largest canvas a provider opens, in pixels (8K UHD).
19pub const MAX_CANVAS_PIXELS: u64 = 7_680 * 4_320;
20/// Most frames an animated image may have.
21pub const MAX_ANIMATION_FRAMES: usize = 10_000;
22/// Most pixels all of an animated image's frames may cover together. About a thousand 1080p
23/// frames, roughly ten seconds of native decoding.
24pub const MAX_ANIMATION_PIXELS: u64 = 1 << 31;
25/// Decoded bytes an animated source or an image sequence keeps between requests.
26pub const DEFAULT_FRAME_BUDGET: usize = 256 * 1024 * 1024;
27/// Most pixels the raster images inside one source may decode to together. An SVG counts every
28/// image draw per render (an image reused through `<use>` counts twice); Lottie counts its assets
29/// once at open.
30pub const MAX_SOURCE_IMAGE_PIXELS: u64 = 4 * MAX_CANVAS_PIXELS;
31/// Most encoded raster bytes the images of one SVG source may hold, counting each copy usvg
32/// makes; shared bytes count once.
33#[cfg(feature = "svg")]
34pub(crate) const MAX_SOURCE_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
35
36/// Most canvases of blended fill one SVG render or Lottie frame may draw. A 1080p canvas of
37/// blended fill costs about 4 to 10 ms natively, so this is about 2 s. Opaque fills are not
38/// discounted, since whether something above fades is unknown before drawing.
39#[cfg(any(feature = "svg", feature = "lottie"))]
40pub(crate) const MAX_DRAWING: f64 = 256.0;
41
42/// Blended-fill pixels one pair of edges active in one device row costs tiny-skia's scan
43/// conversion, which inserts and sorts a row's edges: 0.26 ns natively against 2.07 ns a pixel.
44#[cfg(any(feature = "svg", feature = "lottie"))]
45const FILL_PAIR: f64 = 0.13;
46
47/// Blended-fill pixels one edge that is not horizontal costs to build and walk: 0.6 us natively
48/// in small shapes, 2 us in one long outline of tiny segments.
49#[cfg(any(feature = "svg", feature = "lottie"))]
50const FILL_SEGMENT: f64 = 400.0;
51
52/// Blended-fill pixels one dash costs: tiny-skia dashes the whole path before clipping (about
53/// 0.22 us a dash natively).
54#[cfg(any(feature = "svg", feature = "lottie"))]
55const DASH: f64 = 107.0;
56
57/// Most dashes tiny-skia makes of one path.
58#[cfg(any(feature = "svg", feature = "lottie"))]
59pub(crate) const MAX_DASHES: f64 = 1_000_000.0;
60
61/// What filling `segments` segments costs, in blended-fill pixels, where `row_pairs` is the sum
62/// over device rows of the square of the edges active in that row. A path whose rows are unknown
63/// counts all its edges in one row.
64#[cfg(any(feature = "svg", feature = "lottie"))]
65pub(crate) fn fill_geometry(row_pairs: f64, segments: f64) -> f64 {
66 row_pairs * FILL_PAIR + segments * FILL_SEGMENT
67}
68
69/// What making `dashes` dashes costs, in blended-fill pixels.
70#[cfg(any(feature = "svg", feature = "lottie"))]
71pub(crate) fn dash_geometry(dashes: f64) -> f64 {
72 dashes.min(MAX_DASHES) * DASH
73}
74
75/// Minimum canvas an SVG counts as for [`MAX_DRAWING`], since a small icon can still draw many
76/// blurs. Lottie uses its own canvas for area because all its layers are frame-sized, and this
77/// one for geometry, whose cost does not shrink with the canvas.
78#[cfg(any(feature = "svg", feature = "lottie"))]
79pub(crate) const FLOOR_CANVAS: f64 = 1920.0 * 1080.0;
80
81/// Most intermediate pixels (layers, masks, tiles, filter results) held at once: 1 GiB of RGBA8.
82#[cfg(any(feature = "svg", feature = "lottie"))]
83pub(crate) const MAX_HELD_PIXELS: f64 = 268_435_456.0;
84
85/// Refuses a canvas larger than a provider opens.
86///
87/// # Errors
88/// [`ExtensionError::Budget`] or, for an empty canvas,
89/// [`ExtensionError::Malformed`].
90pub fn check_canvas(width: u32, height: u32) -> Result<(), ExtensionError> {
91 if width == 0 || height == 0 {
92 return Err(ExtensionError::Malformed("the canvas is empty".into()));
93 }
94 if width > MAX_CANVAS_SIDE
95 || height > MAX_CANVAS_SIDE
96 || u64::from(width) * u64::from(height) > MAX_CANVAS_PIXELS
97 {
98 return Err(ExtensionError::Budget(format!(
99 "a {width}x{height} canvas is larger than {MAX_CANVAS_PIXELS} pixels"
100 )));
101 }
102 Ok(())
103}
104
105/// The most bytes a provider reads of a whole-file format (SVG, Lottie, dotLottie, PDF), with a
106/// name for the file kind; `None` for streamed formats. `head` is the file's start, used to tell
107/// a dotLottie ZIP from Lottie JSON.
108#[must_use]
109pub fn document_limit(source: &ProviderSource, head: &[u8]) -> Option<(usize, &'static str)> {
110 match source {
111 ProviderSource::Svg => Some((MAX_SVG_DOCUMENT_BYTES, "SVG document")),
112 ProviderSource::Lottie { .. } if head.starts_with(b"PK\x03\x04") => {
113 Some((MAX_PROVIDER_DOCUMENT_BYTES, "dotLottie package"))
114 }
115 ProviderSource::Lottie { .. } => Some((MAX_LOTTIE_DOCUMENT_BYTES, "Lottie file")),
116 ProviderSource::Pdf { .. } => Some((MAX_PDF_DOCUMENT_BYTES, "PDF document")),
117 _ => None,
118 }
119}
120
121/// Refuses a source file of `length` bytes larger than its [`document_limit`].
122///
123/// # Errors
124/// [`ExtensionError::Budget`].
125pub fn check_document_size(
126 source: &ProviderSource,
127 head: &[u8],
128 length: u64,
129) -> Result<(), ExtensionError> {
130 match document_limit(source, head) {
131 Some((limit, what)) if length > limit as u64 => Err(ExtensionError::Budget(format!(
132 "the {what} is {length} bytes, more than the {limit} a provider reads"
133 ))),
134 _ => Ok(()),
135 }
136}
137
138/// Refuses images that together decode to more than [`MAX_SOURCE_IMAGE_PIXELS`].
139///
140/// # Errors
141/// [`ExtensionError::Budget`].
142pub fn check_image_pixels(pixels: u64) -> Result<(), ExtensionError> {
143 if pixels > MAX_SOURCE_IMAGE_PIXELS {
144 return Err(ExtensionError::Budget(format!(
145 "its images decode to {pixels} pixels, more than the {MAX_SOURCE_IMAGE_PIXELS} one source may"
146 )));
147 }
148 Ok(())
149}