tilo-actions 0.5.1

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! An app's own place in a workspace's call: joining it, muting, the camera and screen it sends,
//! and the pictures its view draws.
//!
//! A sandboxed app takes part in a call through its device: the device's call service holds the
//! microphone, camera and screen, asks the person for each the first time, and plays and shows
//! the call through the workspace's live session it holds. The app says what its person did and
//! reads the status of the call and the pictures it draws. What a command is for is the
//! connection's app, its workspace and its grants, decided by the device from the line the
//! launcher handed the app, never from this wire.
use serde::{Deserialize, Serialize};

/// One message's bound. A call has no member limit; a status names
/// each person (64 bytes) and the people whose pictures it shows (64
/// each), so this carries well over a thousand of them, and a
/// [`Command::Pictures`] answer always at least one whole picture of the
/// largest layer ([`MAX_PICTURE_BYTES`] in base64).
pub const MAX_WIRE_BYTES: usize = 1024 * 1024;
pub const MAX_INPUTS: usize = 128;
/// The largest picture one [`Picture`] carries: one encoded tilo-video/1
/// object.
pub const MAX_PICTURE_BYTES: usize = 512 * 1024;
/// Pictures one tile set may ask for at once: what a call view shows.
pub const MAX_SHOWN: usize = 64;
/// The longest a [`Command::Pictures`] is held before it is answered
/// without pictures.
pub const PICTURES_HOLD: std::time::Duration = std::time::Duration::from_secs(5);

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
    pub version: u8,
    /// The turn this command is in the connection's own order: every command that changes the
    /// call carries a later one than any before, and a read carries none.
    pub intent: u64,
    pub command: Command,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Command {
    Join {
        channel_id: String,
    },
    SetMuted {
        muted: bool,
    },
    /// Hear nothing of the call and be heard by no one, or stop. Deafening
    /// mutes the microphone too; undeafening puts it back as it was before,
    /// and unmuting while deafened undeafens. Everyone in the call sees it.
    SetDeafened {
        deafened: bool,
    },
    SelectInput {
        input_id: String,
    },
    /// Send this person's camera in the call from another of the device's cameras
    /// ([`Snapshot::cameras`]). A camera that is on moves to it at once; one that is off starts
    /// from it when it is turned on.
    SelectCamera {
        camera_id: String,
    },
    Leave,
    Status,
    /// [`Command::Status`] once it differs from the status at `revision`
    /// ([`Snapshot::revision`]), or after [`WATCH_HOLD`] when nothing
    /// changed: how an app hears who joins, leaves and talks the moment it
    /// happens, with one question outstanding instead of a poll.
    Watch {
        revision: u64,
    },
    /// Turn this person's camera on or off in the call. Turning it on asks
    /// for the camera through the normal permission prompt, once for as
    /// long as the person allows it there.
    SetCamera {
        on: bool,
    },
    /// Share this person's screen in the call, or stop. Starting asks
    /// through the normal permission prompt.
    SetScreen {
        on: bool,
    },
    /// The pictures this app shows now, each at the layer that fits where
    /// it shows it: the call receives exactly these and nothing else.
    Show {
        pictures: Vec<Shown>,
    },
    /// The pictures received of what [`Command::Show`] asked for since the
    /// cursor `after` ([`Snapshot::pictures_cursor`]), answered as soon as
    /// there are any or after [`PICTURES_HOLD`].
    Pictures {
        after: u64,
    },
    /// How loud this device plays one member (a person id), in
    /// percent of as they arrive: `0` silences them,
    /// up to [`MAX_VOLUME_PERCENT`]. Only what this device hears changes;
    /// nobody else's call does, so it carries no intent.
    SetVolume {
        member: String,
        percent: u16,
    },
}

/// The loudest a member is played ([`Command::SetVolume`]): twice as
/// they arrive.
pub const MAX_VOLUME_PERCENT: u16 = 200;

/// What a picture shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PictureSource {
    Camera,
    Screen,
}

/// How large a picture is received: the layer its tile asks for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PictureLayer {
    /// A face in a filmstrip or a small grid: 320 × 180.
    Low,
    /// A tile in a grid: 640 × 360 (cameras only).
    Mid,
    /// The active speaker or the stage.
    High,
}

/// One picture an app shows: a person's camera or screen at one layer.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Shown {
    /// The person (user root key, lowercase hex).
    pub person: String,
    pub source: PictureSource,
    pub layer: PictureLayer,
}

/// One received picture: an encoded tilo-video/1 object of one stream.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Picture {
    /// The person it shows (user root key, lowercase hex).
    pub person: String,
    /// The stream it belongs to: one participation's source, for as long
    /// as that participation lasts. A person on two devices, or back after
    /// leaving, is another stream; a decoder starts over with each.
    pub stream: String,
    pub source: PictureSource,
    /// The tilo-video/1 object (header and access unit), in base64 on the
    /// wire.
    #[serde(with = "base64_bytes")]
    pub object: Vec<u8>,
}

impl Picture {
    #[must_use]
    pub fn valid(&self) -> bool {
        person_valid(&self.person)
            && identifier(&self.stream)
            && !self.object.is_empty()
            && self.object.len() <= MAX_PICTURE_BYTES
    }

    /// The coded picture inside the object, as the tilo-video/1 header
    /// frames it (version, flags, codec, layer, sequence,
    /// capture time, width, height, payload length, reserved; 32 bytes), or
    /// `None` for an object that does not hold together.
    #[must_use]
    pub fn unit(&self) -> Option<PictureUnit<'_>> {
        let header = self.object.get(..PICTURE_HEADER_BYTES)?;
        let payload = self.object.get(PICTURE_HEADER_BYTES..)?;
        let u16_at = |at: usize| -> Option<u16> {
            Some(u16::from_le_bytes(
                header.get(at..at.checked_add(2)?)?.try_into().ok()?,
            ))
        };
        let length = u32::from_le_bytes(header.get(24..28)?.try_into().ok()?);
        let codec = match header.get(2)? {
            1 => PictureCodec::H264,
            2 => PictureCodec::Vp8,
            3 => PictureCodec::Vp9,
            4 => PictureCodec::Av1,
            _ => return None,
        };
        (header.first() == Some(&1)
            && usize::try_from(length).ok() == Some(payload.len())
            && !payload.is_empty())
        .then_some(PictureUnit {
            keyframe: (header.get(1)? & 1) == 1,
            codec,
            width: u16_at(20)?,
            height: u16_at(22)?,
            payload,
        })
    }
}

/// Bytes of the tilo-video/1 header in front of every coded picture.
pub const PICTURE_HEADER_BYTES: usize = 32;

impl PictureUnit<'_> {
    /// This unit as a tilo-video/1 object of `layer`, the `sequence`th of its
    /// track, captured `timestamp_us` into the stream: what a call carries.
    #[must_use]
    pub fn to_object(&self, layer: PictureLayer, sequence: u64, timestamp_us: u64) -> Vec<u8> {
        let length = u32::try_from(self.payload.len()).unwrap_or(u32::MAX);
        let mut object =
            Vec::with_capacity(PICTURE_HEADER_BYTES.saturating_add(self.payload.len()));
        object.extend_from_slice(&[
            1,
            u8::from(self.keyframe),
            match self.codec {
                PictureCodec::H264 => 1,
                PictureCodec::Vp8 => 2,
                PictureCodec::Vp9 => 3,
                PictureCodec::Av1 => 4,
            },
            match layer {
                PictureLayer::Low => 0,
                PictureLayer::Mid => 1,
                PictureLayer::High => 2,
            },
        ]);
        object.extend_from_slice(&sequence.to_le_bytes());
        object.extend_from_slice(&timestamp_us.to_le_bytes());
        object.extend_from_slice(&self.width.to_le_bytes());
        object.extend_from_slice(&self.height.to_le_bytes());
        object.extend_from_slice(&length.to_le_bytes());
        object.extend_from_slice(&[0; 4]);
        object.extend_from_slice(self.payload);
        object
    }
}

/// How a picture is coded.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureCodec {
    H264,
    Vp8,
    Vp9,
    Av1,
}

/// The coded picture a [`Picture`] carries.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureUnit<'a> {
    /// A decoder can start here.
    pub keyframe: bool,
    pub codec: PictureCodec,
    pub width: u16,
    pub height: u16,
    /// The access unit.
    pub payload: &'a [u8],
}

mod base64_bytes {
    use base64::Engine as _;
    use serde::{Deserialize as _, Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(bytes))
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Vec<u8>, D::Error> {
        let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
        base64::engine::general_purpose::STANDARD
            .decode(text.as_bytes())
            .map_err(serde::de::Error::custom)
    }
}

/// The longest a [`Command::Watch`] is held before it is answered unchanged.
pub const WATCH_HOLD: std::time::Duration = std::time::Duration::from_secs(20);

/// How long an app waits for one command's answer: past the hold the device may keep it for,
/// by the transport's slack ([`REPLY_LOST`], [`WATCH_LOST`], [`PICTURES_LOST`]).
#[must_use]
pub fn lost(request: &Request) -> std::time::Duration {
    match request.command {
        Command::Watch { .. } => WATCH_LOST,
        Command::Pictures { .. } => PICTURES_LOST,
        _ => REPLY_LOST,
    }
}

/// The longest a command may take to be answered. A page's shell carries the
/// command on to its host over the relay, so its answer is a network round
/// trip: a shorter bound answers "timed out" while the host is still working,
/// and the app gives up on a call that was about to start.
pub const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
/// Nothing arrived this long after a command was sent, so the app gives it up.
/// Past [`REPLY_TIMEOUT`]: an app never gives up on what the shell may still
/// answer.
pub const REPLY_LOST: std::time::Duration =
    REPLY_TIMEOUT.saturating_add(std::time::Duration::from_secs(5));
/// A watch is held up to [`WATCH_HOLD`]; past this the shell's answer is lost.
pub const WATCH_DEADLINE: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_TIMEOUT);
/// A watch unanswered this long was lost: an app gives up after the shell.
pub const WATCH_LOST: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_LOST);
/// Pictures are collected up to [`PICTURES_HOLD`]; past this the collection
/// is answered without them.
pub const PICTURES_DEADLINE: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_TIMEOUT);
/// A collection unanswered this long was lost: an app gives up after the shell.
pub const PICTURES_LOST: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_LOST);

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
    Unavailable,
    Idle,
    Preparing,
    Joining,
    Live,
    Reconnecting,
    Ended,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Issue {
    Unavailable,
    Denied,
    PermissionDenied,
    SourceLost,
    CaptureFailed,
    TransportFailed,
    SessionEnded,
    Stale,
    /// The person did not allow the camera.
    CameraDenied,
    /// The camera could not start, or stopped.
    CameraLost,
    /// The person did not allow sharing the screen.
    ScreenDenied,
    /// Sharing the screen could not start, or stopped.
    ScreenLost,
    /// This device cannot take part in calls at all (the platform has no
    /// audio capture and playout): no retry helps.
    Unsupported,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
    pub id: String,
    pub label: String,
}

/// Whose pictures this device publishes and receives now, never an inferred
/// member roster.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Inventory {
    pub revision: Option<u64>,
    /// The person whose camera or screen this device publishes, if it does.
    pub publication: Option<String>,
    /// The people whose pictures this device receives, sorted and distinct.
    pub publishers: Vec<String>,
}
impl Inventory {
    pub fn valid(&self) -> bool {
        if self
            .publishers
            .windows(2)
            .any(|pair| matches!(pair, [left, right] if left >= right))
        {
            return false;
        }
        if self.revision.is_none() && (self.publication.is_some() || !self.publishers.is_empty()) {
            return false;
        }
        self.publication.as_deref().is_none_or(person_valid)
            && self
                .publishers
                .iter()
                .all(|publisher| person_valid(publisher))
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "each bool is its own wire field of the status: muted, capturing, camera, screen, deafened"
)]
pub struct Snapshot {
    pub version: u8,
    pub state: State,
    pub muted: bool,
    pub capture_active: bool,
    pub input_id: Option<String>,
    pub inputs: Vec<Input>,
    pub issue: Option<Issue>,
    #[serde(default)]
    pub inventory_revision: Option<u64>,
    #[serde(default)]
    pub publication: Option<String>,
    #[serde(default)]
    pub publishers: Vec<String>,
    /// Who is in the call of each of the app's workspace's voice channels, before
    /// and while this device takes part: what a voice channel shows.
    #[serde(default)]
    pub rosters: Vec<Roster>,
    /// Who this device's call hears talking now (person ids, sorted and
    /// distinct), this person among them while
    /// their microphone is heard: what the speaking rings show.
    #[serde(default)]
    pub speaking: Vec<String>,
    /// This person's camera is on in the call. Like every field added
    /// after the first version, written only when set, so an app that does
    /// not know it reads a status without it.
    #[serde(default, skip_serializing_if = "is_false")]
    pub camera: bool,
    /// This person shares a screen in the call.
    #[serde(default, skip_serializing_if = "is_false")]
    pub screen: bool,
    /// This person is deafened: the call plays nothing here, and they are
    /// muted.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deafened: bool,
    /// Advances whenever anything above changes; what a
    /// [`Command::Watch`] waits past.
    #[serde(default)]
    pub revision: u64,
    /// The pictures a [`Command::Pictures`] answer carries, oldest first;
    /// empty in every other answer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub pictures: Vec<Picture>,
    /// Where the next [`Command::Pictures`] continues.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub pictures_cursor: u64,
    /// This call service draws the pictures itself, where the view shows them (a browser page
    /// decodes them): no [`Command::Pictures`] is asked of it, and none is collected. The
    /// tiles still say what they show ([`Command::Show`]), which is what the service receives.
    #[serde(default, skip_serializing_if = "is_false")]
    pub pictures_local: bool,
    /// How loud this device plays each member of the call, in percent of as they arrive
    /// ([`Command::SetVolume`]), sorted by person: what the view's volume controls show, and
    /// nobody else's call hears.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub volumes: Vec<Volume>,
    /// The cameras this device's call can send from ([`Command::SelectCamera`]), labelled as the
    /// person chooses between them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cameras: Vec<Input>,
    /// The camera the call sends from, or would once the camera is on.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub camera_id: Option<String>,
}

/// How loud this device plays one member of a call, in percent of as they arrive
/// ([`Command::SetVolume`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Volume {
    /// The person, as the call names them.
    pub member: String,
    /// Percent of as they arrive, up to [`MAX_VOLUME_PERCENT`].
    pub percent: u16,
}

/// The people in one voice channel's call.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Roster {
    pub channel_id: String,
    /// Person ids (a user root key in lowercase hex), sorted and distinct:
    /// a person on two devices is in the call once.
    pub people: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cameras: Vec<String>,
    /// Those of `people` who share a screen, sorted and distinct.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub screens: Vec<String>,
    /// Those of `people` whose microphone is off, sorted and distinct;
    /// someone who may not speak in the call counts as muted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub muted: Vec<String>,
    /// Those of `people` who are deafened, sorted and distinct; each of
    /// them is muted too.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deafened: Vec<String>,
    /// The services a bridge carries this call to (`discord`), sorted and
    /// distinct: everyone in the call is heard there too. A bridge is no
    /// person, so it is in none of the lists above.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bridges: Vec<String>,
    /// The people a bridge carries into the call from another service, each a
    /// member of it of their own: in `people` above by this id, and shown by
    /// the name and picture they have there.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bridged: Vec<BridgedPerson>,
}

/// One person a bridge carries into a call: who they are there, and the member
/// of `Roster::people` they are in it as.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BridgedPerson {
    /// The person (their root key or stand-in publisher, lowercase hex): in
    /// the roster's `people` like everyone else.
    pub person: String,
    /// The service the call reaches them through (`discord`).
    pub service: String,
    /// Their account there.
    pub account: String,
    /// The name they are shown by.
    pub name: String,
    /// BLAKE3 hex of their picture in the workspace's content store, when it is
    /// held.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub avatar: Option<String>,
}

impl Roster {
    #[must_use]
    pub fn valid(&self) -> bool {
        let among = |subset: &[String]| {
            people_valid(subset)
                && subset
                    .iter()
                    .all(|person| self.people.binary_search(person).is_ok())
        };
        identifier(&self.channel_id)
            && people_valid(&self.people)
            && among(&self.cameras)
            && among(&self.screens)
            && among(&self.muted)
            && among(&self.deafened)
            && self
                .deafened
                .iter()
                .all(|person| self.muted.binary_search(person).is_ok())
            && self.bridges.iter().all(|service| service_valid(service))
            && self.bridges.is_sorted_by(|a, b| a < b)
            && self.bridged.iter().all(|person| {
                person_valid(&person.person)
                    && self.people.binary_search(&person.person).is_ok()
                    && service_valid(&person.service)
                    && !person.account.trim().is_empty()
                    && person.account.len() <= 64
                    && !person.name.trim().is_empty()
                    && person.name.chars().count() <= 80
                    && person.avatar.as_deref().is_none_or(hex32)
            })
            && self.bridged.is_sorted_by(|a, b| a.person < b.person)
    }
}

/// A service a bridge reaches, as its messages name it: `discord`.
fn service_valid(service: &str) -> bool {
    (1..=32).contains(&service.len())
        && service
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

/// A person id: a user root key in lowercase hex.
fn person_valid(person: &str) -> bool {
    hex32(person)
}

/// 32 bytes in lowercase hex: a key or a BLAKE3 hash.
fn hex32(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// Person ids: a user root key in lowercase hex each, sorted and distinct.
fn people_valid(people: &[String]) -> bool {
    people.iter().all(|person| person_valid(person))
        && people
            .windows(2)
            .all(|pair| matches!(pair, [left, right] if left < right))
}

impl Request {
    #[must_use]
    pub const fn new(command: Command) -> Self {
        Self {
            version: 1,
            intent: 0,
            command,
        }
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        self.version == 1
            && match &self.command {
                Command::Join { channel_id } => identifier(channel_id),
                Command::SelectInput { input_id } => identifier(input_id),
                Command::SelectCamera { camera_id } => identifier(camera_id),
                Command::Show { pictures } => {
                    pictures.len() <= MAX_SHOWN
                        && pictures.iter().all(|shown| {
                            person_valid(&shown.person)
                                && (shown.source == PictureSource::Camera
                                    || shown.layer != PictureLayer::Mid)
                        })
                        && pictures.windows(2).all(|pair| {
                            matches!(pair, [left, right]
                                if (&left.person, left.source) < (&right.person, right.source))
                        })
                }
                Command::SetVolume { member, percent } => {
                    person_valid(member) && *percent <= MAX_VOLUME_PERCENT
                }
                Command::SetMuted { .. }
                | Command::SetDeafened { .. }
                | Command::SetCamera { .. }
                | Command::SetScreen { .. }
                | Command::Leave
                | Command::Status
                | Command::Watch { .. }
                | Command::Pictures { .. } => true,
            }
    }

    /// Whether this command carries an intent: everything that changes
    /// the call. A status, a watch and collecting pictures only read, and
    /// saying which pictures are shown or how loud someone plays changes
    /// nothing of the call itself.
    #[must_use]
    pub const fn carries_intent(&self) -> bool {
        !matches!(
            self.command,
            Command::Status
                | Command::Watch { .. }
                | Command::Pictures { .. }
                | Command::Show { .. }
                | Command::SetVolume { .. }
        )
    }

    pub fn dispatch_valid(&self) -> bool {
        self.valid()
            && match self.command {
                Command::Status
                | Command::Watch { .. }
                | Command::Pictures { .. }
                | Command::Show { .. }
                | Command::SetVolume { .. } => self.intent == 0,
                Command::Leave => self.intent > 0,
                _ => self.intent > 0 && self.intent < u64::MAX,
            }
    }

    /// Encode a valid command for the wire.
    pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
        encode(self, self.valid())
    }

    /// Decode one bounded, valid command.
    pub fn decode(bytes: &[u8]) -> Result<Self, &'static str> {
        let value: Self = decode(bytes)?;
        value
            .valid()
            .then_some(value)
            .ok_or("invalid local media command")
    }
}

impl Snapshot {
    #[must_use]
    pub const fn unavailable() -> Self {
        Self {
            version: 1,
            state: State::Unavailable,
            muted: true,
            capture_active: false,
            input_id: None,
            inputs: Vec::new(),
            issue: Some(Issue::Unavailable),
            inventory_revision: None,
            publication: None,
            publishers: Vec::new(),
            rosters: Vec::new(),
            speaking: Vec::new(),
            camera: false,
            screen: false,
            deafened: false,
            revision: 0,
            pictures: Vec::new(),
            pictures_cursor: 0,
            volumes: Vec::new(),
            cameras: Vec::new(),
            camera_id: None,
            pictures_local: false,
        }
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        let mut ids = std::collections::BTreeSet::new();
        let inventory = Inventory {
            revision: self.inventory_revision,
            publication: self.publication.clone(),
            publishers: self.publishers.clone(),
        };
        self.version == 1
            && inventory.valid()
            && (self.state == State::Live
                || (self.inventory_revision.is_none()
                    && self.publication.is_none()
                    && self.publishers.is_empty()))
            && (!self.capture_active
                || (!self.muted && self.state == State::Live && self.input_id.is_some()))
            // Deafened is muted, and only in a call.
            && (!self.deafened
                || (self.muted
                    && !matches!(self.state, State::Unavailable | State::Idle | State::Ended)))
            && self.input_id.as_deref().is_none_or(identifier)
            && self.rosters.iter().all(Roster::valid)
            && self.speaking.iter().all(|id| person_valid(id))
            && self
                .speaking
                .windows(2)
                .all(|pair| matches!(pair, [left, right] if left < right))
            // Nothing shows outside a call.
            && (!matches!(self.state, State::Unavailable | State::Idle | State::Ended)
                || (!self.camera && !self.screen))
            && self.pictures.iter().all(Picture::valid)
            && self
                .rosters
                .windows(2)
                .all(|pair| matches!(pair, [left, right] if left.channel_id < right.channel_id))
            && self.inputs.len() <= MAX_INPUTS
            && self.inputs.iter().all(|input| {
                identifier(&input.id) && identifier(&input.label) && ids.insert(&input.id)
            })
            && self.cameras.len() <= MAX_INPUTS
            && {
                let mut cameras = std::collections::BTreeSet::new();
                self.cameras.iter().all(|camera| {
                    identifier(&camera.id) && identifier(&camera.label) && cameras.insert(&camera.id)
                })
            }
            && self.camera_id.as_deref().is_none_or(identifier)
            && self.volumes.iter().all(|volume| {
                person_valid(&volume.member) && volume.percent <= MAX_VOLUME_PERCENT
            })
            && self
                .volumes
                .windows(2)
                .all(|pair| matches!(pair, [left, right] if left.member < right.member))
    }

    /// Encode a valid status for the wire.
    pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
        encode(self, self.valid())
    }

    /// Decode one bounded, valid status.
    pub fn decode(bytes: &[u8]) -> Result<Self, &'static str> {
        let value: Self = decode(bytes)?;
        value
            .valid()
            .then_some(value)
            .ok_or("invalid local media status")
    }
}

#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if hands the field by reference"
)]
const fn is_false(value: &bool) -> bool {
    !*value
}

#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if hands the field by reference"
)]
const fn is_zero(value: &u64) -> bool {
    *value == 0
}

fn identifier(value: &str) -> bool {
    !value.is_empty() && value.len() <= 256 && !value.chars().any(char::is_control)
}

fn encode(value: &impl Serialize, valid: bool) -> Result<Vec<u8>, &'static str> {
    if !valid {
        return Err("invalid local media value");
    }
    let bytes = serde_json::to_vec(value).map_err(|_| "invalid local media value")?;
    (bytes.len() <= MAX_WIRE_BYTES)
        .then_some(bytes)
        .ok_or("local media value exceeds bound")
}

fn decode<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, &'static str> {
    if bytes.len() > MAX_WIRE_BYTES {
        return Err("local media value exceeds bound");
    }
    serde_json::from_slice(bytes).map_err(|_| "invalid local media value")
}

#[cfg(test)]
mod tests;