Skip to main content

tilo_render_protocol/
frame.rs

1//! One frame of one surface, as it sits in the ring.
2//!
3//! ```text
4//! header   u32 magic "TRF1", u16 version, u16 flags, u32 record length,
5//!          u32 surface, u64 sequence, u32 width, u32 height,
6//!          4 × f32 base colour (premultiplied-free sRGB, alpha last)
7//! sections u16 kind, u16 section flags, u32 length, payload, zero padding to 4
8//! ```
9//!
10//! A section whose kind the reader does not know is skipped when its sender
11//! set [`SECTION_OPTIONAL`], and refuses the frame otherwise: a later step can
12//! add scene annotations as optional sections that older services ignore,
13//! and service-run motion as required ones that only a service which
14//! announced them in its hello receives.
15//!
16//! Sections of version 1:
17//!
18//! - [`SECTION_DAMAGE`]: rectangles of the surface that changed since the
19//!   previous frame, in pixels. With the header's [`FRAME_FULL`] the whole
20//!   surface did.
21//! - [`SECTION_SCROLL_COPY`]: copies within the retained surface, in order,
22//!   before the damage is repainted (what a scroll keeps).
23//! - [`SECTION_LAYER`]: a layer's new content, transform, opacity and clip;
24//!   or that it keeps its content; or that it is gone. Layers not named keep
25//!   everything.
26//! - [`SECTION_ORDER`]: the order layers draw in, bottom first. Without it
27//!   the previous order holds; new layers go on top.
28//! - [`SECTION_BACKDROP`]: a floating surface's blurred backdrop: the
29//!   placeholder image the scene draws, where, how blurred, and the scene
30//!   composed below it.
31
32use crate::bytes::{Reader, Writer};
33use crate::scene::{self, ResourceIds, Resources};
34use crate::validate::{SceneCost, validate};
35use crate::{ImageId, LayerId, Limits, SurfaceId, WireError};
36use vello_encoding::{Encoding, Transform};
37
38const MAGIC: u32 = u32::from_le_bytes(*b"TRF1");
39const HEADER_BYTES: usize = 48;
40
41/// The whole surface changed: repaint all of it.
42pub const FRAME_FULL: u16 = 1;
43
44/// A reader that does not know this section's kind skips it.
45pub const SECTION_OPTIONAL: u16 = 1;
46
47pub const SECTION_DAMAGE: u16 = 1;
48pub const SECTION_SCROLL_COPY: u16 = 2;
49pub const SECTION_LAYER: u16 = 3;
50pub const SECTION_ORDER: u16 = 4;
51pub const SECTION_BACKDROP: u16 = 5;
52
53/// A rectangle in surface pixels, `x0 <= x1`, `y0 <= y1`.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct Rect {
56    pub x0: f32,
57    pub y0: f32,
58    pub x1: f32,
59    pub y1: f32,
60}
61
62impl Rect {
63    fn valid(&self) -> bool {
64        [self.x0, self.y0, self.x1, self.y1]
65            .iter()
66            .all(|value| value.is_finite() && value.abs() <= crate::validate::MAX_COORDINATE)
67            && self.x0 <= self.x1
68            && self.y0 <= self.y1
69    }
70}
71
72/// A copy within the retained surface: the source rectangle and how far it
73/// moves, in pixels.
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct ScrollCopy {
76    pub x: u32,
77    pub y: u32,
78    pub width: u32,
79    pub height: u32,
80    pub dx: i32,
81    pub dy: i32,
82}
83
84/// What a frame does to one layer.
85#[derive(Clone)]
86pub enum LayerChange {
87    Content(Box<Encoding>),
88    /// The content stays; the properties change.
89    Keep,
90    /// The layer is gone.
91    Remove,
92}
93
94#[derive(Clone)]
95pub struct LayerUpdate {
96    pub id: LayerId,
97    pub change: LayerChange,
98    /// Placed by this transform.
99    pub transform: Transform,
100    /// Drawn at this opacity, `0..=1`.
101    pub opacity: f32,
102    /// Clipped to this rectangle, in surface pixels.
103    pub clip: Option<Rect>,
104}
105
106impl LayerUpdate {
107    /// Layer `id` with new `content`, untransformed, opaque, unclipped.
108    #[must_use]
109    pub fn content(id: LayerId, content: Encoding) -> Self {
110        Self {
111            id,
112            change: LayerChange::Content(Box::new(content)),
113            transform: Transform::IDENTITY,
114            opacity: 1.0,
115            clip: None,
116        }
117    }
118}
119
120/// A floating surface's blurred backdrop.
121#[derive(Clone)]
122pub struct Backdrop {
123    /// The placeholder image the frame draws, which the service replaces
124    /// with the blur.
125    pub image: ImageId,
126    /// Where the placeholder lands, in surface pixels.
127    pub rect: Rect,
128    /// Blur standard deviation, in surface pixels.
129    pub blur_px: f32,
130    /// The sampling the surface asked for, after the blur: `0` smooth, `1`
131    /// at one colour per cell of `cell_px` (a surface shown as pixels).
132    pub sampling: u8,
133    /// The cell's side in surface pixels, where `sampling` is blocky; `0`
134    /// otherwise.
135    pub cell_px: f32,
136    /// The lens the backdrop is bent through, in surface pixels: the
137    /// displacement at the rim (`0` bends nothing), the band it eases
138    /// across, the rounded rect's corner radius, and the fraction red and
139    /// blue are set apart by.
140    pub refraction: [f32; 4],
141    /// The relative luminances, darkest and lightest, what shows through
142    /// is compressed into so text over the surface stays legible; `0`, `1`
143    /// compresses nothing.
144    pub legible: [f32; 2],
145    /// What the backdrop shows where nothing below covers it.
146    pub ground: [f32; 4],
147    /// The theme's material stage the service runs over the blurred backdrop: its WGSL, which the
148    /// service checks before it compiles it, and its uniforms. `None` shows the backdrop as it is.
149    pub stage: Option<BackdropStage>,
150    /// Everything composed below the surface.
151    pub below: Encoding,
152}
153
154/// A material stage as a frame carries it.
155#[derive(Clone, Debug, PartialEq)]
156pub struct BackdropStage {
157    pub wgsl: String,
158    pub uniforms: [f32; STAGE_FLOATS],
159}
160
161/// How many numbers a stage's uniforms hold.
162pub const STAGE_FLOATS: usize = 40;
163
164/// The most WGSL a stage may carry, bytes.
165pub const MAX_STAGE_SOURCE: usize = 16 * 1024;
166
167/// A frame record, decoded.
168#[derive(Clone)]
169pub struct Frame {
170    pub surface: SurfaceId,
171    pub sequence: u64,
172    pub width: u32,
173    pub height: u32,
174    pub base_color: [f32; 4],
175    pub full: bool,
176    pub damage: Vec<Rect>,
177    pub scroll_copies: Vec<ScrollCopy>,
178    pub layers: Vec<LayerUpdate>,
179    pub order: Option<Vec<LayerId>>,
180    pub backdrops: Vec<Backdrop>,
181}
182
183/// Writes a frame record; [`FrameWriter::finish`] fills in its length.
184pub struct FrameWriter<'a> {
185    out: &'a mut Vec<u8>,
186    start: usize,
187}
188
189impl<'a> FrameWriter<'a> {
190    /// Start a record for `surface` at the end of `out`.
191    pub fn new(
192        out: &'a mut Vec<u8>,
193        (surface, sequence): (SurfaceId, u64),
194        (width, height): (u32, u32),
195        base_color: [f32; 4],
196        full: bool,
197    ) -> Self {
198        let start = out.len();
199        let mut w = Writer::new(out);
200        w.u32(MAGIC);
201        w.u16(crate::PROTOCOL_VERSION);
202        w.u16(if full { FRAME_FULL } else { 0 });
203        w.u32(0);
204        w.u32(surface.0);
205        w.u64(sequence);
206        w.u32(width);
207        w.u32(height);
208        for value in base_color {
209            w.f32(value);
210        }
211        Self { out, start }
212    }
213
214    fn section(
215        &mut self,
216        kind: u16,
217        body: impl FnOnce(&mut Writer<'_>) -> Result<(), WireError>,
218    ) -> Result<(), WireError> {
219        let mut w = Writer::new(self.out);
220        w.u16(kind);
221        w.u16(0);
222        let length_at = w.len();
223        w.u32(0);
224        let body_start = w.len();
225        body(&mut w)?;
226        let length = w.len().checked_sub(body_start).ok_or(WireError::Overflow)?;
227        w.patch_u32(
228            length_at,
229            u32::try_from(length).map_err(|_| WireError::Overflow)?,
230        )?;
231        w.align4(length);
232        Ok(())
233    }
234
235    /// The rectangles that changed.
236    pub fn damage(&mut self, rects: &[Rect]) -> Result<(), WireError> {
237        if rects.is_empty() {
238            return Ok(());
239        }
240        self.section(SECTION_DAMAGE, |w| {
241            w.count(rects.len())?;
242            for rect in rects {
243                for value in [rect.x0, rect.y0, rect.x1, rect.y1] {
244                    w.f32(value);
245                }
246            }
247            Ok(())
248        })
249    }
250
251    /// The copies a scroll keeps, in order.
252    pub fn scroll_copies(&mut self, copies: &[ScrollCopy]) -> Result<(), WireError> {
253        if copies.is_empty() {
254            return Ok(());
255        }
256        self.section(SECTION_SCROLL_COPY, |w| {
257            w.count(copies.len())?;
258            for copy in copies {
259                for value in [copy.x, copy.y, copy.width, copy.height] {
260                    w.u32(value);
261                }
262                w.i32(copy.dx);
263                w.i32(copy.dy);
264            }
265            Ok(())
266        })
267    }
268
269    /// One layer's change; its content's resources are registered through
270    /// `ids`.
271    pub fn layer(
272        &mut self,
273        layer: &LayerUpdate,
274        ids: &mut dyn ResourceIds,
275    ) -> Result<(), WireError> {
276        self.section(SECTION_LAYER, |w| {
277            w.u32(layer.id.0);
278            let (op, content) = match &layer.change {
279                LayerChange::Content(content) => (0_u32, Some(content)),
280                LayerChange::Keep => (1, None),
281                LayerChange::Remove => (2, None),
282            };
283            w.u32(op | if layer.clip.is_some() { 1 << 8 } else { 0 });
284            for value in layer
285                .transform
286                .matrix
287                .iter()
288                .chain(&layer.transform.translation)
289            {
290                w.f32(*value);
291            }
292            w.f32(layer.opacity);
293            let clip = layer.clip.unwrap_or(Rect {
294                x0: 0.0,
295                y0: 0.0,
296                x1: 0.0,
297                y1: 0.0,
298            });
299            for value in [clip.x0, clip.y0, clip.x1, clip.y1] {
300                w.f32(value);
301            }
302            if let Some(content) = content {
303                scene::encode(content, ids, w.vec())?;
304            }
305            Ok(())
306        })
307    }
308
309    /// Layer `id`'s new content, untransformed, opaque, unclipped: what a
310    /// toolkit frame sends for its root layer, without copying the encoding.
311    pub fn content(
312        &mut self,
313        id: LayerId,
314        content: &Encoding,
315        ids: &mut dyn ResourceIds,
316    ) -> Result<(), WireError> {
317        self.section(SECTION_LAYER, |w| {
318            w.u32(id.0);
319            w.u32(0);
320            for value in [1.0_f32, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] {
321                w.f32(value);
322            }
323            scene::encode(content, ids, w.vec())?;
324            Ok(())
325        })
326    }
327
328    /// The order layers draw in, bottom first.
329    pub fn order(&mut self, order: &[LayerId]) -> Result<(), WireError> {
330        self.section(SECTION_ORDER, |w| {
331            w.count(order.len())?;
332            for id in order {
333                w.u32(id.0);
334            }
335            Ok(())
336        })
337    }
338
339    /// A floating surface's backdrop.
340    pub fn backdrop(
341        &mut self,
342        backdrop: &Backdrop,
343        ids: &mut dyn ResourceIds,
344    ) -> Result<(), WireError> {
345        self.section(SECTION_BACKDROP, |w| {
346            w.u32(backdrop.image.0);
347            let rect = backdrop.rect;
348            for value in [
349                rect.x0,
350                rect.y0,
351                rect.x1,
352                rect.y1,
353                backdrop.blur_px,
354                backdrop.cell_px,
355            ] {
356                w.f32(value);
357            }
358            for value in backdrop.refraction.into_iter().chain(backdrop.legible) {
359                w.f32(value);
360            }
361            w.u8(backdrop.sampling);
362            for value in backdrop.ground {
363                w.f32(value);
364            }
365            match &backdrop.stage {
366                Some(stage) => {
367                    let len = u32::try_from(stage.wgsl.len())
368                        .map_err(|_| WireError::Invalid("backdrop stage"))?;
369                    w.u32(len);
370                    w.bytes(stage.wgsl.as_bytes());
371                    for value in stage.uniforms {
372                        w.f32(value);
373                    }
374                }
375                None => w.u32(0),
376            }
377            scene::encode(&backdrop.below, ids, w.vec())?;
378            Ok(())
379        })
380    }
381
382    /// A section of a kind this crate does not write (a later step's), as
383    /// raw bytes.
384    pub fn raw_section(
385        &mut self,
386        kind: u16,
387        optional: bool,
388        payload: &[u8],
389    ) -> Result<(), WireError> {
390        let mut w = Writer::new(self.out);
391        w.u16(kind);
392        w.u16(if optional { SECTION_OPTIONAL } else { 0 });
393        w.count(payload.len())?;
394        w.bytes(payload);
395        w.align4(payload.len());
396        Ok(())
397    }
398
399    /// Close the record and return its length.
400    pub fn finish(self) -> Result<usize, WireError> {
401        let length = self
402            .out
403            .len()
404            .checked_sub(self.start)
405            .ok_or(WireError::Overflow)?;
406        let at = self.start.checked_add(8).ok_or(WireError::Overflow)?;
407        Writer::new(self.out)
408            .patch_u32(at, u32::try_from(length).map_err(|_| WireError::Overflow)?)?;
409        Ok(length)
410    }
411}
412
413/// A frame, read and validated, with what it costs to draw.
414pub struct Checked {
415    pub frame: Frame,
416    pub cost: SceneCost,
417}
418
419/// Read one frame record from `bytes` (exactly one record) and validate
420/// every scene in it against `limits`. Every byte is read once.
421///
422/// # Errors
423///
424/// The first thing wrong with the record.
425pub fn read(
426    bytes: &[u8],
427    resources: &dyn Resources,
428    limits: &Limits,
429) -> Result<Checked, WireError> {
430    if bytes.len() > limits.frame_bytes as usize {
431        return Err(WireError::OverLimit("frame bytes"));
432    }
433    let mut r = Reader::new(bytes);
434    if r.u32()? != MAGIC {
435        return Err(WireError::Malformed("not a frame record"));
436    }
437    if r.u16()? != crate::PROTOCOL_VERSION {
438        return Err(WireError::Malformed("frame version"));
439    }
440    let flags = r.u16()?;
441    if flags & !FRAME_FULL != 0 {
442        return Err(WireError::Malformed("frame flags"));
443    }
444    if r.u32()? as usize != bytes.len() {
445        return Err(WireError::Malformed("frame length"));
446    }
447    let mut frame = Frame {
448        surface: SurfaceId(r.u32()?),
449        sequence: r.u64()?,
450        width: r.u32()?,
451        height: r.u32()?,
452        base_color: [r.f32()?, r.f32()?, r.f32()?, r.f32()?],
453        full: flags & FRAME_FULL != 0,
454        damage: Vec::new(),
455        scroll_copies: Vec::new(),
456        layers: Vec::new(),
457        order: None,
458        backdrops: Vec::new(),
459    };
460    debug_assert_eq!(bytes.len().saturating_sub(r.remaining()), HEADER_BYTES);
461    if frame.width == 0
462        || frame.height == 0
463        || frame.width > limits.surface_edge
464        || frame.height > limits.surface_edge
465    {
466        return Err(WireError::OverLimit("surface size"));
467    }
468    if !frame.base_color.iter().all(|value| value.is_finite()) {
469        return Err(WireError::Invalid("base colour"));
470    }
471    let mut cost = SceneCost::default();
472    while !r.is_empty() {
473        let kind = r.u16()?;
474        let section_flags = r.u16()?;
475        let length = r.u32()? as usize;
476        let payload = r.take(length)?;
477        r.align4(length)?;
478        if section_flags & !SECTION_OPTIONAL != 0 {
479            return Err(WireError::Malformed("section flags"));
480        }
481        let mut body = Reader::new(payload);
482        match kind {
483            SECTION_DAMAGE => read_damage(&mut body, &mut frame, limits)?,
484            SECTION_SCROLL_COPY => read_copies(&mut body, &mut frame, limits)?,
485            SECTION_LAYER => {
486                if frame.layers.len() >= limits.layers as usize {
487                    return Err(WireError::OverLimit("layers"));
488                }
489                let (layer, layer_cost) = read_layer(&mut body, resources, limits)?;
490                cost = cost.plus(layer_cost);
491                frame.layers.push(layer);
492            }
493            SECTION_ORDER => {
494                let count = body.count(4)?;
495                if count > limits.layers as usize || frame.order.is_some() {
496                    return Err(WireError::OverLimit("layer order"));
497                }
498                let order = (0..count)
499                    .map(|_| body.u32().map(LayerId))
500                    .collect::<Result<Vec<_>, _>>()?;
501                frame.order = Some(order);
502            }
503            SECTION_BACKDROP => {
504                if frame.backdrops.len() >= limits.backdrops as usize {
505                    return Err(WireError::OverLimit("backdrops"));
506                }
507                let (backdrop, below_cost) = read_backdrop(&mut body, resources, limits)?;
508                cost = cost.plus(below_cost);
509                frame.backdrops.push(backdrop);
510            }
511            _ if section_flags & SECTION_OPTIONAL != 0 => continue,
512            _ => return Err(WireError::UnknownSection(kind)),
513        }
514        if !body.is_empty() {
515            return Err(WireError::Malformed("bytes after a section"));
516        }
517    }
518    cost.check(limits)?;
519    Ok(Checked { frame, cost })
520}
521
522fn read_damage(r: &mut Reader<'_>, frame: &mut Frame, limits: &Limits) -> Result<(), WireError> {
523    let count = r.count(16)?;
524    if count.saturating_add(frame.damage.len()) > limits.rects as usize {
525        return Err(WireError::OverLimit("damage rectangles"));
526    }
527    for _ in 0..count {
528        let rect = Rect {
529            x0: r.f32()?,
530            y0: r.f32()?,
531            x1: r.f32()?,
532            y1: r.f32()?,
533        };
534        if !rect.valid() {
535            return Err(WireError::Invalid("damage rectangle"));
536        }
537        frame.damage.push(rect);
538    }
539    Ok(())
540}
541
542fn read_copies(r: &mut Reader<'_>, frame: &mut Frame, limits: &Limits) -> Result<(), WireError> {
543    let count = r.count(24)?;
544    if count.saturating_add(frame.scroll_copies.len()) > limits.rects as usize {
545        return Err(WireError::OverLimit("scroll copies"));
546    }
547    for _ in 0..count {
548        let copy = ScrollCopy {
549            x: r.u32()?,
550            y: r.u32()?,
551            width: r.u32()?,
552            height: r.u32()?,
553            dx: r.i32()?,
554            dy: r.i32()?,
555        };
556        let inside = |origin: u32, extent: u32, delta: i32, limit: u32| {
557            origin.checked_add(extent).is_some_and(|end| end <= limit)
558                && origin
559                    .checked_add_signed(delta)
560                    .and_then(|moved| moved.checked_add(extent))
561                    .is_some_and(|end| end <= limit)
562        };
563        if copy.width == 0
564            || copy.height == 0
565            || !inside(copy.x, copy.width, copy.dx, frame.width)
566            || !inside(copy.y, copy.height, copy.dy, frame.height)
567        {
568            return Err(WireError::Invalid("scroll copy outside the surface"));
569        }
570        frame.scroll_copies.push(copy);
571    }
572    Ok(())
573}
574
575fn read_encoding(
576    r: &mut Reader<'_>,
577    resources: &dyn Resources,
578    limits: &Limits,
579) -> Result<(Encoding, SceneCost), WireError> {
580    let bytes = r.take(r.remaining())?;
581    let encoding = scene::decode(bytes, resources)?;
582    let cost = validate(&encoding, limits)?;
583    Ok((encoding, cost))
584}
585
586fn read_layer(
587    r: &mut Reader<'_>,
588    resources: &dyn Resources,
589    limits: &Limits,
590) -> Result<(LayerUpdate, SceneCost), WireError> {
591    let id = LayerId(r.u32()?);
592    let op = r.u32()?;
593    if op & !0x1ff != 0 {
594        return Err(WireError::Malformed("layer op"));
595    }
596    let transform = Transform {
597        matrix: [r.f32()?, r.f32()?, r.f32()?, r.f32()?],
598        translation: [r.f32()?, r.f32()?],
599    };
600    let opacity = r.f32()?;
601    let clip = Rect {
602        x0: r.f32()?,
603        y0: r.f32()?,
604        x1: r.f32()?,
605        y1: r.f32()?,
606    };
607    let finite = transform
608        .matrix
609        .iter()
610        .chain(&transform.translation)
611        .all(|value| value.is_finite() && value.abs() <= crate::validate::MAX_COORDINATE);
612    if !finite || !(0.0..=1.0).contains(&opacity) || !clip.valid() {
613        return Err(WireError::Invalid("layer properties"));
614    }
615    let (change, cost) = match op & 0xff {
616        0 => {
617            let (content, cost) = read_encoding(r, resources, limits)?;
618            (LayerChange::Content(Box::new(content)), cost)
619        }
620        1 => (LayerChange::Keep, SceneCost::default()),
621        2 => (LayerChange::Remove, SceneCost::default()),
622        _ => return Err(WireError::Malformed("layer op")),
623    };
624    Ok((
625        LayerUpdate {
626            id,
627            change,
628            transform,
629            opacity,
630            clip: (op & (1 << 8) != 0).then_some(clip),
631        },
632        cost,
633    ))
634}
635
636fn read_backdrop(
637    r: &mut Reader<'_>,
638    resources: &dyn Resources,
639    limits: &Limits,
640) -> Result<(Backdrop, SceneCost), WireError> {
641    let image = ImageId(r.u32()?);
642    if resources.image(image).is_none() {
643        return Err(WireError::UnknownResource("a backdrop image"));
644    }
645    let rect = Rect {
646        x0: r.f32()?,
647        y0: r.f32()?,
648        x1: r.f32()?,
649        y1: r.f32()?,
650    };
651    let blur_px = r.f32()?;
652    let cell_px = r.f32()?;
653    let refraction = [r.f32()?, r.f32()?, r.f32()?, r.f32()?];
654    let legible = [r.f32()?, r.f32()?];
655    let sampling = r.u8()?;
656    let ground = [r.f32()?, r.f32()?, r.f32()?, r.f32()?];
657    let stage_len = r.u32()? as usize;
658    let stage = if stage_len == 0 {
659        None
660    } else {
661        if stage_len > MAX_STAGE_SOURCE {
662            return Err(WireError::Invalid("backdrop stage"));
663        }
664        let wgsl = std::str::from_utf8(r.take(stage_len)?)
665            .map_err(|_| WireError::Invalid("backdrop stage"))?
666            .to_owned();
667        let mut uniforms = [0.0; STAGE_FLOATS];
668        for value in &mut uniforms {
669            *value = r.f32()?;
670            if !value.is_finite() {
671                return Err(WireError::Invalid("backdrop stage"));
672            }
673        }
674        Some(BackdropStage { wgsl, uniforms })
675    };
676    let valid = rect.valid()
677        && blur_px.is_finite()
678        && (0.0..=4096.0).contains(&blur_px)
679        && sampling <= 1
680        && cell_px.is_finite()
681        && (0.0..=4096.0).contains(&cell_px)
682        && refraction
683            .iter()
684            .all(|value| value.is_finite() && (0.0..=4096.0).contains(value))
685        && legible
686            .iter()
687            .all(|value| value.is_finite() && (0.0..=1.0).contains(value))
688        && legible[0] <= legible[1]
689        && ground.iter().all(|value| value.is_finite());
690    if !valid {
691        return Err(WireError::Invalid("backdrop"));
692    }
693    let (below, cost) = read_encoding(r, resources, limits)?;
694    Ok((
695        Backdrop {
696            image,
697            rect,
698            blur_px,
699            sampling,
700            cell_px,
701            refraction,
702            legible,
703            ground,
704            stage,
705            below,
706        },
707        cost,
708    ))
709}