Skip to main content

alpha2_extensions/svg/
mod.rs

1//! Static SVG, rasterized by resvg at the size it is shown.
2//!
3//! Only host-registered resources are read: fonts from the resolver (never system fonts) and
4//! images from `data:` URLs or registered locators. Missing fonts and images are reported.
5//!
6//! usvg and resvg do not bound their own work, so costs are counted first and an over-budget
7//! document is refused: nesting depth ([`markup`], [`MAX_NESTING`]), conversion steps
8//! ([`document`], [`MAX_READING`]), total SVG text including nested images
9//! ([`MAX_SVG_DOCUMENT_BYTES`]), and drawing cost at each render size ([`render_cost`]).
10
11mod document;
12mod markup;
13mod path_data;
14mod render_cost;
15
16use std::io::Read as _;
17use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
18use std::sync::{Arc, Mutex, PoisonError};
19
20use alpha2_time::MediaTime;
21use resvg::tiny_skia::{Pixmap, Transform};
22use resvg::usvg::{
23    self, FontResolver, ImageHrefResolver, ImageKind, Node, Options, Tree, roxmltree,
24};
25
26use alpha2_model::{MAX_SVG_DOCUMENT_BYTES, ProviderSource};
27
28use crate::api::{
29    Diagnostic, ExtensionError, Format, FramePixels, ProbeReport, ResourceResolver, Timing,
30    VisualFrame, VisualProvider, VisualSource,
31};
32use crate::budget::{check_canvas, check_document_size, check_image_pixels};
33
34/// Reads static SVG documents.
35pub struct SvgProvider;
36
37impl VisualProvider for SvgProvider {
38    fn name(&self) -> &'static str {
39        "svg"
40    }
41
42    fn probe(&self, bytes: &[u8]) -> Option<Result<ProbeReport, ExtensionError>> {
43        if !looks_like_svg(bytes) {
44            return None;
45        }
46        Some(
47            check_document_size(&ProviderSource::Svg, bytes, bytes.len() as u64)
48                .and_then(|()| parse(bytes, &crate::api::NoResources))
49                .map(|(_, report)| report),
50        )
51    }
52
53    fn open(
54        &self,
55        bytes: Arc<[u8]>,
56        _source: &ProviderSource,
57        resolver: &dyn ResourceResolver,
58    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
59        if !looks_like_svg(&bytes) {
60            return Err(ExtensionError::Mismatch("not an SVG document".into()));
61        }
62        check_document_size(&ProviderSource::Svg, &bytes, bytes.len() as u64)?;
63        let (tree, report) = parse(&bytes, resolver)?;
64        Ok(Box::new(SvgSource {
65            tree,
66            report,
67            last: None,
68        }))
69    }
70}
71
72/// Whether the bytes are XML with an `svg` root, skipping any BOM, prolog, comments, and doctype
73/// (internal subset included, as Adobe Illustrator writes).
74fn looks_like_svg(bytes: &[u8]) -> bool {
75    let mut rest = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
76    loop {
77        rest = rest.trim_ascii_start();
78        let skipped = if let Some(after) = rest.strip_prefix(b"<?") {
79            after_closing(after, b"?>")
80        } else if let Some(after) = rest.strip_prefix(b"<!--") {
81            after_closing(after, b"-->")
82        } else if let Some(after) = rest.strip_prefix(b"<!DOCTYPE") {
83            after_doctype(after)
84        } else {
85            return rest.strip_prefix(b"<svg").is_some_and(|after| {
86                after
87                    .first()
88                    .is_some_and(|next| next.is_ascii_whitespace() || matches!(next, b'>' | b'/'))
89            });
90        };
91        let Some(after) = skipped else {
92            return false;
93        };
94        rest = after;
95    }
96}
97
98fn after_closing<'a>(bytes: &'a [u8], closing: &[u8]) -> Option<&'a [u8]> {
99    let at = bytes
100        .windows(closing.len())
101        .position(|window| window == closing)?;
102    Some(&bytes[at + closing.len()..])
103}
104
105/// What follows a doctype whose `<!DOCTYPE` precedes `bytes`. Quoted literals, comments, and the
106/// internal subset may contain a `>` that does not end it.
107fn after_doctype(mut bytes: &[u8]) -> Option<&[u8]> {
108    let mut subset = false;
109    loop {
110        if let Some(after) = bytes.strip_prefix(b"<!--") {
111            bytes = after_closing(after, b"-->")?;
112        } else if let Some(after) = bytes.strip_prefix(b"<?") {
113            bytes = after_closing(after, b"?>")?;
114        } else {
115            let (&first, after) = bytes.split_first()?;
116            bytes = match first {
117                b'"' | b'\'' => after_closing(after, &[first])?,
118                b'[' if !subset => {
119                    subset = true;
120                    after
121                }
122                b']' if subset => {
123                    subset = false;
124                    after
125                }
126                b'>' if !subset => return Some(after),
127                _ => after,
128            };
129        }
130    }
131}
132
133/// Deepest element nesting, including nested SVG images and `<use>` copies. At this depth the
134/// recursive parser, usvg, and resvg use well under a quarter of a 1 MiB stack; a native release
135/// build overflows 1 MiB between 600 and 1,000 levels. Real documents nest a few tens deep.
136pub(crate) const MAX_NESTING: usize = 256;
137
138/// Most conversion steps for one SVG and its nested images (style matching, `<use>` checks,
139/// ancestry walks at about 18 ns each). About a second natively.
140pub(crate) const MAX_READING: u64 = 1 << 27;
141
142/// Remaining budget for one document and its nested SVG images, shared with the image resolver.
143struct Reading {
144    /// Unpacked SVG text bytes left.
145    text: AtomicUsize,
146    steps: AtomicU64,
147    /// Levels used by the enclosing documents being converted.
148    nesting: AtomicUsize,
149    /// A nested document's budget error, which refuses the outer document.
150    refused: Mutex<Option<ExtensionError>>,
151}
152
153impl Reading {
154    fn new() -> Self {
155        Self {
156            text: AtomicUsize::new(MAX_SVG_DOCUMENT_BYTES),
157            steps: AtomicU64::new(MAX_READING),
158            nesting: AtomicUsize::new(0),
159            refused: Mutex::new(None),
160        }
161    }
162
163    fn refuse(&self, error: ExtensionError) {
164        self.refused
165            .lock()
166            .unwrap_or_else(PoisonError::into_inner)
167            .get_or_insert(error);
168    }
169
170    fn refusal(&self) -> Option<ExtensionError> {
171        self.refused
172            .lock()
173            .unwrap_or_else(PoisonError::into_inner)
174            .take()
175    }
176
177    fn take_text(&self, length: usize) -> Result<(), ExtensionError> {
178        let left = self.text.load(Ordering::Relaxed);
179        let left = left.checked_sub(length).ok_or_else(too_much_text)?;
180        self.text.store(left, Ordering::Relaxed);
181        Ok(())
182    }
183}
184
185fn too_much_text() -> ExtensionError {
186    ExtensionError::Budget(format!(
187        "the SVG and the SVG images it draws are more than {MAX_SVG_DOCUMENT_BYTES} bytes of text together"
188    ))
189}
190
191/// Parses SVG `text` within the remaining `reading` budget, reserving this document's nesting
192/// for the SVG images it draws.
193fn read_document(
194    text: &[u8],
195    options: &Options,
196    reading: &Reading,
197) -> Result<Tree, ExtensionError> {
198    let malformed = |error: usvg::Error| ExtensionError::Malformed(error.to_string());
199    reading.take_text(text.len())?;
200    let text = std::str::from_utf8(text).map_err(|_| malformed(usvg::Error::NotAnUtf8Str))?;
201    let base = reading.nesting.load(Ordering::Relaxed);
202    let limit = MAX_NESTING.saturating_sub(base);
203    markup::nesting(text, limit)?;
204    let xml = roxmltree::Document::parse_with_options(
205        text,
206        roxmltree::ParsingOptions {
207            allow_dtd: true,
208            ..roxmltree::ParsingOptions::default()
209        },
210    )
211    .map_err(|error| malformed(usvg::Error::ParsingFailed(error)))?;
212    let steps = reading.steps.load(Ordering::Relaxed);
213    let conversion = document::conversion(&xml, steps, limit)?;
214    reading
215        .steps
216        .store(steps - conversion.steps, Ordering::Relaxed);
217    reading
218        .nesting
219        .store(base + conversion.depth, Ordering::Relaxed);
220    let tree = Tree::from_xmltree(&xml, options);
221    reading.nesting.store(base, Ordering::Relaxed);
222    tree.map_err(malformed)
223}
224
225/// Parses a document with only `resolver`'s resources, checks its budgets at its own size, and
226/// reports what it could not draw.
227fn parse(
228    bytes: &[u8],
229    resolver: &dyn ResourceResolver,
230) -> Result<(Tree, ProbeReport), ExtensionError> {
231    let registered_fonts = resolver.fonts();
232    let missing_fonts = Mutex::new(Vec::<String>::new());
233    let image_reports = Mutex::new(Vec::<Diagnostic>::new());
234    let reading = Reading::new();
235    let options = Options {
236        // Filled on the first font request, so documents without text load no fonts.
237        fontdb: Arc::new(usvg::fontdb::Database::new()),
238        font_resolver: font_resolver(&registered_fonts, &missing_fonts),
239        image_href_resolver: image_resolver(resolver, &image_reports, &reading),
240        ..Options::default()
241    };
242    let tree = read_document(bytes, &options, &reading);
243    drop(options);
244    if let Some(refusal) = reading.refusal() {
245        return Err(refusal);
246    }
247    let tree = tree?;
248    let size = tree.size().to_int_size();
249    check_canvas(size.width(), size.height())?;
250    check_image_pixels(image_pixels(tree.root()))?;
251    render_cost::check(&tree, size.width(), size.height())?;
252    let mut diagnostics = Vec::new();
253    let missing_fonts = missing_fonts
254        .into_inner()
255        .unwrap_or_else(PoisonError::into_inner);
256    if !missing_fonts.is_empty() {
257        diagnostics.push(Diagnostic::MissingFont {
258            families: missing_fonts.join(", "),
259        });
260    }
261    for diagnostic in image_reports
262        .into_inner()
263        .unwrap_or_else(PoisonError::into_inner)
264    {
265        if !diagnostics.contains(&diagnostic) {
266            diagnostics.push(diagnostic);
267        }
268    }
269    let report = ProbeReport {
270        format: Format::Svg,
271        width: size.width(),
272        height: size.height(),
273        timing: Timing::Static,
274        loop_count: None,
275        items: Vec::new(),
276        item: None,
277        color: None,
278        diagnostics,
279    };
280    Ok((tree, report))
281}
282
283/// Selects fonts from `registered`, loading them on the first request, and records unmatched
284/// families in `missing`. usvg asks only for text it actually draws.
285fn font_resolver<'a>(
286    registered: &'a [Arc<[u8]>],
287    missing: &'a Mutex<Vec<String>>,
288) -> FontResolver<'a> {
289    let select_font = FontResolver::default_font_selector();
290    FontResolver {
291        select_font: Box::new(move |font, fontdb| {
292            if fontdb.is_empty() {
293                let fontdb = Arc::make_mut(fontdb);
294                for font in registered {
295                    // Shared, not copied; the source keeps its fonts as long as its tree.
296                    fontdb
297                        .load_font_source(usvg::fontdb::Source::Binary(Arc::new(Arc::clone(font))));
298                }
299            }
300            let found = select_font(font, fontdb);
301            if found.is_none() {
302                let mut missing = missing.lock().unwrap_or_else(PoisonError::into_inner);
303                for family in font.families() {
304                    let family = match family {
305                        usvg::FontFamily::Named(name) => name.clone(),
306                        generic => generic.to_string(),
307                    };
308                    if !missing.contains(&family) {
309                        missing.push(family);
310                    }
311                }
312            }
313            found
314        }),
315        select_fallback: FontResolver::default_fallback_selector(),
316    }
317}
318
319/// Resolves `data:` images and registered hrefs, recording what is not drawn in `reports`.
320/// Nested SVG images share the outer document's `reading` budget.
321fn image_resolver<'a>(
322    resolver: &'a dyn ResourceResolver,
323    reports: &'a Mutex<Vec<Diagnostic>>,
324    reading: &'a Reading,
325) -> ImageHrefResolver<'a> {
326    let default_data = ImageHrefResolver::default_data_resolver();
327    let report = move |diagnostic| {
328        reports
329            .lock()
330            .unwrap_or_else(PoisonError::into_inner)
331            .push(diagnostic);
332    };
333    ImageHrefResolver {
334        // Nested SVG documents resolve their `data:` images through this too.
335        resolve_data: Box::new(move |mime, data, options| {
336            // Matches usvg's own resolver: SVG type, or plain text that is not a raster image.
337            let svg = mime == "image/svg+xml"
338                || (mime == "text/plain" && imagesize::image_type(&data).is_err());
339            if svg {
340                return nested_svg(&data, options, reading);
341            }
342            let kind = default_data(mime, data, options)?;
343            within_canvas(kind, || format!("data:{mime}"), reports)
344        }),
345        resolve_string: Box::new(move |href, options| {
346            let unreadable = |reason: &str| {
347                report(Diagnostic::UnreadableImage {
348                    href: href.to_owned(),
349                    reason: reason.to_owned(),
350                });
351                None
352            };
353            let Ok(bytes) = resolver.bytes(href) else {
354                report(Diagnostic::MissingImage {
355                    href: href.to_owned(),
356                });
357                return None;
358            };
359            let data = || Arc::new(bytes.to_vec());
360            let raster = match registered_image(&bytes) {
361                Some(Registered::Png) => ImageKind::PNG(data()),
362                Some(Registered::Jpeg) => ImageKind::JPEG(data()),
363                Some(Registered::Gif) => ImageKind::GIF(data()),
364                Some(Registered::Webp) => ImageKind::WEBP(data()),
365                // Like a `data:` SVG, its external images are not loaded (SVG-as-image rules).
366                Some(Registered::Svg) => {
367                    return nested_svg(&bytes, options, reading)
368                        .or_else(|| unreadable("the SVG document does not parse"));
369                }
370                None => return unreadable("not a PNG, JPEG, GIF, WebP, or SVG image"),
371            };
372            within_canvas(raster, || href.to_owned(), reports)
373        }),
374    }
375}
376
377/// Reads a plain or gzipped SVG image within `reading`. Over budget refuses the outer document;
378/// a parse failure just leaves the image out.
379fn nested_svg(data: &[u8], options: &Options, reading: &Reading) -> Option<ImageKind> {
380    let unpacked;
381    let text = if data.starts_with(&[0x1f, 0x8b]) {
382        // Unpacked only as far as there is text left to read.
383        let left = reading.text.load(Ordering::Relaxed);
384        let mut text = Vec::new();
385        let read = flate2::read::GzDecoder::new(data)
386            .take(u64::try_from(left).unwrap_or(u64::MAX).saturating_add(1))
387            .read_to_end(&mut text);
388        if read.is_err() {
389            return None;
390        }
391        if text.len() > left {
392            reading.refuse(too_much_text());
393            return None;
394        }
395        unpacked = text;
396        &unpacked[..]
397    } else {
398        data
399    };
400    let nested = Options {
401        resources_dir: None,
402        dpi: options.dpi,
403        font_size: options.font_size,
404        languages: options.languages.clone(),
405        shape_rendering: options.shape_rendering,
406        text_rendering: options.text_rendering,
407        image_rendering: options.image_rendering,
408        default_size: options.default_size,
409        image_href_resolver: ImageHrefResolver {
410            resolve_data: Box::new(|mime, data, nested| {
411                (options.image_href_resolver.resolve_data)(mime, data, nested)
412            }),
413            resolve_string: Box::new(|_, _| None),
414        },
415        fontdb: options.fontdb.clone(),
416        font_resolver: FontResolver {
417            select_font: Box::new(|font, fontdb| (options.font_resolver.select_font)(font, fontdb)),
418            select_fallback: Box::new(|c, used, fontdb| {
419                (options.font_resolver.select_fallback)(c, used, fontdb)
420            }),
421        },
422        ..Options::default()
423    };
424    match read_document(text, &nested, reading) {
425        Ok(tree) => Some(ImageKind::SVG(tree)),
426        Err(error @ ExtensionError::Budget(_)) => {
427            reading.refuse(error);
428            None
429        }
430        Err(_) => None,
431    }
432}
433
434/// Drops and reports as missing a raster image whose declared size exceeds the canvas limit,
435/// since resvg would decode it at that size on every render.
436fn within_canvas(
437    kind: ImageKind,
438    href: impl FnOnce() -> String,
439    reports: &Mutex<Vec<Diagnostic>>,
440) -> Option<ImageKind> {
441    let (ImageKind::JPEG(data)
442    | ImageKind::PNG(data)
443    | ImageKind::GIF(data)
444    | ImageKind::WEBP(data)) = &kind
445    else {
446        return Some(kind);
447    };
448    // A header usvg cannot size is left out by usvg itself.
449    let declared = imagesize::blob_size(data).ok()?;
450    let side = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
451    if check_canvas(side(declared.width), side(declared.height)).is_err() {
452        reports
453            .lock()
454            .unwrap_or_else(PoisonError::into_inner)
455            .push(Diagnostic::MissingImage { href: href() });
456        return None;
457    }
458    Some(kind)
459}
460
461/// Decoded raster pixels `group` draws, counted per draw since resvg decodes on every draw.
462fn image_pixels(group: &usvg::Group) -> u64 {
463    let mut pixels = 0_u64;
464    for node in group.children() {
465        match node {
466            Node::Group(inner) => pixels = pixels.saturating_add(image_pixels(inner)),
467            Node::Image(image) => pixels = pixels.saturating_add(raster_pixels(image.kind())),
468            Node::Path(_) | Node::Text(_) => {}
469        }
470        // Clip paths, masks, filter images, patterns, and a nested SVG's own tree.
471        node.subroots(|root| pixels = pixels.saturating_add(image_pixels(root)));
472    }
473    pixels
474}
475
476/// Declared raster pixels; zero for a nested SVG, whose images are counted where drawn.
477fn raster_pixels(kind: &ImageKind) -> u64 {
478    match kind {
479        ImageKind::JPEG(data)
480        | ImageKind::PNG(data)
481        | ImageKind::GIF(data)
482        | ImageKind::WEBP(data) => imagesize::blob_size(data).map_or(0, |size| {
483            u64::try_from(size.width)
484                .unwrap_or(u64::MAX)
485                .saturating_mul(u64::try_from(size.height).unwrap_or(u64::MAX))
486        }),
487        ImageKind::SVG(_) => 0,
488    }
489}
490
491enum Registered {
492    Png,
493    Jpeg,
494    Gif,
495    Webp,
496    /// Plain or gzipped.
497    Svg,
498}
499
500fn registered_image(bytes: &[u8]) -> Option<Registered> {
501    if bytes.starts_with(b"\x89PNG") {
502        Some(Registered::Png)
503    } else if bytes.starts_with(&[0xff, 0xd8]) {
504        Some(Registered::Jpeg)
505    } else if bytes.starts_with(b"GIF8") {
506        Some(Registered::Gif)
507    } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
508        Some(Registered::Webp)
509    } else if looks_like_svg(bytes) || bytes.starts_with(&[0x1f, 0x8b]) {
510        Some(Registered::Svg)
511    } else {
512        None
513    }
514}
515
516struct SvgSource {
517    tree: Tree,
518    report: ProbeReport,
519    /// The last rasterization, reused while the size holds.
520    last: Option<VisualFrame>,
521}
522
523impl VisualSource for SvgSource {
524    fn report(&self) -> &ProbeReport {
525        &self.report
526    }
527
528    fn render(&mut self, _time: MediaTime, fit: (u32, u32)) -> Result<VisualFrame, ExtensionError> {
529        let size = self.tree.size();
530        let (width, height) = fitted(size.width(), size.height(), fit);
531        if let Some(last) = self
532            .last
533            .as_ref()
534            .filter(|last| (last.width, last.height) == (width, height))
535        {
536            return Ok(last.clone());
537        }
538        render_cost::check(&self.tree, width, height)?;
539        let mut pixmap = Pixmap::new(width, height).ok_or_else(|| {
540            ExtensionError::Budget(format!("cannot rasterize at {width}x{height}"))
541        })?;
542        // Sizes are within MAX_CANVAS_SIDE, which f32 holds exactly.
543        #[allow(clippy::cast_precision_loss)]
544        let transform =
545            Transform::from_scale(width as f32 / size.width(), height as f32 / size.height());
546        resvg::render(&self.tree, transform, &mut pixmap.as_mut());
547        let frame = VisualFrame {
548            width,
549            height,
550            pixels: FramePixels::Rgba8(pixmap.take().into()),
551            index: 0,
552            start: MediaTime::from_ticks(i64::MIN),
553            end: None,
554            diagnostics: Vec::new(),
555        };
556        self.last = Some(frame.clone());
557        Ok(frame)
558    }
559
560    fn resident_bytes(&self) -> usize {
561        self.last.as_ref().map_or(0, |last| last.pixels.byte_len())
562    }
563}
564
565/// The largest whole-pixel size that fits in `fit` keeping aspect; the own size if `fit` is empty.
566// Every size is positive and within MAX_CANVAS_SIDE, which f32 holds exactly.
567#[allow(
568    clippy::cast_precision_loss,
569    clippy::cast_possible_truncation,
570    clippy::cast_sign_loss
571)]
572fn fitted(width: f32, height: f32, fit: (u32, u32)) -> (u32, u32) {
573    if fit.0 == 0 || fit.1 == 0 {
574        return (
575            width.round().max(1.0) as u32,
576            height.round().max(1.0) as u32,
577        );
578    }
579    let scale = (fit.0 as f32 / width).min(fit.1 as f32 / height);
580    (
581        (width * scale).round().clamp(1.0, fit.0 as f32) as u32,
582        (height * scale).round().clamp(1.0, fit.1 as f32) as u32,
583    )
584}