Skip to main content

tilo_actions/remote/
native_media.rs

1//! An app's own place in a workspace's call: joining it, muting, the camera and screen it sends,
2//! and the pictures its view draws.
3//!
4//! A sandboxed app takes part in a call through its device: the device's call service holds the
5//! microphone, camera and screen, asks the person for each the first time, and plays and shows
6//! the call through the workspace's live session it holds. The app says what its person did and
7//! reads the status of the call and the pictures it draws. What a command is for is the
8//! connection's app, its workspace and its grants, decided by the device from the line the
9//! launcher handed the app, never from this wire.
10use serde::{Deserialize, Serialize};
11
12/// One message's bound. A call has no member limit; a status names
13/// each person (64 bytes) and the people whose pictures it shows (64
14/// each), so this carries well over a thousand of them, and a
15/// [`Command::Pictures`] answer always at least one whole picture of the
16/// largest layer ([`MAX_PICTURE_BYTES`] in base64).
17pub const MAX_WIRE_BYTES: usize = 1024 * 1024;
18pub const MAX_INPUTS: usize = 128;
19/// The largest picture one [`Picture`] carries: one encoded tilo-video/1
20/// object.
21pub const MAX_PICTURE_BYTES: usize = 512 * 1024;
22/// Pictures one tile set may ask for at once: what a call view shows.
23pub const MAX_SHOWN: usize = 64;
24/// The longest a [`Command::Pictures`] is held before it is answered
25/// without pictures.
26pub const PICTURES_HOLD: std::time::Duration = std::time::Duration::from_secs(5);
27
28#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(deny_unknown_fields)]
30pub struct Request {
31    pub version: u8,
32    /// The turn this command is in the connection's own order: every command that changes the
33    /// call carries a later one than any before, and a read carries none.
34    pub intent: u64,
35    pub command: Command,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
40pub enum Command {
41    Join {
42        channel_id: String,
43    },
44    SetMuted {
45        muted: bool,
46    },
47    /// Hear nothing of the call and be heard by no one, or stop. Deafening
48    /// mutes the microphone too; undeafening puts it back as it was before,
49    /// and unmuting while deafened undeafens. Everyone in the call sees it.
50    SetDeafened {
51        deafened: bool,
52    },
53    SelectInput {
54        input_id: String,
55    },
56    /// Send this person's camera in the call from another of the device's cameras
57    /// ([`Snapshot::cameras`]). A camera that is on moves to it at once; one that is off starts
58    /// from it when it is turned on.
59    SelectCamera {
60        camera_id: String,
61    },
62    Leave,
63    Status,
64    /// [`Command::Status`] once it differs from the status at `revision`
65    /// ([`Snapshot::revision`]), or after [`WATCH_HOLD`] when nothing
66    /// changed: how an app hears who joins, leaves and talks the moment it
67    /// happens, with one question outstanding instead of a poll.
68    Watch {
69        revision: u64,
70    },
71    /// Turn this person's camera on or off in the call. Turning it on asks
72    /// for the camera through the normal permission prompt, once for as
73    /// long as the person allows it there.
74    SetCamera {
75        on: bool,
76    },
77    /// Share this person's screen in the call, or stop. Starting asks
78    /// through the normal permission prompt.
79    SetScreen {
80        on: bool,
81    },
82    /// The pictures this app shows now, each at the layer that fits where
83    /// it shows it: the call receives exactly these and nothing else.
84    Show {
85        pictures: Vec<Shown>,
86    },
87    /// The pictures received of what [`Command::Show`] asked for since the
88    /// cursor `after` ([`Snapshot::pictures_cursor`]), answered as soon as
89    /// there are any or after [`PICTURES_HOLD`].
90    Pictures {
91        after: u64,
92    },
93    /// How loud this device plays one member (a person id), in
94    /// percent of as they arrive: `0` silences them,
95    /// up to [`MAX_VOLUME_PERCENT`]. Only what this device hears changes;
96    /// nobody else's call does, so it carries no intent.
97    SetVolume {
98        member: String,
99        percent: u16,
100    },
101}
102
103/// The loudest a member is played ([`Command::SetVolume`]): twice as
104/// they arrive.
105pub const MAX_VOLUME_PERCENT: u16 = 200;
106
107/// What a picture shows.
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum PictureSource {
111    Camera,
112    Screen,
113}
114
115/// How large a picture is received: the layer its tile asks for.
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum PictureLayer {
119    /// A face in a filmstrip or a small grid: 320 × 180.
120    Low,
121    /// A tile in a grid: 640 × 360 (cameras only).
122    Mid,
123    /// The active speaker or the stage.
124    High,
125}
126
127/// One picture an app shows: a person's camera or screen at one layer.
128#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
129#[serde(deny_unknown_fields)]
130pub struct Shown {
131    /// The person (user root key, lowercase hex).
132    pub person: String,
133    pub source: PictureSource,
134    pub layer: PictureLayer,
135}
136
137/// One received picture: an encoded tilo-video/1 object of one stream.
138#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140pub struct Picture {
141    /// The person it shows (user root key, lowercase hex).
142    pub person: String,
143    /// The stream it belongs to: one participation's source, for as long
144    /// as that participation lasts. A person on two devices, or back after
145    /// leaving, is another stream; a decoder starts over with each.
146    pub stream: String,
147    pub source: PictureSource,
148    /// The tilo-video/1 object (header and access unit), in base64 on the
149    /// wire.
150    #[serde(with = "base64_bytes")]
151    pub object: Vec<u8>,
152}
153
154impl Picture {
155    #[must_use]
156    pub fn valid(&self) -> bool {
157        person_valid(&self.person)
158            && identifier(&self.stream)
159            && !self.object.is_empty()
160            && self.object.len() <= MAX_PICTURE_BYTES
161    }
162
163    /// The coded picture inside the object, as the tilo-video/1 header
164    /// frames it (version, flags, codec, layer, sequence,
165    /// capture time, width, height, payload length, reserved; 32 bytes), or
166    /// `None` for an object that does not hold together.
167    #[must_use]
168    pub fn unit(&self) -> Option<PictureUnit<'_>> {
169        let header = self.object.get(..PICTURE_HEADER_BYTES)?;
170        let payload = self.object.get(PICTURE_HEADER_BYTES..)?;
171        let u16_at = |at: usize| -> Option<u16> {
172            Some(u16::from_le_bytes(
173                header.get(at..at.checked_add(2)?)?.try_into().ok()?,
174            ))
175        };
176        let length = u32::from_le_bytes(header.get(24..28)?.try_into().ok()?);
177        let codec = match header.get(2)? {
178            1 => PictureCodec::H264,
179            2 => PictureCodec::Vp8,
180            3 => PictureCodec::Vp9,
181            4 => PictureCodec::Av1,
182            _ => return None,
183        };
184        (header.first() == Some(&1)
185            && usize::try_from(length).ok() == Some(payload.len())
186            && !payload.is_empty())
187        .then_some(PictureUnit {
188            keyframe: (header.get(1)? & 1) == 1,
189            codec,
190            width: u16_at(20)?,
191            height: u16_at(22)?,
192            payload,
193        })
194    }
195}
196
197/// Bytes of the tilo-video/1 header in front of every coded picture.
198pub const PICTURE_HEADER_BYTES: usize = 32;
199
200impl PictureUnit<'_> {
201    /// This unit as a tilo-video/1 object of `layer`, the `sequence`th of its
202    /// track, captured `timestamp_us` into the stream: what a call carries.
203    #[must_use]
204    pub fn to_object(&self, layer: PictureLayer, sequence: u64, timestamp_us: u64) -> Vec<u8> {
205        let length = u32::try_from(self.payload.len()).unwrap_or(u32::MAX);
206        let mut object =
207            Vec::with_capacity(PICTURE_HEADER_BYTES.saturating_add(self.payload.len()));
208        object.extend_from_slice(&[
209            1,
210            u8::from(self.keyframe),
211            match self.codec {
212                PictureCodec::H264 => 1,
213                PictureCodec::Vp8 => 2,
214                PictureCodec::Vp9 => 3,
215                PictureCodec::Av1 => 4,
216            },
217            match layer {
218                PictureLayer::Low => 0,
219                PictureLayer::Mid => 1,
220                PictureLayer::High => 2,
221            },
222        ]);
223        object.extend_from_slice(&sequence.to_le_bytes());
224        object.extend_from_slice(&timestamp_us.to_le_bytes());
225        object.extend_from_slice(&self.width.to_le_bytes());
226        object.extend_from_slice(&self.height.to_le_bytes());
227        object.extend_from_slice(&length.to_le_bytes());
228        object.extend_from_slice(&[0; 4]);
229        object.extend_from_slice(self.payload);
230        object
231    }
232}
233
234/// How a picture is coded.
235#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236pub enum PictureCodec {
237    H264,
238    Vp8,
239    Vp9,
240    Av1,
241}
242
243/// The coded picture a [`Picture`] carries.
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub struct PictureUnit<'a> {
246    /// A decoder can start here.
247    pub keyframe: bool,
248    pub codec: PictureCodec,
249    pub width: u16,
250    pub height: u16,
251    /// The access unit.
252    pub payload: &'a [u8],
253}
254
255mod base64_bytes {
256    use base64::Engine as _;
257    use serde::{Deserialize as _, Deserializer, Serializer};
258
259    pub(super) fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
260        serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(bytes))
261    }
262
263    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
264        deserializer: D,
265    ) -> Result<Vec<u8>, D::Error> {
266        let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
267        base64::engine::general_purpose::STANDARD
268            .decode(text.as_bytes())
269            .map_err(serde::de::Error::custom)
270    }
271}
272
273/// The longest a [`Command::Watch`] is held before it is answered unchanged.
274pub const WATCH_HOLD: std::time::Duration = std::time::Duration::from_secs(20);
275
276/// How long an app waits for one command's answer: past the hold the device may keep it for,
277/// by the transport's slack ([`REPLY_LOST`], [`WATCH_LOST`], [`PICTURES_LOST`]).
278#[must_use]
279pub fn lost(request: &Request) -> std::time::Duration {
280    match request.command {
281        Command::Watch { .. } => WATCH_LOST,
282        Command::Pictures { .. } => PICTURES_LOST,
283        _ => REPLY_LOST,
284    }
285}
286
287/// The longest a command may take to be answered. A page's shell carries the
288/// command on to its host over the relay, so its answer is a network round
289/// trip: a shorter bound answers "timed out" while the host is still working,
290/// and the app gives up on a call that was about to start.
291pub const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
292/// Nothing arrived this long after a command was sent, so the app gives it up.
293/// Past [`REPLY_TIMEOUT`]: an app never gives up on what the shell may still
294/// answer.
295pub const REPLY_LOST: std::time::Duration =
296    REPLY_TIMEOUT.saturating_add(std::time::Duration::from_secs(5));
297/// A watch is held up to [`WATCH_HOLD`]; past this the shell's answer is lost.
298pub const WATCH_DEADLINE: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_TIMEOUT);
299/// A watch unanswered this long was lost: an app gives up after the shell.
300pub const WATCH_LOST: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_LOST);
301/// Pictures are collected up to [`PICTURES_HOLD`]; past this the collection
302/// is answered without them.
303pub const PICTURES_DEADLINE: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_TIMEOUT);
304/// A collection unanswered this long was lost: an app gives up after the shell.
305pub const PICTURES_LOST: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_LOST);
306
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub enum State {
310    Unavailable,
311    Idle,
312    Preparing,
313    Joining,
314    Live,
315    Reconnecting,
316    Ended,
317}
318
319#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
320#[serde(rename_all = "snake_case")]
321pub enum Issue {
322    Unavailable,
323    Denied,
324    PermissionDenied,
325    SourceLost,
326    CaptureFailed,
327    TransportFailed,
328    SessionEnded,
329    Stale,
330    /// The person did not allow the camera.
331    CameraDenied,
332    /// The camera could not start, or stopped.
333    CameraLost,
334    /// The person did not allow sharing the screen.
335    ScreenDenied,
336    /// Sharing the screen could not start, or stopped.
337    ScreenLost,
338    /// This device cannot take part in calls at all (the platform has no
339    /// audio capture and playout): no retry helps.
340    Unsupported,
341}
342
343#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
344#[serde(deny_unknown_fields)]
345pub struct Input {
346    pub id: String,
347    pub label: String,
348}
349
350/// Whose pictures this device publishes and receives now, never an inferred
351/// member roster.
352#[derive(Clone, Debug, Default, PartialEq, Eq)]
353pub struct Inventory {
354    pub revision: Option<u64>,
355    /// The person whose camera or screen this device publishes, if it does.
356    pub publication: Option<String>,
357    /// The people whose pictures this device receives, sorted and distinct.
358    pub publishers: Vec<String>,
359}
360impl Inventory {
361    pub fn valid(&self) -> bool {
362        if self
363            .publishers
364            .windows(2)
365            .any(|pair| matches!(pair, [left, right] if left >= right))
366        {
367            return false;
368        }
369        if self.revision.is_none() && (self.publication.is_some() || !self.publishers.is_empty()) {
370            return false;
371        }
372        self.publication.as_deref().is_none_or(person_valid)
373            && self
374                .publishers
375                .iter()
376                .all(|publisher| person_valid(publisher))
377    }
378}
379
380#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
381#[serde(deny_unknown_fields)]
382#[allow(
383    clippy::struct_excessive_bools,
384    reason = "each bool is its own wire field of the status: muted, capturing, camera, screen, deafened"
385)]
386pub struct Snapshot {
387    pub version: u8,
388    pub state: State,
389    pub muted: bool,
390    pub capture_active: bool,
391    pub input_id: Option<String>,
392    pub inputs: Vec<Input>,
393    pub issue: Option<Issue>,
394    #[serde(default)]
395    pub inventory_revision: Option<u64>,
396    #[serde(default)]
397    pub publication: Option<String>,
398    #[serde(default)]
399    pub publishers: Vec<String>,
400    /// Who is in the call of each of the app's workspace's voice channels, before
401    /// and while this device takes part: what a voice channel shows.
402    #[serde(default)]
403    pub rosters: Vec<Roster>,
404    /// Who this device's call hears talking now (person ids, sorted and
405    /// distinct), this person among them while
406    /// their microphone is heard: what the speaking rings show.
407    #[serde(default)]
408    pub speaking: Vec<String>,
409    /// This person's camera is on in the call. Like every field added
410    /// after the first version, written only when set, so an app that does
411    /// not know it reads a status without it.
412    #[serde(default, skip_serializing_if = "is_false")]
413    pub camera: bool,
414    /// This person shares a screen in the call.
415    #[serde(default, skip_serializing_if = "is_false")]
416    pub screen: bool,
417    /// This person is deafened: the call plays nothing here, and they are
418    /// muted.
419    #[serde(default, skip_serializing_if = "is_false")]
420    pub deafened: bool,
421    /// Advances whenever anything above changes; what a
422    /// [`Command::Watch`] waits past.
423    #[serde(default)]
424    pub revision: u64,
425    /// The pictures a [`Command::Pictures`] answer carries, oldest first;
426    /// empty in every other answer.
427    #[serde(default, skip_serializing_if = "Vec::is_empty")]
428    pub pictures: Vec<Picture>,
429    /// Where the next [`Command::Pictures`] continues.
430    #[serde(default, skip_serializing_if = "is_zero")]
431    pub pictures_cursor: u64,
432    /// This call service draws the pictures itself, where the view shows them (a browser page
433    /// decodes them): no [`Command::Pictures`] is asked of it, and none is collected. The
434    /// tiles still say what they show ([`Command::Show`]), which is what the service receives.
435    #[serde(default, skip_serializing_if = "is_false")]
436    pub pictures_local: bool,
437    /// How loud this device plays each member of the call, in percent of as they arrive
438    /// ([`Command::SetVolume`]), sorted by person: what the view's volume controls show, and
439    /// nobody else's call hears.
440    #[serde(default, skip_serializing_if = "Vec::is_empty")]
441    pub volumes: Vec<Volume>,
442    /// The cameras this device's call can send from ([`Command::SelectCamera`]), labelled as the
443    /// person chooses between them.
444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
445    pub cameras: Vec<Input>,
446    /// The camera the call sends from, or would once the camera is on.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub camera_id: Option<String>,
449}
450
451/// How loud this device plays one member of a call, in percent of as they arrive
452/// ([`Command::SetVolume`]).
453#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
454#[serde(deny_unknown_fields)]
455pub struct Volume {
456    /// The person, as the call names them.
457    pub member: String,
458    /// Percent of as they arrive, up to [`MAX_VOLUME_PERCENT`].
459    pub percent: u16,
460}
461
462/// The people in one voice channel's call.
463#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
464#[serde(deny_unknown_fields)]
465pub struct Roster {
466    pub channel_id: String,
467    /// Person ids (a user root key in lowercase hex), sorted and distinct:
468    /// a person on two devices is in the call once.
469    pub people: Vec<String>,
470    #[serde(default, skip_serializing_if = "Vec::is_empty")]
471    pub cameras: Vec<String>,
472    /// Those of `people` who share a screen, sorted and distinct.
473    #[serde(default, skip_serializing_if = "Vec::is_empty")]
474    pub screens: Vec<String>,
475    /// Those of `people` whose microphone is off, sorted and distinct;
476    /// someone who may not speak in the call counts as muted.
477    #[serde(default, skip_serializing_if = "Vec::is_empty")]
478    pub muted: Vec<String>,
479    /// Those of `people` who are deafened, sorted and distinct; each of
480    /// them is muted too.
481    #[serde(default, skip_serializing_if = "Vec::is_empty")]
482    pub deafened: Vec<String>,
483    /// The services a bridge carries this call to (`discord`), sorted and
484    /// distinct: everyone in the call is heard there too. A bridge is no
485    /// person, so it is in none of the lists above.
486    #[serde(default, skip_serializing_if = "Vec::is_empty")]
487    pub bridges: Vec<String>,
488    /// The people a bridge carries into the call from another service, each a
489    /// member of it of their own: in `people` above by this id, and shown by
490    /// the name and picture they have there.
491    #[serde(default, skip_serializing_if = "Vec::is_empty")]
492    pub bridged: Vec<BridgedPerson>,
493}
494
495/// One person a bridge carries into a call: who they are there, and the member
496/// of `Roster::people` they are in it as.
497#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(deny_unknown_fields)]
499pub struct BridgedPerson {
500    /// The person (their root key or stand-in publisher, lowercase hex): in
501    /// the roster's `people` like everyone else.
502    pub person: String,
503    /// The service the call reaches them through (`discord`).
504    pub service: String,
505    /// Their account there.
506    pub account: String,
507    /// The name they are shown by.
508    pub name: String,
509    /// BLAKE3 hex of their picture in the workspace's content store, when it is
510    /// held.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub avatar: Option<String>,
513}
514
515impl Roster {
516    #[must_use]
517    pub fn valid(&self) -> bool {
518        let among = |subset: &[String]| {
519            people_valid(subset)
520                && subset
521                    .iter()
522                    .all(|person| self.people.binary_search(person).is_ok())
523        };
524        identifier(&self.channel_id)
525            && people_valid(&self.people)
526            && among(&self.cameras)
527            && among(&self.screens)
528            && among(&self.muted)
529            && among(&self.deafened)
530            && self
531                .deafened
532                .iter()
533                .all(|person| self.muted.binary_search(person).is_ok())
534            && self.bridges.iter().all(|service| service_valid(service))
535            && self.bridges.is_sorted_by(|a, b| a < b)
536            && self.bridged.iter().all(|person| {
537                person_valid(&person.person)
538                    && self.people.binary_search(&person.person).is_ok()
539                    && service_valid(&person.service)
540                    && !person.account.trim().is_empty()
541                    && person.account.len() <= 64
542                    && !person.name.trim().is_empty()
543                    && person.name.chars().count() <= 80
544                    && person.avatar.as_deref().is_none_or(hex32)
545            })
546            && self.bridged.is_sorted_by(|a, b| a.person < b.person)
547    }
548}
549
550/// A service a bridge reaches, as its messages name it: `discord`.
551fn service_valid(service: &str) -> bool {
552    (1..=32).contains(&service.len())
553        && service
554            .bytes()
555            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
556}
557
558/// A person id: a user root key in lowercase hex.
559fn person_valid(person: &str) -> bool {
560    hex32(person)
561}
562
563/// 32 bytes in lowercase hex: a key or a BLAKE3 hash.
564fn hex32(value: &str) -> bool {
565    value.len() == 64
566        && value
567            .bytes()
568            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
569}
570
571/// Person ids: a user root key in lowercase hex each, sorted and distinct.
572fn people_valid(people: &[String]) -> bool {
573    people.iter().all(|person| person_valid(person))
574        && people
575            .windows(2)
576            .all(|pair| matches!(pair, [left, right] if left < right))
577}
578
579impl Request {
580    #[must_use]
581    pub const fn new(command: Command) -> Self {
582        Self {
583            version: 1,
584            intent: 0,
585            command,
586        }
587    }
588
589    #[must_use]
590    pub fn valid(&self) -> bool {
591        self.version == 1
592            && match &self.command {
593                Command::Join { channel_id } => identifier(channel_id),
594                Command::SelectInput { input_id } => identifier(input_id),
595                Command::SelectCamera { camera_id } => identifier(camera_id),
596                Command::Show { pictures } => {
597                    pictures.len() <= MAX_SHOWN
598                        && pictures.iter().all(|shown| {
599                            person_valid(&shown.person)
600                                && (shown.source == PictureSource::Camera
601                                    || shown.layer != PictureLayer::Mid)
602                        })
603                        && pictures.windows(2).all(|pair| {
604                            matches!(pair, [left, right]
605                                if (&left.person, left.source) < (&right.person, right.source))
606                        })
607                }
608                Command::SetVolume { member, percent } => {
609                    person_valid(member) && *percent <= MAX_VOLUME_PERCENT
610                }
611                Command::SetMuted { .. }
612                | Command::SetDeafened { .. }
613                | Command::SetCamera { .. }
614                | Command::SetScreen { .. }
615                | Command::Leave
616                | Command::Status
617                | Command::Watch { .. }
618                | Command::Pictures { .. } => true,
619            }
620    }
621
622    /// Whether this command carries an intent: everything that changes
623    /// the call. A status, a watch and collecting pictures only read, and
624    /// saying which pictures are shown or how loud someone plays changes
625    /// nothing of the call itself.
626    #[must_use]
627    pub const fn carries_intent(&self) -> bool {
628        !matches!(
629            self.command,
630            Command::Status
631                | Command::Watch { .. }
632                | Command::Pictures { .. }
633                | Command::Show { .. }
634                | Command::SetVolume { .. }
635        )
636    }
637
638    pub fn dispatch_valid(&self) -> bool {
639        self.valid()
640            && match self.command {
641                Command::Status
642                | Command::Watch { .. }
643                | Command::Pictures { .. }
644                | Command::Show { .. }
645                | Command::SetVolume { .. } => self.intent == 0,
646                Command::Leave => self.intent > 0,
647                _ => self.intent > 0 && self.intent < u64::MAX,
648            }
649    }
650
651    /// Encode a valid command for the wire.
652    pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
653        encode(self, self.valid())
654    }
655
656    /// Decode one bounded, valid command.
657    pub fn decode(bytes: &[u8]) -> Result<Self, &'static str> {
658        let value: Self = decode(bytes)?;
659        value
660            .valid()
661            .then_some(value)
662            .ok_or("invalid local media command")
663    }
664}
665
666impl Snapshot {
667    #[must_use]
668    pub const fn unavailable() -> Self {
669        Self {
670            version: 1,
671            state: State::Unavailable,
672            muted: true,
673            capture_active: false,
674            input_id: None,
675            inputs: Vec::new(),
676            issue: Some(Issue::Unavailable),
677            inventory_revision: None,
678            publication: None,
679            publishers: Vec::new(),
680            rosters: Vec::new(),
681            speaking: Vec::new(),
682            camera: false,
683            screen: false,
684            deafened: false,
685            revision: 0,
686            pictures: Vec::new(),
687            pictures_cursor: 0,
688            volumes: Vec::new(),
689            cameras: Vec::new(),
690            camera_id: None,
691            pictures_local: false,
692        }
693    }
694
695    #[must_use]
696    pub fn valid(&self) -> bool {
697        let mut ids = std::collections::BTreeSet::new();
698        let inventory = Inventory {
699            revision: self.inventory_revision,
700            publication: self.publication.clone(),
701            publishers: self.publishers.clone(),
702        };
703        self.version == 1
704            && inventory.valid()
705            && (self.state == State::Live
706                || (self.inventory_revision.is_none()
707                    && self.publication.is_none()
708                    && self.publishers.is_empty()))
709            && (!self.capture_active
710                || (!self.muted && self.state == State::Live && self.input_id.is_some()))
711            // Deafened is muted, and only in a call.
712            && (!self.deafened
713                || (self.muted
714                    && !matches!(self.state, State::Unavailable | State::Idle | State::Ended)))
715            && self.input_id.as_deref().is_none_or(identifier)
716            && self.rosters.iter().all(Roster::valid)
717            && self.speaking.iter().all(|id| person_valid(id))
718            && self
719                .speaking
720                .windows(2)
721                .all(|pair| matches!(pair, [left, right] if left < right))
722            // Nothing shows outside a call.
723            && (!matches!(self.state, State::Unavailable | State::Idle | State::Ended)
724                || (!self.camera && !self.screen))
725            && self.pictures.iter().all(Picture::valid)
726            && self
727                .rosters
728                .windows(2)
729                .all(|pair| matches!(pair, [left, right] if left.channel_id < right.channel_id))
730            && self.inputs.len() <= MAX_INPUTS
731            && self.inputs.iter().all(|input| {
732                identifier(&input.id) && identifier(&input.label) && ids.insert(&input.id)
733            })
734            && self.cameras.len() <= MAX_INPUTS
735            && {
736                let mut cameras = std::collections::BTreeSet::new();
737                self.cameras.iter().all(|camera| {
738                    identifier(&camera.id) && identifier(&camera.label) && cameras.insert(&camera.id)
739                })
740            }
741            && self.camera_id.as_deref().is_none_or(identifier)
742            && self.volumes.iter().all(|volume| {
743                person_valid(&volume.member) && volume.percent <= MAX_VOLUME_PERCENT
744            })
745            && self
746                .volumes
747                .windows(2)
748                .all(|pair| matches!(pair, [left, right] if left.member < right.member))
749    }
750
751    /// Encode a valid status for the wire.
752    pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
753        encode(self, self.valid())
754    }
755
756    /// Decode one bounded, valid status.
757    pub fn decode(bytes: &[u8]) -> Result<Self, &'static str> {
758        let value: Self = decode(bytes)?;
759        value
760            .valid()
761            .then_some(value)
762            .ok_or("invalid local media status")
763    }
764}
765
766#[allow(
767    clippy::trivially_copy_pass_by_ref,
768    reason = "serde's skip_serializing_if hands the field by reference"
769)]
770const fn is_false(value: &bool) -> bool {
771    !*value
772}
773
774#[allow(
775    clippy::trivially_copy_pass_by_ref,
776    reason = "serde's skip_serializing_if hands the field by reference"
777)]
778const fn is_zero(value: &u64) -> bool {
779    *value == 0
780}
781
782fn identifier(value: &str) -> bool {
783    !value.is_empty() && value.len() <= 256 && !value.chars().any(char::is_control)
784}
785
786fn encode(value: &impl Serialize, valid: bool) -> Result<Vec<u8>, &'static str> {
787    if !valid {
788        return Err("invalid local media value");
789    }
790    let bytes = serde_json::to_vec(value).map_err(|_| "invalid local media value")?;
791    (bytes.len() <= MAX_WIRE_BYTES)
792        .then_some(bytes)
793        .ok_or("local media value exceeds bound")
794}
795
796fn decode<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, &'static str> {
797    if bytes.len() > MAX_WIRE_BYTES {
798        return Err("local media value exceeds bound");
799    }
800    serde_json::from_slice(bytes).map_err(|_| "invalid local media value")
801}
802
803#[cfg(test)]
804mod tests;