Skip to main content

tilo_render_protocol/
validate.rs

1//! The CPU pass every scene passes before the GPU sees it.
2//!
3//! The render service draws every app of a room on one device. A scene that
4//! makes vello's CPU stages panic takes the room's rendering down; one that
5//! makes its shaders read the wrong data draws another app's pixels or hangs
6//! the GPU for everyone. So a decoded [`Encoding`] is checked against exactly
7//! the invariants vello's own encoder establishes and its resolver and
8//! shaders rely on:
9//!
10//! - **Streams agree with each other.** Every path tag is a tag vello writes;
11//!   the path data holds exactly the points the segment tags consume; there
12//!   is one transform per transform tag, one style per style tag, one draw
13//!   object per path (glyph runs bring their paths at resolve), and the draw
14//!   data holds exactly what the draw tags say.
15//! - **Every late-bound resource is where its draw is.** A gradient's ramp
16//!   and an image's atlas slot are written by the resolver at the offset its
17//!   patch names, so every gradient and image draw has exactly one patch at
18//!   its own offset, in stream order, and an image draw's size is the
19//!   registered image's: a scene cannot point the shader at another app's
20//!   pixels in the shared atlas. Glyph runs are referenced once each, in
21//!   stream order, with their glyph and coordinate ranges in bounds.
22//! - **Numbers are finite and bounded.** Coordinates, transforms, stroke
23//!   widths, gradient geometry, layer alpha and glyph sizes.
24//! - **Clips nest.** Begin and end balance, never deeper than the limit, and
25//!   a layer leaves none open.
26//! - **Work is bounded** by the app's [`Limits`]: paths, segments, draw
27//!   objects, glyphs.
28//!
29//! The pass is O(encoded size) and allocates nothing proportional to it
30//! beyond a per-draw marker.
31
32use vello_encoding::{DrawTag, Encoding, Patch, PathTag, Style, Transform};
33
34use crate::{Limits, WireError};
35
36/// Largest coordinate magnitude a scene may encode. Far beyond any surface;
37/// small enough that tile arithmetic on the GPU stays exact.
38pub const MAX_COORDINATE: f32 = 1.0e7;
39
40/// Largest glyph size, in pixels per em.
41pub const MAX_FONT_SIZE: f32 = 16_384.0;
42
43/// Variation coordinates of one glyph run (a font has at most a few dozen axes).
44pub const MAX_RUN_COORDS: usize = 64;
45
46/// What a valid scene costs, for the service's per-frame budget.
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub struct SceneCost {
49    pub paths: u32,
50    pub segments: u64,
51    pub draw_objects: u32,
52    pub glyphs: u32,
53    pub clip_depth: u32,
54}
55
56impl SceneCost {
57    /// Both costs together (a frame's layers and backdrops).
58    #[must_use]
59    pub fn plus(self, other: Self) -> Self {
60        Self {
61            paths: self.paths.saturating_add(other.paths),
62            segments: self.segments.saturating_add(other.segments),
63            draw_objects: self.draw_objects.saturating_add(other.draw_objects),
64            glyphs: self.glyphs.saturating_add(other.glyphs),
65            clip_depth: self.clip_depth.max(other.clip_depth),
66        }
67    }
68
69    /// The first limit this cost breaks.
70    pub fn check(&self, limits: &Limits) -> Result<(), WireError> {
71        if self.paths > limits.paths {
72            return Err(WireError::OverLimit("paths"));
73        }
74        if self.segments > u64::from(limits.segments) {
75            return Err(WireError::OverLimit("segments"));
76        }
77        if self.draw_objects > limits.draw_objects {
78            return Err(WireError::OverLimit("draw objects"));
79        }
80        if self.glyphs > limits.glyphs {
81            return Err(WireError::OverLimit("glyphs"));
82        }
83        if self.clip_depth > limits.clip_depth {
84            return Err(WireError::OverLimit("clip depth"));
85        }
86        Ok(())
87    }
88}
89
90/// Segments a glyph's outline is reckoned at before it is expanded, for the
91/// segment budget. Text glyphs are tens; a pathological outline is bounded by
92/// the glyph cache and vello's scratch budget, not by this estimate.
93const SEGMENTS_PER_GLYPH: u64 = 64;
94
95/// Check `encoding` and return what it costs. `limits` bounds the cost.
96///
97/// # Errors
98///
99/// The first invariant the encoding breaks.
100pub fn validate(encoding: &Encoding, limits: &Limits) -> Result<SceneCost, WireError> {
101    let paths = check_path_streams(encoding)?;
102    let draws = check_draw_stream(encoding, limits)?;
103    check_patches(encoding, &draws)?;
104    check_glyph_runs(encoding)?;
105    check_transforms(&encoding.transforms)?;
106    check_styles(&encoding.styles)?;
107    check_stops(encoding)?;
108    if encoding.flags & !(Encoding::FORCE_NEXT_TRANSFORM | Encoding::FORCE_NEXT_STYLE) != 0 {
109        return Err(WireError::Invalid("unknown encoding flags"));
110    }
111    let glyphs = encoding.resources.glyphs.len();
112    let cost = SceneCost {
113        paths: paths
114            .paths
115            .saturating_add(u32::try_from(encoding.resources.glyph_runs.len()).unwrap_or(u32::MAX)),
116        segments: u64::from(paths.segments)
117            .saturating_add((glyphs as u64).saturating_mul(SEGMENTS_PER_GLYPH)),
118        draw_objects: u32::try_from(encoding.draw_tags.len()).unwrap_or(u32::MAX),
119        glyphs: u32::try_from(glyphs).unwrap_or(u32::MAX),
120        clip_depth: draws.max_depth,
121    };
122    cost.check(limits)?;
123    Ok(cost)
124}
125
126struct PathCounts {
127    paths: u32,
128    segments: u32,
129}
130
131fn finite_coordinate(value: f32) -> bool {
132    value.is_finite() && value.abs() <= MAX_COORDINATE
133}
134
135fn finite_transform(transform: &Transform) -> bool {
136    transform
137        .matrix
138        .iter()
139        .chain(transform.translation.iter())
140        .all(|value| finite_coordinate(*value))
141}
142
143fn check_transforms(transforms: &[Transform]) -> Result<(), WireError> {
144    if transforms.iter().all(finite_transform) {
145        Ok(())
146    } else {
147        Err(WireError::Invalid("a transform is not finite"))
148    }
149}
150
151/// The path tags, path data, transform and style counts, and the number of
152/// paths and segments.
153fn check_path_streams(encoding: &Encoding) -> Result<PathCounts, WireError> {
154    let data = &encoding.path_data;
155    let mut offset = 0_usize;
156    let mut paths = 0_u32;
157    let mut segments = 0_u32;
158    let mut transforms = 0_usize;
159    let mut styles = 0_usize;
160    for tag in &encoding.path_tags {
161        let bits = tag.0;
162        if bits == PathTag::PATH.0 {
163            paths = paths.checked_add(1).ok_or(WireError::Overflow)?;
164            continue;
165        }
166        if bits == PathTag::TRANSFORM.0 {
167            transforms = transforms.checked_add(1).ok_or(WireError::Overflow)?;
168            continue;
169        }
170        if bits == PathTag::STYLE.0 {
171            styles = styles.checked_add(1).ok_or(WireError::Overflow)?;
172            continue;
173        }
174        // A segment: two type bits, the subpath-end and f32 bits, nothing else.
175        if bits & !0x0f != 0 || !tag.is_path_segment() {
176            return Err(WireError::Invalid("unknown path tag"));
177        }
178        segments = segments.checked_add(1).ok_or(WireError::Overflow)?;
179        let points = usize::from(tag.path_segment_type().0);
180        let words_per_point = if tag.is_f32() { 2 } else { 1 };
181        // The segment reads its start point at `offset` and its own points
182        // after it; the last of them is the next segment's start.
183        let read = points
184            .checked_add(1)
185            .and_then(|read| read.checked_mul(words_per_point))
186            .ok_or(WireError::Overflow)?;
187        let end = offset.checked_add(read).ok_or(WireError::Overflow)?;
188        let words = data
189            .get(offset..end)
190            .ok_or(WireError::Invalid("path data shorter than its segments"))?;
191        if tag.is_f32()
192            && !words
193                .iter()
194                .all(|word| finite_coordinate(f32::from_bits(*word)))
195        {
196            return Err(WireError::Invalid("a path coordinate is not finite"));
197        }
198        let advance = points
199            .checked_add(usize::from(tag.is_subpath_end()))
200            .and_then(|advance| advance.checked_mul(words_per_point))
201            .ok_or(WireError::Overflow)?;
202        offset = offset.checked_add(advance).ok_or(WireError::Overflow)?;
203    }
204    if offset != data.len() {
205        return Err(WireError::Invalid("path data does not match its segments"));
206    }
207    if transforms != encoding.transforms.len() {
208        return Err(WireError::Invalid(
209            "transform count does not match its tags",
210        ));
211    }
212    if styles != encoding.styles.len() {
213        return Err(WireError::Invalid("style count does not match its tags"));
214    }
215    if paths != encoding.n_paths {
216        return Err(WireError::Invalid("path count does not match its tags"));
217    }
218    if segments != encoding.n_path_segments {
219        return Err(WireError::Invalid("segment count does not match its tags"));
220    }
221    Ok(PathCounts { paths, segments })
222}
223
224/// What kind of late-bound data a draw object's first data word waits for.
225#[derive(Clone, Copy, PartialEq, Eq)]
226enum Slot {
227    Ramp,
228    Image { width_height: u32 },
229}
230
231struct Draws {
232    /// Draw data offset (in words) of every draw whose first word a patch
233    /// fills, in stream order.
234    slots: Vec<(usize, Slot)>,
235    max_depth: u32,
236}
237
238/// Words of draw data a draw tag carries, or `None` for a tag vello never
239/// writes.
240fn draw_words(tag: DrawTag) -> Option<usize> {
241    let known = [
242        DrawTag::COLOR,
243        DrawTag::LINEAR_GRADIENT,
244        DrawTag::RADIAL_GRADIENT,
245        DrawTag::SWEEP_GRADIENT,
246        DrawTag::IMAGE,
247        DrawTag::BLUR_RECT,
248        DrawTag::BEGIN_CLIP,
249        DrawTag::END_CLIP,
250    ];
251    known
252        .contains(&tag)
253        .then_some(((tag.0 >> 2) & 0x7) as usize)
254}
255
256fn floats_finite(words: &[u32]) -> bool {
257    words
258        .iter()
259        .all(|word| finite_coordinate(f32::from_bits(*word)))
260}
261
262fn valid_blend(mode: u32) -> bool {
263    use vello_encoding::DrawBeginClip;
264    if mode == DrawBeginClip::LUMINANCE_MASK_BLEND_MODE || mode == DrawBeginClip::CLIP_BLEND_MODE {
265        return true;
266    }
267    let mix = mode >> 8;
268    let compose = mode & 0xff;
269    mix <= 15 && compose <= 13
270}
271
272fn check_draw_stream(encoding: &Encoding, limits: &Limits) -> Result<Draws, WireError> {
273    let data = &encoding.draw_data;
274    let mut offset = 0_usize;
275    let mut depth = 0_u32;
276    let mut max_depth = 0_u32;
277    let mut clips = 0_u32;
278    let mut slots = Vec::new();
279    for tag in &encoding.draw_tags {
280        let words = draw_words(*tag).ok_or(WireError::Invalid("unknown draw tag"))?;
281        let end = offset.checked_add(words).ok_or(WireError::Overflow)?;
282        let body = data
283            .get(offset..end)
284            .ok_or(WireError::Invalid("draw data shorter than its tags"))?;
285        match *tag {
286            DrawTag::LINEAR_GRADIENT | DrawTag::RADIAL_GRADIENT | DrawTag::SWEEP_GRADIENT => {
287                if !floats_finite(body.get(1..).unwrap_or_default()) {
288                    return Err(WireError::Invalid("gradient geometry is not finite"));
289                }
290                slots.push((offset, Slot::Ramp));
291            }
292            DrawTag::IMAGE => {
293                let width_height = *body.get(1).ok_or(WireError::Invalid("image draw data"))?;
294                slots.push((offset, Slot::Image { width_height }));
295            }
296            DrawTag::BLUR_RECT => {
297                if !floats_finite(body.get(1..).unwrap_or_default()) {
298                    return Err(WireError::Invalid("blurred rectangle is not finite"));
299                }
300            }
301            DrawTag::BEGIN_CLIP => {
302                let (Some(mode), Some(alpha)) = (body.first(), body.get(1)) else {
303                    return Err(WireError::Invalid("clip draw data"));
304                };
305                let alpha = f32::from_bits(*alpha);
306                if !valid_blend(*mode) || !(0.0..=1.0).contains(&alpha) {
307                    return Err(WireError::Invalid("layer blend or alpha"));
308                }
309                depth = depth.checked_add(1).ok_or(WireError::Overflow)?;
310                max_depth = max_depth.max(depth);
311                if depth > limits.clip_depth {
312                    return Err(WireError::OverLimit("clip depth"));
313                }
314                clips = clips.checked_add(1).ok_or(WireError::Overflow)?;
315            }
316            DrawTag::END_CLIP => {
317                depth = depth
318                    .checked_sub(1)
319                    .ok_or(WireError::Invalid("a clip ends that never began"))?;
320                clips = clips.checked_add(1).ok_or(WireError::Overflow)?;
321            }
322            _ => {}
323        }
324        offset = end;
325    }
326    if offset != data.len() {
327        return Err(WireError::Invalid("draw data does not match its tags"));
328    }
329    if depth != 0 || encoding.n_open_clips != 0 {
330        return Err(WireError::Invalid("a clip is left open"));
331    }
332    if clips != encoding.n_clips {
333        return Err(WireError::Invalid("clip count does not match its tags"));
334    }
335    // One draw object per path; a glyph run's paths arrive at resolve.
336    let objects = usize::try_from(encoding.n_paths)
337        .ok()
338        .and_then(|paths| paths.checked_add(encoding.resources.glyph_runs.len()))
339        .ok_or(WireError::Overflow)?;
340    if objects != encoding.draw_tags.len() {
341        return Err(WireError::Invalid("draw objects do not match paths"));
342    }
343    Ok(Draws { slots, max_depth })
344}
345
346fn check_patches(encoding: &Encoding, draws: &Draws) -> Result<(), WireError> {
347    let res = &encoding.resources;
348    let mut slots = draws.slots.iter();
349    let mut next_run = 0_usize;
350    let mut run_offsets = [0_usize; 6];
351    for patch in &res.patches {
352        match patch {
353            Patch::Ramp {
354                draw_data_offset,
355                stops,
356                ..
357            } => {
358                let Some((offset, Slot::Ramp)) = slots.next() else {
359                    return Err(WireError::Invalid("a ramp patch without its gradient"));
360                };
361                if offset != draw_data_offset {
362                    return Err(WireError::Invalid("a ramp patch away from its gradient"));
363                }
364                if stops.start >= stops.end || res.color_stops.get(stops.clone()).is_none() {
365                    return Err(WireError::Invalid("gradient stops out of range"));
366                }
367            }
368            Patch::Image {
369                draw_data_offset,
370                image,
371            } => {
372                let Some((offset, Slot::Image { width_height })) = slots.next() else {
373                    return Err(WireError::Invalid("an image patch without its draw"));
374                };
375                if offset != draw_data_offset {
376                    return Err(WireError::Invalid("an image patch away from its draw"));
377                }
378                let expected = (image.width < 1 << 16 && image.height < 1 << 16)
379                    .then_some((image.width << 16) | image.height);
380                if expected != Some(*width_height) {
381                    return Err(WireError::Invalid(
382                        "an image draw's size is not its image's",
383                    ));
384                }
385                let pixels = image
386                    .format
387                    .size_in_bytes(image.width, image.height)
388                    .ok_or(WireError::Overflow)?;
389                if image.data.data().len() < pixels {
390                    return Err(WireError::Invalid("image data shorter than its size"));
391                }
392            }
393            Patch::GlyphRun { index } => {
394                if *index != next_run {
395                    return Err(WireError::Invalid("glyph runs out of order"));
396                }
397                next_run = next_run.checked_add(1).ok_or(WireError::Overflow)?;
398                let run = res
399                    .glyph_runs
400                    .get(*index)
401                    .ok_or(WireError::Invalid("a glyph run patch without its run"))?;
402                let offsets = &run.stream_offsets;
403                let now = [
404                    offsets.path_tags,
405                    offsets.path_data,
406                    offsets.draw_tags,
407                    offsets.draw_data,
408                    offsets.transforms,
409                    offsets.styles,
410                ];
411                let lengths = [
412                    encoding.path_tags.len(),
413                    encoding.path_data.len(),
414                    encoding.draw_tags.len(),
415                    encoding.draw_data.len(),
416                    encoding.transforms.len(),
417                    encoding.styles.len(),
418                ];
419                for ((now, before), length) in now.iter().zip(run_offsets).zip(lengths) {
420                    if *now < before || *now > length {
421                        return Err(WireError::Invalid("glyph run stream offsets"));
422                    }
423                }
424                run_offsets = now;
425            }
426        }
427    }
428    if slots.next().is_some() {
429        return Err(WireError::Invalid(
430            "a gradient or image draw without its patch",
431        ));
432    }
433    if next_run != res.glyph_runs.len() {
434        return Err(WireError::Invalid("a glyph run without its patch"));
435    }
436    Ok(())
437}
438
439fn check_glyph_runs(encoding: &Encoding) -> Result<(), WireError> {
440    let res = &encoding.resources;
441    for run in &res.glyph_runs {
442        if run.glyphs.start > run.glyphs.end || res.glyphs.get(run.glyphs.clone()).is_none() {
443            return Err(WireError::Invalid("glyph range out of bounds"));
444        }
445        let coords = run.normalized_coords.clone();
446        if coords.start > coords.end
447            || res.normalized_coords.get(coords.clone()).is_none()
448            || coords.len() > MAX_RUN_COORDS
449        {
450            return Err(WireError::Invalid("variation coordinates out of bounds"));
451        }
452        if !(run.font_size.is_finite() && run.font_size > 0.0 && run.font_size <= MAX_FONT_SIZE) {
453            return Err(WireError::Invalid("font size"));
454        }
455        let transforms_finite = finite_transform(&run.transform)
456            && run.glyph_transform.as_ref().is_none_or(finite_transform)
457            && run.brush_transform.as_ref().is_none_or(finite_transform);
458        if !transforms_finite {
459            return Err(WireError::Invalid("a glyph run transform is not finite"));
460        }
461        let embolden = &run.font_embolden;
462        let bounded =
463            |value: f64, low: f64, high: f64| value.is_finite() && (low..=high).contains(&value);
464        if !(bounded(embolden.amount.xx, -1.0e3, 1.0e3)
465            && bounded(embolden.amount.yy, -1.0e3, 1.0e3)
466            && bounded(embolden.miter_limit, 0.0, 1.0e3)
467            && bounded(embolden.tolerance, 0.0, 1.0e3))
468        {
469            return Err(WireError::Invalid("glyph embolden"));
470        }
471        if let peniko::Style::Stroke(stroke) = &run.style {
472            let dashes_ok = stroke
473                .dash_pattern
474                .iter()
475                .all(|dash| bounded(*dash, 0.0, 1.0e6))
476                && (stroke.dash_pattern.is_empty()
477                    || stroke.dash_pattern.iter().sum::<f64>() > 1.0e-3);
478            if !(bounded(stroke.width, 0.0, 1.0e6)
479                && bounded(stroke.miter_limit, 0.0, 1.0e3)
480                && bounded(stroke.dash_offset, -1.0e6, 1.0e6)
481                && dashes_ok)
482            {
483                return Err(WireError::Invalid("glyph stroke"));
484            }
485        }
486        if !res
487            .glyphs
488            .get(run.glyphs.clone())
489            .unwrap_or_default()
490            .iter()
491            .all(|glyph| finite_coordinate(glyph.x) && finite_coordinate(glyph.y))
492        {
493            return Err(WireError::Invalid("a glyph position is not finite"));
494        }
495    }
496    Ok(())
497}
498
499/// Style flag bits vello defines: fill or stroke, fill rule, join, caps and
500/// the half-float miter limit.
501const STYLE_BITS: u32 = Style::FLAGS_STYLE_BIT
502    | Style::FLAGS_FILL_BIT
503    | Style::FLAGS_JOIN_MASK
504    | Style::FLAGS_START_CAP_MASK
505    | Style::FLAGS_END_CAP_MASK
506    | Style::MITER_LIMIT_MASK;
507
508fn check_styles(styles: &[Style]) -> Result<(), WireError> {
509    for style in styles {
510        let flags = style.flags_and_miter_limit;
511        let width = style.line_width;
512        let join = flags & Style::FLAGS_JOIN_MASK;
513        let caps_known = (flags & Style::FLAGS_START_CAP_MASK) != Style::FLAGS_START_CAP_MASK
514            && (flags & Style::FLAGS_END_CAP_MASK) != Style::FLAGS_END_CAP_MASK;
515        if flags & !STYLE_BITS != 0
516            || join == Style::FLAGS_JOIN_MASK
517            || !caps_known
518            || !(width.is_finite() && (0.0..=1.0e6).contains(&width))
519        {
520            return Err(WireError::Invalid("style"));
521        }
522    }
523    Ok(())
524}
525
526fn check_stops(encoding: &Encoding) -> Result<(), WireError> {
527    for stop in &encoding.resources.color_stops {
528        let valid = stop.offset.is_finite()
529            && (0.0..=1.0).contains(&stop.offset)
530            && stop.color.components.iter().all(|value| value.is_finite());
531        if !valid {
532            return Err(WireError::Invalid("gradient stop"));
533        }
534    }
535    Ok(())
536}