use serde::{Deserialize, Serialize};
pub const MAX_WIRE_BYTES: usize = 1024 * 1024;
pub const MAX_INPUTS: usize = 128;
pub const MAX_PICTURE_BYTES: usize = 512 * 1024;
pub const MAX_SHOWN: usize = 64;
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,
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,
},
SetDeafened {
deafened: bool,
},
SelectInput {
input_id: String,
},
SelectCamera {
camera_id: String,
},
Leave,
Status,
Watch {
revision: u64,
},
SetCamera {
on: bool,
},
SetScreen {
on: bool,
},
Show {
pictures: Vec<Shown>,
},
Pictures {
after: u64,
},
SetVolume {
member: String,
percent: u16,
},
}
pub const MAX_VOLUME_PERCENT: u16 = 200;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PictureSource {
Camera,
Screen,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PictureLayer {
Low,
Mid,
High,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Shown {
pub person: String,
pub source: PictureSource,
pub layer: PictureLayer,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Picture {
pub person: String,
pub stream: String,
pub source: PictureSource,
#[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
}
#[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,
})
}
}
pub const PICTURE_HEADER_BYTES: usize = 32;
impl PictureUnit<'_> {
#[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(×tamp_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
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureCodec {
H264,
Vp8,
Vp9,
Av1,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureUnit<'a> {
pub keyframe: bool,
pub codec: PictureCodec,
pub width: u16,
pub height: u16,
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)
}
}
pub const WATCH_HOLD: std::time::Duration = std::time::Duration::from_secs(20);
#[must_use]
pub fn lost(request: &Request) -> std::time::Duration {
match request.command {
Command::Watch { .. } => WATCH_LOST,
Command::Pictures { .. } => PICTURES_LOST,
_ => REPLY_LOST,
}
}
pub const REPLY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
pub const REPLY_LOST: std::time::Duration =
REPLY_TIMEOUT.saturating_add(std::time::Duration::from_secs(5));
pub const WATCH_DEADLINE: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_TIMEOUT);
pub const WATCH_LOST: std::time::Duration = WATCH_HOLD.saturating_add(REPLY_LOST);
pub const PICTURES_DEADLINE: std::time::Duration = PICTURES_HOLD.saturating_add(REPLY_TIMEOUT);
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,
CameraDenied,
CameraLost,
ScreenDenied,
ScreenLost,
Unsupported,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
pub id: String,
pub label: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Inventory {
pub revision: Option<u64>,
pub publication: Option<String>,
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>,
#[serde(default)]
pub rosters: Vec<Roster>,
#[serde(default)]
pub speaking: Vec<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub camera: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub screen: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub deafened: bool,
#[serde(default)]
pub revision: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub pictures: Vec<Picture>,
#[serde(default, skip_serializing_if = "is_zero")]
pub pictures_cursor: u64,
#[serde(default, skip_serializing_if = "is_false")]
pub pictures_local: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub volumes: Vec<Volume>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cameras: Vec<Input>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub camera_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Volume {
pub member: String,
pub percent: u16,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Roster {
pub channel_id: String,
pub people: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cameras: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub screens: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub muted: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub deafened: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bridges: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bridged: Vec<BridgedPerson>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BridgedPerson {
pub person: String,
pub service: String,
pub account: String,
pub name: String,
#[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)
}
}
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'-')
}
fn person_valid(person: &str) -> bool {
hex32(person)
}
fn hex32(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
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,
}
}
#[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,
}
}
pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
encode(self, self.valid())
}
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()))
&& (!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))
&& (!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))
}
pub fn encode(&self) -> Result<Vec<u8>, &'static str> {
encode(self, self.valid())
}
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;