1use serde::{Deserialize, Serialize};
11
12pub const MAX_WIRE_BYTES: usize = 1024 * 1024;
18pub const MAX_INPUTS: usize = 128;
19pub const MAX_PICTURE_BYTES: usize = 512 * 1024;
22pub const MAX_SHOWN: usize = 64;
24pub 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 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 SetDeafened {
51 deafened: bool,
52 },
53 SelectInput {
54 input_id: String,
55 },
56 SelectCamera {
60 camera_id: String,
61 },
62 Leave,
63 Status,
64 Watch {
69 revision: u64,
70 },
71 SetCamera {
75 on: bool,
76 },
77 SetScreen {
80 on: bool,
81 },
82 Show {
85 pictures: Vec<Shown>,
86 },
87 Pictures {
91 after: u64,
92 },
93 SetVolume {
98 member: String,
99 percent: u16,
100 },
101}
102
103pub const MAX_VOLUME_PERCENT: u16 = 200;
106
107#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum PictureLayer {
119 Low,
121 Mid,
123 High,
125}
126
127#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
129#[serde(deny_unknown_fields)]
130pub struct Shown {
131 pub person: String,
133 pub source: PictureSource,
134 pub layer: PictureLayer,
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140pub struct Picture {
141 pub person: String,
143 pub stream: String,
147 pub source: PictureSource,
148 #[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 #[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
197pub const PICTURE_HEADER_BYTES: usize = 32;
199
200impl PictureUnit<'_> {
201 #[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(×tamp_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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
236pub enum PictureCodec {
237 H264,
238 Vp8,
239 Vp9,
240 Av1,
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub struct PictureUnit<'a> {
246 pub keyframe: bool,
248 pub codec: PictureCodec,
249 pub width: u16,
250 pub height: u16,
251 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
273pub const WATCH_HOLD: std::time::Duration = std::time::Duration::from_secs(20);
275
276#[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
287pub const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
292pub const REPLY_LOST: std::time::Duration =
296 REPLY_TIMEOUT.saturating_add(std::time::Duration::from_secs(5));
297pub const WATCH_DEADLINE: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_TIMEOUT);
299pub const WATCH_LOST: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_LOST);
301pub const PICTURES_DEADLINE: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_TIMEOUT);
304pub 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 CameraDenied,
332 CameraLost,
334 ScreenDenied,
336 ScreenLost,
338 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
353pub struct Inventory {
354 pub revision: Option<u64>,
355 pub publication: Option<String>,
357 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 #[serde(default)]
403 pub rosters: Vec<Roster>,
404 #[serde(default)]
408 pub speaking: Vec<String>,
409 #[serde(default, skip_serializing_if = "is_false")]
413 pub camera: bool,
414 #[serde(default, skip_serializing_if = "is_false")]
416 pub screen: bool,
417 #[serde(default, skip_serializing_if = "is_false")]
420 pub deafened: bool,
421 #[serde(default)]
424 pub revision: u64,
425 #[serde(default, skip_serializing_if = "Vec::is_empty")]
428 pub pictures: Vec<Picture>,
429 #[serde(default, skip_serializing_if = "is_zero")]
431 pub pictures_cursor: u64,
432 #[serde(default, skip_serializing_if = "is_false")]
436 pub pictures_local: bool,
437 #[serde(default, skip_serializing_if = "Vec::is_empty")]
441 pub volumes: Vec<Volume>,
442 #[serde(default, skip_serializing_if = "Vec::is_empty")]
445 pub cameras: Vec<Input>,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub camera_id: Option<String>,
449}
450
451#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
454#[serde(deny_unknown_fields)]
455pub struct Volume {
456 pub member: String,
458 pub percent: u16,
460}
461
462#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
464#[serde(deny_unknown_fields)]
465pub struct Roster {
466 pub channel_id: String,
467 pub people: Vec<String>,
470 #[serde(default, skip_serializing_if = "Vec::is_empty")]
471 pub cameras: Vec<String>,
472 #[serde(default, skip_serializing_if = "Vec::is_empty")]
474 pub screens: Vec<String>,
475 #[serde(default, skip_serializing_if = "Vec::is_empty")]
478 pub muted: Vec<String>,
479 #[serde(default, skip_serializing_if = "Vec::is_empty")]
482 pub deafened: Vec<String>,
483 #[serde(default, skip_serializing_if = "Vec::is_empty")]
487 pub bridges: Vec<String>,
488 #[serde(default, skip_serializing_if = "Vec::is_empty")]
492 pub bridged: Vec<BridgedPerson>,
493}
494
495#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
498#[serde(deny_unknown_fields)]
499pub struct BridgedPerson {
500 pub person: String,
503 pub service: String,
505 pub account: String,
507 pub name: String,
509 #[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
550fn 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
558fn person_valid(person: &str) -> bool {
560 hex32(person)
561}
562
563fn 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
571fn 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 #[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 pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
653 encode(self, self.valid())
654 }
655
656 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 && (!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 && (!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 pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
753 encode(self, self.valid())
754 }
755
756 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;