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