Skip to main content

tilo_render_protocol/
control.rs

1//! Messages on the control channel between an app and its render service.
2//!
3//! The channel is small and ordered: frames themselves travel through the
4//! ring (`shm`), and the control channel says where ("frame N is at offset O")
5//! and what became of them ("frame N is in buffer B", "frame N was
6//! dropped, because …", "frame N was presented at T"). Descriptors ride along
7//! where a message names one: the ring with the hello, an image's memfd with
8//! its registration, the render buffers with their announcement.
9//!
10//! Messages are postcard-encoded; one message is one `SOCK_SEQPACKET` packet.
11
12use serde::{Deserialize, Serialize};
13
14use crate::{FontId, ImageId, Limits, SurfaceId, WireError};
15
16/// Largest encoded message either side sends or accepts.
17pub const MAX_MESSAGE_BYTES: usize = 16 * 1024;
18
19/// Most descriptors one message carries.
20pub const MAX_MESSAGE_FDS: usize = 4;
21
22/// Longest font path an app may name.
23pub const MAX_FONT_PATH: usize = 1024;
24
25/// Pixel layout of an uploaded image.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub enum ImageFormat {
28    Rgba8,
29    Bgra8,
30}
31
32/// How an uploaded image's alpha is encoded.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
34pub enum AlphaType {
35    Straight,
36    Premultiplied,
37}
38
39/// A buffer format both the compositor and the app's surface take: a DRM
40/// fourcc and modifier, as the compositor advertised them to the app.
41#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
42pub struct DmabufFormat {
43    pub fourcc: u32,
44    pub modifier: u64,
45}
46
47/// What an app sends.
48#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
49pub enum AppMessage {
50    /// The first message, with the ring's memfd. `version` is the newest the
51    /// app speaks.
52    Hello {
53        version: u16,
54    },
55    /// A new ring, with its memfd, replacing the current one; sent only when
56    /// the service holds no frame of the old one (a frame outgrew it).
57    Ring,
58    /// A surface the app renders through the service. `formats` are the
59    /// linear formats the compositor accepts from this app; `opaque` says
60    /// whether the surface ignores alpha.
61    CreateSurface {
62        surface: SurfaceId,
63        opaque: bool,
64        formats: Vec<DmabufFormat>,
65    },
66    DestroySurface {
67        surface: SurfaceId,
68    },
69    /// Frame `sequence` of a surface is the record at `offset..offset + len`
70    /// in the ring.
71    Frame {
72        sequence: u64,
73        offset: u64,
74        len: u32,
75    },
76    /// The compositor released `buffer` of `surface`: the service may draw
77    /// into it again.
78    Released {
79        surface: SurfaceId,
80        generation: u32,
81        buffer: u32,
82    },
83    /// An image's pixels, in the sealed memfd that comes with this message,
84    /// tightly packed.
85    RegisterImage {
86        image: ImageId,
87        width: u32,
88        height: u32,
89        format: ImageFormat,
90        alpha: AlphaType,
91    },
92    DropImage {
93        image: ImageId,
94    },
95    /// A font from the shared read-only view, by its path there.
96    RegisterFontFile {
97        font: FontId,
98        path: String,
99        index: u32,
100    },
101    /// A font the app holds in memory, in the sealed memfd that comes with
102    /// this message.
103    RegisterFontData {
104        font: FontId,
105        index: u32,
106    },
107    DropFont {
108        font: FontId,
109    },
110    /// The compositor presented (or discarded) frame `sequence`; for the
111    /// app's frame timeline in the service.
112    Presented {
113        surface: SurfaceId,
114        sequence: u64,
115        presented_ns: u64,
116        refresh_ns: u64,
117        discarded: bool,
118    },
119    /// A file of the product font catalog, by the SHA-256 its manifest pins
120    /// (lowercase hex), from the digests the service's welcome lists. Every
121    /// process names a catalog face the same way wherever its own namespace
122    /// put the catalog, and the service maps its own copy of the file.
123    RegisterCatalogFont {
124        font: FontId,
125        sha256: String,
126        index: u32,
127    },
128}
129
130/// Why a frame or a request was not served.
131#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
132pub enum Refusal {
133    /// The record or a resource broke the protocol; nothing was drawn.
134    Invalid(String),
135    /// Over one of the app's limits; nothing was drawn.
136    OverLimit(String),
137    /// The GPU failed the frame; the app should send a full frame again.
138    RenderFailed(String),
139    /// Retired: a frame over the app's GPU budget is held until the overrun has
140    /// been waited out, never refused. A service that still sends this drew
141    /// nothing; the app sends a full frame again.
142    Throttled,
143}
144
145impl From<WireError> for Refusal {
146    fn from(error: WireError) -> Self {
147        match error {
148            WireError::OverLimit(what) => Self::OverLimit(what.to_owned()),
149            other => Self::Invalid(other.to_string()),
150        }
151    }
152}
153
154/// Where a buffer's pixels live.
155#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
156pub enum BufferKind {
157    /// A dma-buf with this format; attach it with `zwp_linux_dmabuf_v1`.
158    Dmabuf(DmabufFormat),
159    /// Shared memory in `wl_shm` format `format` (`argb8888` = 0,
160    /// `xrgb8888` = 1, or a fourcc); attach it with `wl_shm`. Used when the
161    /// service has no GPU.
162    Shm { format: u32 },
163}
164
165/// One buffer of a surface: the layout of its single plane.
166#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
167pub struct Plane {
168    pub offset: u32,
169    pub stride: u32,
170}
171
172/// The device a render service draws on, in wgpu's words (`AdapterInfo`'s
173/// name, device type, backend and driver, as `Debug` prints the enums).
174#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
175pub struct Renderer {
176    pub name: String,
177    /// `Cpu` when frames are rasterised in software.
178    pub device_type: String,
179    pub backend: String,
180    pub driver: String,
181}
182
183/// What the service sends.
184#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
185pub enum ServiceMessage {
186    /// Answer to the hello: the version both speak, the app's limits, the
187    /// catalog files the service has (by their pinned SHA-256), and the font
188    /// directories it may name other fonts in by path. Only a font in neither
189    /// is uploaded.
190    Welcome {
191        version: u16,
192        limits: Limits,
193        catalog: Vec<String>,
194        font_roots: Vec<String>,
195        /// What draws this app's frames, which the app names in its log as
196        /// a window drawing on its own GPU names its adapter.
197        renderer: Renderer,
198    },
199    /// The buffers `surface` is drawn into from now on, one descriptor each,
200    /// in order. A new generation replaces the previous one (a resize).
201    Buffers {
202        surface: SurfaceId,
203        generation: u32,
204        width: u32,
205        height: u32,
206        kind: BufferKind,
207        planes: Vec<Plane>,
208    },
209    /// Frame `sequence` is drawn in `buffer`: attach it with `damage` (in
210    /// buffer pixels; empty means all of it).
211    FrameReady {
212        surface: SurfaceId,
213        sequence: u64,
214        generation: u32,
215        buffer: u32,
216        damage: Vec<[i32; 4]>,
217        /// GPU time the frame took, in microseconds (0 when unmeasured).
218        gpu_us: u32,
219    },
220    /// Frame `sequence` was not drawn; the ring space it used is free.
221    FrameDropped { sequence: u64, why: Refusal },
222    /// A request other than a frame was refused. The connection stays up.
223    Refused { why: Refusal },
224}
225
226pub fn encode<T: Serialize>(message: &T) -> Result<Vec<u8>, WireError> {
227    let bytes = postcard::to_allocvec(message).map_err(|_| WireError::Malformed("message"))?;
228    if bytes.len() > MAX_MESSAGE_BYTES {
229        return Err(WireError::OverLimit("message size"));
230    }
231    Ok(bytes)
232}
233
234/// Decode a message from the channel.
235pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T, WireError> {
236    if bytes.len() > MAX_MESSAGE_BYTES {
237        return Err(WireError::OverLimit("message size"));
238    }
239    let (message, rest) =
240        postcard::take_from_bytes(bytes).map_err(|_| WireError::Malformed("message"))?;
241    if !rest.is_empty() {
242        return Err(WireError::Malformed("bytes after a message"));
243    }
244    Ok(message)
245}