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
16#[cfg(test)]
17pub(crate) use document::REFERENCE_LEVELS;
18
19use std::collections::{HashMap, HashSet};
20use std::io::Read as _;
21use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
22use std::sync::{Arc, Mutex, PoisonError};
23
24use alpha2_time::MediaTime;
25use resvg::tiny_skia::{Pixmap, Transform};
26use resvg::usvg::{
27    self, FontResolver, ImageHrefResolver, ImageKind, Node, Options, Tree, roxmltree,
28};
29
30#[cfg(feature = "pdf")]
31use alpha2_model::Rgba;
32use alpha2_model::{MAX_SVG_DOCUMENT_BYTES, ProviderSource};
33
34use crate::api::{
35    Diagnostic, ExtensionError, Format, FramePixels, ProbeReport, ResourceResolver, Timing,
36    VisualFrame, VisualProvider, VisualSource,
37};
38use crate::budget::{
39    MAX_SOURCE_IMAGE_BYTES, MAX_SOURCE_IMAGE_PIXELS, check_canvas, check_document_size,
40    check_image_pixels,
41};
42
43/// Reads static SVG documents.
44pub struct SvgProvider;
45
46impl VisualProvider for SvgProvider {
47    fn name(&self) -> &'static str {
48        "svg"
49    }
50
51    fn probe(&self, bytes: &[u8]) -> Option<Result<ProbeReport, ExtensionError>> {
52        if !looks_like_svg(bytes) {
53            return None;
54        }
55        Some(
56            check_document_size(&ProviderSource::Svg, bytes, bytes.len() as u64)
57                .and_then(|()| {
58                    parse(
59                        bytes,
60                        &crate::api::NoResources,
61                        MAX_SVG_DOCUMENT_BYTES,
62                        MAX_SOURCE_IMAGE_BYTES,
63                    )
64                })
65                .map(|(_, report)| report),
66        )
67    }
68
69    fn open(
70        &self,
71        bytes: Arc<[u8]>,
72        _source: &ProviderSource,
73        resolver: &dyn ResourceResolver,
74    ) -> Result<Box<dyn VisualSource>, ExtensionError> {
75        if !looks_like_svg(&bytes) {
76            return Err(ExtensionError::Mismatch("not an SVG document".into()));
77        }
78        check_document_size(&ProviderSource::Svg, &bytes, bytes.len() as u64)?;
79        Ok(Box::new(open_document(&bytes, resolver)?))
80    }
81}
82
83/// Opens SVG text another provider generated, with every SVG budget except the document size
84/// check, which is the caller's.
85///
86/// # Errors
87/// [`ExtensionError::Malformed`] or [`ExtensionError::Budget`].
88pub(crate) fn open_document(
89    bytes: &[u8],
90    resolver: &dyn ResourceResolver,
91) -> Result<SvgSource, ExtensionError> {
92    open_document_within(
93        bytes,
94        resolver,
95        MAX_SVG_DOCUMENT_BYTES,
96        MAX_SOURCE_IMAGE_BYTES,
97    )
98}
99
100/// [`open_document`] reading at most `text` bytes of SVG text and holding at most `images` bytes
101/// of raster images, for a provider that bounds its documents' markup and embedded images itself.
102///
103/// # Errors
104/// [`ExtensionError::Malformed`] or [`ExtensionError::Budget`].
105pub(crate) fn open_document_within(
106    bytes: &[u8],
107    resolver: &dyn ResourceResolver,
108    text: usize,
109    images: u64,
110) -> Result<SvgSource, ExtensionError> {
111    let (tree, report) = parse(bytes, resolver, text, images)?;
112    let size = tree.size();
113    let images = held_image_bytes(tree.root(), &mut HashSet::new());
114    Ok(SvgSource {
115        view: (0.0, 0.0, size.width(), size.height()),
116        scale: 1.0,
117        tree,
118        report,
119        background: None,
120        opacity: u8::MAX,
121        images,
122        last: None,
123    })
124}
125
126/// Whether the bytes are XML with an `svg` root, skipping any BOM, prolog, comments, and doctype
127/// (internal subset included, as Adobe Illustrator writes).
128fn looks_like_svg(bytes: &[u8]) -> bool {
129    let mut rest = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
130    loop {
131        rest = rest.trim_ascii_start();
132        let skipped = if let Some(after) = rest.strip_prefix(b"<?") {
133            after_closing(after, b"?>")
134        } else if let Some(after) = rest.strip_prefix(b"<!--") {
135            after_closing(after, b"-->")
136        } else if let Some(after) = rest.strip_prefix(b"<!DOCTYPE") {
137            after_doctype(after)
138        } else {
139            return rest.strip_prefix(b"<svg").is_some_and(|after| {
140                after
141                    .first()
142                    .is_some_and(|next| next.is_ascii_whitespace() || matches!(next, b'>' | b'/'))
143            });
144        };
145        let Some(after) = skipped else {
146            return false;
147        };
148        rest = after;
149    }
150}
151
152fn after_closing<'a>(bytes: &'a [u8], closing: &[u8]) -> Option<&'a [u8]> {
153    let at = bytes
154        .windows(closing.len())
155        .position(|window| window == closing)?;
156    Some(&bytes[at + closing.len()..])
157}
158
159/// What follows a doctype whose `<!DOCTYPE` precedes `bytes`. Quoted literals, comments, and the
160/// internal subset may contain a `>` that does not end it.
161fn after_doctype(mut bytes: &[u8]) -> Option<&[u8]> {
162    let mut subset = false;
163    loop {
164        if let Some(after) = bytes.strip_prefix(b"<!--") {
165            bytes = after_closing(after, b"-->")?;
166        } else if let Some(after) = bytes.strip_prefix(b"<?") {
167            bytes = after_closing(after, b"?>")?;
168        } else {
169            let (&first, after) = bytes.split_first()?;
170            bytes = match first {
171                b'"' | b'\'' => after_closing(after, &[first])?,
172                b'[' if !subset => {
173                    subset = true;
174                    after
175                }
176                b']' if subset => {
177                    subset = false;
178                    after
179                }
180                b'>' if !subset => return Some(after),
181                _ => after,
182            };
183        }
184    }
185}
186
187/// Deepest element nesting, including nested SVG images and `<use>` copies. At this depth the
188/// recursive parser, usvg, and resvg use well under a quarter of a 1 MiB stack; a native release
189/// build overflows 1 MiB between 600 and 1,000 levels. Real documents nest a few tens deep.
190pub(crate) const MAX_NESTING: usize = 256;
191
192/// Most conversion steps for one SVG and its nested images (style matching, `<use>` checks,
193/// ancestry walks at about 18 ns each). About a second natively.
194pub(crate) const MAX_READING: u64 = 1 << 27;
195
196/// Most XML nodes one SVG parses to, entities expanded. Text runs, comments, and processing
197/// instructions are nodes too, so this is four per element of [`document::MAX_ELEMENTS`].
198#[allow(clippy::cast_possible_truncation)]
199const MAX_NODES: u32 = 4 * document::MAX_ELEMENTS as u32;
200
201/// Remaining budget for one document and its nested SVG images, shared with the image resolver.
202struct Reading {
203    /// Unpacked SVG text bytes allowed in all.
204    limit: usize,
205    /// Unpacked SVG text bytes left.
206    text: AtomicUsize,
207    steps: AtomicU64,
208    /// Levels used by the enclosing documents being converted.
209    nesting: AtomicUsize,
210    /// Raster image bytes allowed in all.
211    image_limit: u64,
212    /// Raster image bytes left.
213    image_bytes: AtomicU64,
214    /// Declared raster image pixels left, counted per image element.
215    image_pixels: AtomicU64,
216    /// A nested document's budget error, which refuses the outer document.
217    refused: Mutex<Option<ExtensionError>>,
218}
219
220impl Reading {
221    fn new(text: usize, images: u64) -> Self {
222        Self {
223            limit: text,
224            text: AtomicUsize::new(text),
225            steps: AtomicU64::new(MAX_READING),
226            nesting: AtomicUsize::new(0),
227            image_limit: images,
228            image_bytes: AtomicU64::new(images),
229            image_pixels: AtomicU64::new(MAX_SOURCE_IMAGE_PIXELS),
230            refused: Mutex::new(None),
231        }
232    }
233
234    /// Charges a raster image the tree will hold: `bytes` it adds and the pixels it declares.
235    /// Past either budget the whole document is refused.
236    fn take_image(&self, bytes: usize, pixels: u64) -> bool {
237        let take = |left: &AtomicU64, amount: u64| {
238            let now = left.load(Ordering::Relaxed);
239            let after = now.checked_sub(amount);
240            left.store(after.unwrap_or(0), Ordering::Relaxed);
241            after.is_some()
242        };
243        if !take(&self.image_bytes, u64::try_from(bytes).unwrap_or(u64::MAX)) {
244            self.refuse(ExtensionError::Budget(format!(
245                "its raster images are more than {} bytes, each copy counted",
246                self.image_limit
247            )));
248            return false;
249        }
250        if !take(&self.image_pixels, pixels) {
251            self.refuse(ExtensionError::Budget(format!(
252                "its images decode to more than the {MAX_SOURCE_IMAGE_PIXELS} pixels one source \
253                 may, each copy counted"
254            )));
255            return false;
256        }
257        true
258    }
259
260    fn refuse(&self, error: ExtensionError) {
261        self.refused
262            .lock()
263            .unwrap_or_else(PoisonError::into_inner)
264            .get_or_insert(error);
265    }
266
267    fn is_refused(&self) -> bool {
268        self.refused
269            .lock()
270            .unwrap_or_else(PoisonError::into_inner)
271            .is_some()
272    }
273
274    fn refusal(&self) -> Option<ExtensionError> {
275        self.refused
276            .lock()
277            .unwrap_or_else(PoisonError::into_inner)
278            .take()
279    }
280
281    fn take_text(&self, length: usize) -> Result<(), ExtensionError> {
282        let left = self.text.load(Ordering::Relaxed);
283        let left = left
284            .checked_sub(length)
285            .ok_or_else(|| too_much_text(self.limit))?;
286        self.text.store(left, Ordering::Relaxed);
287        Ok(())
288    }
289}
290
291fn too_much_text(limit: usize) -> ExtensionError {
292    ExtensionError::Budget(format!(
293        "the SVG and the SVG images it draws are more than {limit} bytes of text together, \
294         entities expanded"
295    ))
296}
297
298/// Parses SVG `text` within the remaining `reading` budget, reserving this document's nesting
299/// for the SVG images it draws.
300fn read_document(
301    text: &[u8],
302    options: &Options,
303    reading: &Reading,
304) -> Result<Tree, ExtensionError> {
305    let malformed = |error: usvg::Error| ExtensionError::Malformed(error.to_string());
306    reading.take_text(text.len())?;
307    let text = std::str::from_utf8(text).map_err(|_| malformed(usvg::Error::NotAnUtf8Str))?;
308    let base = reading.nesting.load(Ordering::Relaxed);
309    let limit = MAX_NESTING.saturating_sub(base);
310    // The parser copies or reads every byte an entity reference expands to.
311    reading.take_text(markup::entity_expansion(text, limit)?)?;
312    let xml = roxmltree::Document::parse_with_options(
313        text,
314        roxmltree::ParsingOptions {
315            allow_dtd: true,
316            nodes_limit: MAX_NODES,
317            ..roxmltree::ParsingOptions::default()
318        },
319    )
320    .map_err(|error| match error {
321        roxmltree::Error::NodesLimitReached => {
322            ExtensionError::Budget(format!("the SVG parses to more than {MAX_NODES} nodes"))
323        }
324        error => malformed(usvg::Error::ParsingFailed(error)),
325    })?;
326    let steps = reading.steps.load(Ordering::Relaxed);
327    let conversion = document::conversion(&xml, steps, limit)?;
328    reading
329        .steps
330        .store(steps - conversion.steps, Ordering::Relaxed);
331    reading
332        .nesting
333        .store(base + conversion.depth, Ordering::Relaxed);
334    let tree = Tree::from_xmltree(&xml, options);
335    reading.nesting.store(base, Ordering::Relaxed);
336    tree.map_err(malformed)
337}
338
339/// Parses a document with only `resolver`'s resources, at most `text` bytes of SVG text and
340/// `images` bytes of raster images, checks its budgets at its own size, and reports what it
341/// could not draw.
342fn parse(
343    bytes: &[u8],
344    resolver: &dyn ResourceResolver,
345    text: usize,
346    images: u64,
347) -> Result<(Tree, ProbeReport), ExtensionError> {
348    let registered_fonts = resolver.fonts();
349    let missing_fonts = Mutex::new(Vec::<String>::new());
350    let image_reports = Mutex::new(Vec::<Diagnostic>::new());
351    let reading = Reading::new(text, images);
352    let options = Options {
353        // Filled on the first font request, so documents without text load no fonts.
354        fontdb: Arc::new(usvg::fontdb::Database::new()),
355        font_resolver: font_resolver(&registered_fonts, &missing_fonts),
356        image_href_resolver: image_resolver(resolver, &image_reports, &reading),
357        ..Options::default()
358    };
359    let tree = read_document(bytes, &options, &reading);
360    drop(options);
361    if let Some(refusal) = reading.refusal() {
362        return Err(refusal);
363    }
364    let tree = tree?;
365    let size = tree.size().to_int_size();
366    check_canvas(size.width(), size.height())?;
367    check_image_pixels(image_pixels(tree.root()))?;
368    render_cost::check(&tree, Transform::default(), size.width(), size.height())?;
369    let mut diagnostics = Vec::new();
370    let missing_fonts = missing_fonts
371        .into_inner()
372        .unwrap_or_else(PoisonError::into_inner);
373    if !missing_fonts.is_empty() {
374        diagnostics.push(Diagnostic::MissingFont {
375            families: missing_fonts.join(", "),
376        });
377    }
378    for diagnostic in image_reports
379        .into_inner()
380        .unwrap_or_else(PoisonError::into_inner)
381    {
382        if !diagnostics.contains(&diagnostic) {
383            diagnostics.push(diagnostic);
384        }
385    }
386    let report = ProbeReport {
387        format: Format::Svg,
388        width: size.width(),
389        height: size.height(),
390        timing: Timing::Static,
391        loop_count: None,
392        items: Vec::new(),
393        item: None,
394        color: None,
395        diagnostics,
396    };
397    Ok((tree, report))
398}
399
400/// Selects fonts from `registered`, loading them on the first request, and records unmatched
401/// families in `missing`. usvg asks only for text it actually draws.
402fn font_resolver<'a>(
403    registered: &'a [Arc<[u8]>],
404    missing: &'a Mutex<Vec<String>>,
405) -> FontResolver<'a> {
406    let select_font = FontResolver::default_font_selector();
407    FontResolver {
408        select_font: Box::new(move |font, fontdb| {
409            if fontdb.is_empty() {
410                let fontdb = Arc::make_mut(fontdb);
411                for font in registered {
412                    // Shared, not copied; the source keeps its fonts as long as its tree.
413                    fontdb
414                        .load_font_source(usvg::fontdb::Source::Binary(Arc::new(Arc::clone(font))));
415                }
416            }
417            let found = select_font(font, fontdb);
418            if found.is_none() {
419                let mut missing = missing.lock().unwrap_or_else(PoisonError::into_inner);
420                for family in font.families() {
421                    let family = match family {
422                        usvg::FontFamily::Named(name) => name.clone(),
423                        generic => generic.to_string(),
424                    };
425                    if !missing.contains(&family) {
426                        missing.push(family);
427                    }
428                }
429            }
430            found
431        }),
432        select_fallback: FontResolver::default_fallback_selector(),
433    }
434}
435
436/// Resolves `data:` images and registered hrefs, recording what is not drawn in `reports`.
437/// Nested SVG images share the outer document's `reading` budget.
438fn image_resolver<'a>(
439    resolver: &'a dyn ResourceResolver,
440    reports: &'a Mutex<Vec<Diagnostic>>,
441    reading: &'a Reading,
442) -> ImageHrefResolver<'a> {
443    let default_data = ImageHrefResolver::default_data_resolver();
444    let by_locator = Mutex::new(HashMap::<String, Option<Arc<Vec<u8>>>>::new());
445    let report = move |diagnostic| {
446        reports
447            .lock()
448            .unwrap_or_else(PoisonError::into_inner)
449            .push(diagnostic);
450    };
451    ImageHrefResolver {
452        // Nested SVG documents resolve their `data:` images through this too.
453        resolve_data: Box::new(move |mime, data, options| {
454            if reading.is_refused() {
455                return None;
456            }
457            // Matches usvg's own resolver: SVG type, or plain text that is not a raster image.
458            let svg = mime == "image/svg+xml"
459                || (mime == "text/plain" && imagesize::image_type(&data).is_err());
460            if svg {
461                return nested_svg(&data, options, reading);
462            }
463            let kind = default_data(mime, data, options)?;
464            // usvg decodes a `data:` URL again for every element that draws it.
465            within_canvas(kind, || format!("data:{mime}"), reports)
466                .filter(|kind| charge(kind, true, reading))
467        }),
468        resolve_string: Box::new(move |href, options| {
469            if reading.is_refused() {
470                return None;
471            }
472            let unreadable = |reason: &str| {
473                report(Diagnostic::UnreadableImage {
474                    href: href.to_owned(),
475                    reason: reason.to_owned(),
476                });
477                None
478            };
479            // Elements naming one locator share its bytes, which count once.
480            let mut shared = by_locator.lock().unwrap_or_else(PoisonError::into_inner);
481            let (bytes, fresh) = if let Some(known) = shared.get(href) {
482                (known.clone(), false)
483            } else {
484                let read = resolver
485                    .bytes(href)
486                    .ok()
487                    .map(|bytes| Arc::new(bytes.to_vec()));
488                shared.insert(href.to_owned(), read.clone());
489                (read, true)
490            };
491            drop(shared);
492            let Some(bytes) = bytes else {
493                report(Diagnostic::MissingImage {
494                    href: href.to_owned(),
495                });
496                return None;
497            };
498            let data = || Arc::clone(&bytes);
499            let raster = match registered_image(&bytes) {
500                Some(Registered::Png) => ImageKind::PNG(data()),
501                Some(Registered::Jpeg) => ImageKind::JPEG(data()),
502                Some(Registered::Gif) => ImageKind::GIF(data()),
503                Some(Registered::Webp) => ImageKind::WEBP(data()),
504                // Like a `data:` SVG, its external images are not loaded (SVG-as-image rules).
505                Some(Registered::Svg) => {
506                    return nested_svg(&bytes, options, reading)
507                        .or_else(|| unreadable("the SVG document does not parse"));
508                }
509                None => return unreadable("not a PNG, JPEG, GIF, WebP, or SVG image"),
510            };
511            within_canvas(raster, || href.to_owned(), reports)
512                .filter(|kind| charge(kind, fresh, reading))
513        }),
514    }
515}
516
517/// Reads a plain or gzipped SVG image within `reading`. Over budget refuses the outer document;
518/// a parse failure just leaves the image out.
519fn nested_svg(data: &[u8], options: &Options, reading: &Reading) -> Option<ImageKind> {
520    if reading.is_refused() {
521        return None;
522    }
523    let unpacked;
524    let text = if data.starts_with(&[0x1f, 0x8b]) {
525        // Unpacked only as far as there is text left to read.
526        let left = reading.text.load(Ordering::Relaxed);
527        let mut text = Vec::new();
528        let read = flate2::read::GzDecoder::new(data)
529            .take(u64::try_from(left).unwrap_or(u64::MAX).saturating_add(1))
530            .read_to_end(&mut text);
531        if read.is_err() {
532            return None;
533        }
534        if text.len() > left {
535            reading.refuse(too_much_text(reading.limit));
536            return None;
537        }
538        unpacked = text;
539        &unpacked[..]
540    } else {
541        data
542    };
543    let nested = Options {
544        resources_dir: None,
545        dpi: options.dpi,
546        font_size: options.font_size,
547        languages: options.languages.clone(),
548        shape_rendering: options.shape_rendering,
549        text_rendering: options.text_rendering,
550        image_rendering: options.image_rendering,
551        default_size: options.default_size,
552        image_href_resolver: ImageHrefResolver {
553            resolve_data: Box::new(|mime, data, nested| {
554                (options.image_href_resolver.resolve_data)(mime, data, nested)
555            }),
556            resolve_string: Box::new(|_, _| None),
557        },
558        fontdb: options.fontdb.clone(),
559        font_resolver: FontResolver {
560            select_font: Box::new(|font, fontdb| (options.font_resolver.select_font)(font, fontdb)),
561            select_fallback: Box::new(|c, used, fontdb| {
562                (options.font_resolver.select_fallback)(c, used, fontdb)
563            }),
564        },
565        ..Options::default()
566    };
567    match read_document(text, &nested, reading) {
568        Ok(tree) => Some(ImageKind::SVG(tree)),
569        Err(error @ ExtensionError::Budget(_)) => {
570            reading.refuse(error);
571            None
572        }
573        Err(_) => None,
574    }
575}
576
577/// Drops and reports as missing a raster image whose declared size exceeds the canvas limit,
578/// since resvg would decode it at that size on every render.
579fn within_canvas(
580    kind: ImageKind,
581    href: impl FnOnce() -> String,
582    reports: &Mutex<Vec<Diagnostic>>,
583) -> Option<ImageKind> {
584    let (ImageKind::JPEG(data)
585    | ImageKind::PNG(data)
586    | ImageKind::GIF(data)
587    | ImageKind::WEBP(data)) = &kind
588    else {
589        return Some(kind);
590    };
591    // A header usvg cannot size is left out by usvg itself.
592    let declared = imagesize::blob_size(data).ok()?;
593    let side = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
594    if check_canvas(side(declared.width), side(declared.height)).is_err() {
595        reports
596            .lock()
597            .unwrap_or_else(PoisonError::into_inner)
598            .push(Diagnostic::MissingImage { href: href() });
599        return None;
600    }
601    Some(kind)
602}
603
604/// Charges a raster image to `reading`: its bytes when `fresh`, and its declared pixels always.
605/// False once the document is refused.
606fn charge(kind: &ImageKind, fresh: bool, reading: &Reading) -> bool {
607    let (ImageKind::JPEG(data)
608    | ImageKind::PNG(data)
609    | ImageKind::GIF(data)
610    | ImageKind::WEBP(data)) = kind
611    else {
612        return true;
613    };
614    // A decoded `data:` URL grows into its buffer, which can be up to twice its length.
615    let bytes = if fresh { data.capacity() } else { 0 };
616    reading.take_image(bytes, raster_pixels(kind))
617}
618
619/// Bytes of the distinct raster images `group` holds, nested SVG images and subroots included.
620fn held_image_bytes(group: &usvg::Group, seen: &mut HashSet<usize>) -> usize {
621    let mut bytes = 0_usize;
622    for node in group.children() {
623        match node {
624            Node::Group(inner) => bytes = bytes.saturating_add(held_image_bytes(inner, seen)),
625            Node::Image(image) => match image.kind() {
626                ImageKind::JPEG(data)
627                | ImageKind::PNG(data)
628                | ImageKind::GIF(data)
629                | ImageKind::WEBP(data) => {
630                    if seen.insert(Arc::as_ptr(data) as usize) {
631                        bytes = bytes.saturating_add(data.capacity());
632                    }
633                }
634                ImageKind::SVG(_) => {}
635            },
636            Node::Path(_) | Node::Text(_) => {}
637        }
638        node.subroots(|root| bytes = bytes.saturating_add(held_image_bytes(root, seen)));
639    }
640    bytes
641}
642
643/// Decoded raster pixels `group` draws, counted per draw since resvg decodes on every draw.
644fn image_pixels(group: &usvg::Group) -> u64 {
645    let mut pixels = 0_u64;
646    for node in group.children() {
647        match node {
648            Node::Group(inner) => pixels = pixels.saturating_add(image_pixels(inner)),
649            Node::Image(image) => pixels = pixels.saturating_add(raster_pixels(image.kind())),
650            Node::Path(_) | Node::Text(_) => {}
651        }
652        // Clip paths, masks, filter images, patterns, and a nested SVG's own tree.
653        node.subroots(|root| pixels = pixels.saturating_add(image_pixels(root)));
654    }
655    pixels
656}
657
658/// Declared raster pixels; zero for a nested SVG, whose images are counted where drawn.
659fn raster_pixels(kind: &ImageKind) -> u64 {
660    match kind {
661        ImageKind::JPEG(data)
662        | ImageKind::PNG(data)
663        | ImageKind::GIF(data)
664        | ImageKind::WEBP(data) => imagesize::blob_size(data).map_or(0, |size| {
665            u64::try_from(size.width)
666                .unwrap_or(u64::MAX)
667                .saturating_mul(u64::try_from(size.height).unwrap_or(u64::MAX))
668        }),
669        ImageKind::SVG(_) => 0,
670    }
671}
672
673enum Registered {
674    Png,
675    Jpeg,
676    Gif,
677    Webp,
678    /// Plain or gzipped.
679    Svg,
680}
681
682fn registered_image(bytes: &[u8]) -> Option<Registered> {
683    if bytes.starts_with(b"\x89PNG") {
684        Some(Registered::Png)
685    } else if bytes.starts_with(&[0xff, 0xd8]) {
686        Some(Registered::Jpeg)
687    } else if bytes.starts_with(b"GIF8") {
688        Some(Registered::Gif)
689    } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
690        Some(Registered::Webp)
691    } else if looks_like_svg(bytes) || bytes.starts_with(&[0x1f, 0x8b]) {
692        Some(Registered::Svg)
693    } else {
694        None
695    }
696}
697
698/// An opened SVG document.
699pub(crate) struct SvgSource {
700    tree: Tree,
701    report: ProbeReport,
702    /// The area drawn, as left, top, width, and height in the document's own pixels.
703    view: (f32, f32, f32, f32),
704    /// Output pixels per document pixel at the source's own size.
705    scale: f32,
706    /// Premultiplied RGBA8 painted under the drawing.
707    background: Option<[u8; 4]>,
708    /// Coverage the finished picture is scaled by, out of 255.
709    opacity: u8,
710    /// Bytes of the distinct raster images the tree holds.
711    images: usize,
712    /// The last rasterization, reused while the size holds.
713    last: Option<VisualFrame>,
714}
715
716impl SvgSource {
717    /// The report, for a provider that describes generated SVG as its own format.
718    #[cfg(any(feature = "latex", feature = "pdf"))]
719    pub(crate) fn report_mut(&mut self) -> &mut ProbeReport {
720        &mut self.report
721    }
722
723    /// Paints `color` under the drawing, as a page or paper does.
724    #[cfg(feature = "pdf")]
725    pub(crate) fn with_background(mut self, color: Rgba) -> Self {
726        let mut pixel = [color.red, color.green, color.blue, color.alpha].map(unit_byte);
727        crate::api::premultiply(&mut pixel);
728        self.background = Some(pixel);
729        self
730    }
731
732    /// Widens the drawn area to whole pixels around everything the document paints, including
733    /// what lies outside its own size, and reports that as its size.
734    ///
735    /// # Errors
736    /// [`ExtensionError::Budget`] when the widened canvas or its drawing is over a limit.
737    #[cfg(feature = "latex")]
738    pub(crate) fn including_ink(mut self) -> Result<Self, ExtensionError> {
739        let size = self.tree.size();
740        let (mut left, mut top, mut right, mut bottom) = (0.0, 0.0, size.width(), size.height());
741        if let Some(ink) = self
742            .tree
743            .root()
744            .abs_stroke_bounding_box()
745            .to_non_zero_rect()
746        {
747            left = ink.left().min(left).floor();
748            top = ink.top().min(top).floor();
749            right = ink.right().max(right).ceil();
750            bottom = ink.bottom().max(bottom).ceil();
751        }
752        self.view = (left, top, right - left, bottom - top);
753        self.resized()
754    }
755
756    /// Reports and draws the document `scale` times its own size, such as points at 96 dpi.
757    ///
758    /// # Errors
759    /// [`ExtensionError::Budget`] when the scaled canvas or its drawing is over a limit.
760    #[cfg(feature = "pdf")]
761    pub(crate) fn scaled(mut self, scale: f32) -> Result<Self, ExtensionError> {
762        self.scale = scale;
763        self.resized()
764    }
765
766    /// Checks and reports the own size after the view or scale changed.
767    #[cfg(any(feature = "latex", feature = "pdf"))]
768    fn resized(mut self) -> Result<Self, ExtensionError> {
769        let (width, height) = self.own_size();
770        let (width, height) = fitted(width, height, (0, 0));
771        check_canvas(width, height)?;
772        render_cost::check(&self.tree, self.transform(width, height), width, height)?;
773        self.report.width = width;
774        self.report.height = height;
775        Ok(self)
776    }
777
778    fn own_size(&self) -> (f32, f32) {
779        (self.view.2 * self.scale, self.view.3 * self.scale)
780    }
781
782    /// Maps the drawn area onto a `width` by `height` canvas.
783    // Sizes are within MAX_CANVAS_SIDE, which f32 holds exactly.
784    #[allow(clippy::cast_precision_loss)]
785    fn transform(&self, width: u32, height: u32) -> Transform {
786        let (left, top, view_width, view_height) = self.view;
787        Transform::from_scale(width as f32 / view_width, height as f32 / view_height)
788            .pre_translate(-left, -top)
789    }
790
791    /// Scales the finished picture's coverage by `alpha` in `0..=1`.
792    #[cfg(feature = "latex")]
793    pub(crate) fn with_opacity(mut self, alpha: f32) -> Self {
794        self.opacity = unit_byte(alpha);
795        self
796    }
797}
798
799/// A `0..=1` component as the nearest 8-bit value.
800// Clamped to 0..=255 before the cast.
801#[cfg(any(feature = "latex", feature = "pdf"))]
802#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
803pub(crate) fn unit_byte(value: f32) -> u8 {
804    (value.clamp(0.0, 1.0) * 255.0).round() as u8
805}
806
807impl VisualSource for SvgSource {
808    fn report(&self) -> &ProbeReport {
809        &self.report
810    }
811
812    fn render(&mut self, _time: MediaTime, fit: (u32, u32)) -> Result<VisualFrame, ExtensionError> {
813        let (own_width, own_height) = self.own_size();
814        let (width, height) = fitted(own_width, own_height, fit);
815        if let Some(last) = self
816            .last
817            .as_ref()
818            .filter(|last| (last.width, last.height) == (width, height))
819        {
820            return Ok(last.clone());
821        }
822        let transform = self.transform(width, height);
823        render_cost::check(&self.tree, transform, width, height)?;
824        let mut pixmap = Pixmap::new(width, height).ok_or_else(|| {
825            ExtensionError::Budget(format!("cannot rasterize at {width}x{height}"))
826        })?;
827        if let Some(background) = self.background {
828            for pixel in pixmap.data_mut().as_chunks_mut::<4>().0 {
829                *pixel = background;
830            }
831        }
832        resvg::render(&self.tree, transform, &mut pixmap.as_mut());
833        let mut pixels = pixmap.take();
834        if self.opacity < u8::MAX {
835            let opacity = u16::from(self.opacity);
836            for channel in &mut pixels {
837                *channel = u8::try_from((u16::from(*channel) * opacity + 127) / 255).unwrap_or(255);
838            }
839        }
840        let frame = VisualFrame {
841            width,
842            height,
843            pixels: FramePixels::Rgba8(pixels.into()),
844            index: 0,
845            start: MediaTime::from_ticks(i64::MIN),
846            end: None,
847            diagnostics: Vec::new(),
848        };
849        self.last = Some(frame.clone());
850        Ok(frame)
851    }
852
853    fn resident_bytes(&self) -> usize {
854        self.last
855            .as_ref()
856            .map_or(0, |last| last.pixels.byte_len())
857            .saturating_add(self.images)
858    }
859}
860
861/// The largest whole-pixel size that fits in `fit` keeping aspect; the own size if `fit` is empty.
862// Every size is positive and within MAX_CANVAS_SIDE, which f32 holds exactly.
863#[allow(
864    clippy::cast_precision_loss,
865    clippy::cast_possible_truncation,
866    clippy::cast_sign_loss
867)]
868fn fitted(width: f32, height: f32, fit: (u32, u32)) -> (u32, u32) {
869    if fit.0 == 0 || fit.1 == 0 {
870        return (
871            width.round().max(1.0) as u32,
872            height.round().max(1.0) as u32,
873        );
874    }
875    let scale = (fit.0 as f32 / width).min(fit.1 as f32 / height);
876    (
877        (width * scale).round().clamp(1.0, fit.0 as f32) as u32,
878        (height * scale).round().clamp(1.0, fit.1 as f32) as u32,
879    )
880}
881
882#[cfg(test)]
883mod tests {
884    use super::*;
885
886    #[test]
887    fn a_refused_reading_parses_no_more_nested_images() {
888        let image = br#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>"#;
889        let reading = Reading::new(MAX_SVG_DOCUMENT_BYTES, MAX_SOURCE_IMAGE_BYTES);
890        let options = Options::default();
891        assert!(nested_svg(image, &options, &reading).is_some());
892        reading.refuse(ExtensionError::Budget("refused".into()));
893        let text = reading.text.load(Ordering::Relaxed);
894        assert!(nested_svg(image, &options, &reading).is_none());
895        assert_eq!(reading.text.load(Ordering::Relaxed), text);
896    }
897}