use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::addr::Slug;
use crate::e2ee::{CallId, CallKeysInit, E2eeJoin, JoinIdHex, StatusVoiceE2ee};
use crate::error::{Validate, ValidationError};
use crate::http::{Page, Patch};
use crate::id::Id;
use crate::perms::Perms;
use crate::time::Timestamp;
pub const USER_LIMIT_MAX: u8 = 99;
pub const READY_VOICE_STATES_MAX: usize = 5_000;
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum VoiceConnection {
Connecting = "connecting",
Connected = "connected",
}
}
coded_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum VoiceLeaveReason {
Left = "left" => 1,
Disconnected = "disconnected" => 2,
Replaced = "replaced" => 3,
Moved = "moved" => 4,
RemovedByModerator = "removed_by_moderator" => 5,
PermsLost = "perms_lost" => 6,
ChannelArchived = "channel_archived" => 7,
RemovedFromSpace = "removed_from_space" => 8,
TimedOut = "timed_out" => 9,
AccountRemoved = "account_removed" => 10,
SessionRevoked = "session_revoked" => 11,
DeviceRevoked = "device_revoked" => 12,
Orphaned = "orphaned" => 13,
AloneTimeout = "alone_timeout" => 14,
ConnectTimeout = "connect_timeout" => 15,
MediaRestarted = "media_restarted" => 16,
VoiceDisabled = "voice_disabled" => 17,
E2eeSenderIndexStuck = "e2ee_sender_index_stuck" => 18,
CallEnded = "call_ended" => 19,
MediaUnused = "media_unused" => 20,
MediaRevoked = "media_revoked" => 21,
Unresponsive = "unresponsive" => 22,
E2eeUnsupportedClient = "e2ee_unsupported_client" => 23,
RecordingDeclined = "recording_declined" => 24,
RecordingWithdrawn = "recording_withdrawn" => 25,
RecordingConsentTimeout = "recording_consent_timeout" => 26,
SpaceOrphaned = "space_orphaned" => 27,
MediaPathDown = "media_path_down" => 28,
AppUnlinked = "app_unlinked" => 29,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct VoiceState {
pub member_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub space_id: Option<Id>,
pub channel_id: Id,
pub connection: VoiceConnection,
pub secure: bool,
pub self_mute: bool,
pub self_deaf: bool,
pub server_mute: bool,
pub server_deaf: bool,
pub speak_denied: bool,
pub joined_at: Timestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_id: Option<Id>,
#[serde(default)]
pub self_video: bool,
#[serde(default)]
pub self_stream: bool,
}
impl VoiceState {
pub fn new(
member_id: Id,
channel_id: Id,
connection: VoiceConnection,
joined_at: Timestamp,
) -> Self {
VoiceState {
member_id,
space_id: None,
channel_id,
connection,
secure: false,
self_mute: false,
self_deaf: false,
server_mute: false,
server_deaf: false,
speak_denied: false,
joined_at,
call_id: None,
self_video: false,
self_stream: false,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VoiceJoinRequest {
#[serde(default)]
pub self_mute: bool,
#[serde(default)]
pub self_deaf: bool,
#[serde(default)]
pub self_video: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub e2ee: Option<E2eeJoin>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recording_notice: Option<crate::recording::RecordingNotice>,
#[serde(default, skip_serializing_if = "is_false")]
pub call_credential: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
}
impl Validate for VoiceJoinRequest {
fn validate(&self) -> Result<(), ValidationError> {
if let Some(n) = &self.recording_notice {
n.validate().map_err(|e| e.nested("recording_notice"))?;
}
check_join_origin(self.origin.as_deref())?;
check_credential_join(self.call_credential, self.e2ee.as_ref())
}
}
pub(crate) fn check_join_origin(origin: Option<&str>) -> Result<(), ValidationError> {
match origin {
Some(o) if !crate::mgmt::is_app_origin(o) => Err(ValidationError::invalid(
"origin",
"an App origin is wss://<host>[:port] in lower case, without a path",
)),
_ => Ok(()),
}
}
pub(crate) fn check_credential_join(
call_credential: bool,
e2ee: Option<&E2eeJoin>,
) -> Result<(), ValidationError> {
match e2ee {
Some(_) if call_credential => {
Err(ValidationError::invalid("e2ee", "not with call_credential"))
}
Some(e) => e.validate().map_err(|e| e.nested("e2ee")),
None => Ok(()),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct VoiceJoinResponse {
pub url: String,
pub token: String,
pub expires_at: Timestamp,
pub room: CallId,
pub state: VoiceState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub e2ee: Option<CallKeysInit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media: Option<MediaPolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recording: Option<crate::recording::Recording>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stats: Option<CallStatsBeacon>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_credential: Option<CallCredential>,
}
impl VoiceJoinResponse {
pub fn new(
url: impl Into<String>,
token: impl Into<String>,
expires_at: Timestamp,
room: CallId,
state: VoiceState,
) -> Self {
VoiceJoinResponse {
url: url.into(),
token: token.into(),
expires_at,
room,
state,
e2ee: None,
media: None,
call_id: None,
recording: None,
stats: None,
call_credential: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallCredential {
pub token: String,
pub expires_at: Timestamp,
pub join_id: JoinIdHex,
pub device_scope: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallCredentialRenewResponse {
pub token: String,
pub expires_at: Timestamp,
}
pub const CALL_CREDENTIAL_GRACE_MS: u64 = 30_000;
pub const CALL_CREDENTIAL_RENEWS_PER_MINUTE: u32 = 6;
pub const CALL_SOCKETS_PER_MEMBER_MAX: usize = 4;
pub mod call_close {
use super::VoiceLeaveReason;
pub const CALL_ENDED_PREFIX: &str = "call_ended:";
pub const CALL_ENDED: &str = "call_ended";
pub const SIGNED_OUT: &str = "signed_out";
pub const DEACTIVATED: &str = "deactivated";
pub fn call_ended(reason: VoiceLeaveReason) -> String {
format!("{CALL_ENDED_PREFIX}{}", reason.as_str())
}
pub fn reason_of(text: &str) -> Option<String> {
if let Some(r) = text.strip_prefix(CALL_ENDED_PREFIX) {
let ok = !r.is_empty() && r.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
return ok.then(|| r.to_owned());
}
match text {
SIGNED_OUT => Some(VoiceLeaveReason::SessionRevoked.as_str().to_owned()),
DEACTIVATED => Some(VoiceLeaveReason::AccountRemoved.as_str().to_owned()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn close_texts_name_the_reason() {
assert_eq!(
call_ended(VoiceLeaveReason::PermsLost),
"call_ended:perms_lost"
);
assert_eq!(
reason_of("call_ended:perms_lost").as_deref(),
Some("perms_lost")
);
assert_eq!(
reason_of(&call_ended(VoiceLeaveReason::Replaced)).as_deref(),
Some("replaced")
);
assert_eq!(reason_of("signed_out").as_deref(), Some("session_revoked"));
assert_eq!(reason_of("deactivated").as_deref(), Some("account_removed"));
for t in [
"session_revoked",
"call_ended",
"call_ended:",
"call_ended:X y",
"",
] {
assert_eq!(reason_of(t), None, "{t:?}");
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CallStatsBeacon {
pub interval_ms: u32,
#[serde(default, skip_serializing_if = "is_false")]
pub audio_fields: bool,
}
pub const CALL_STATS_INTERVAL_MS: u32 = 15_000;
pub const CALL_STATS_PER_MINUTE: u32 = 6;
pub const CALL_STATS_BODY_MAX_BYTES: usize = 1_024;
pub const CALL_STATS_WINDOW_MAX_MS: u32 = 120_000;
pub const CALL_STATS_FRAMES_MAX: u32 = 360_000;
pub const CALL_STATS_EVENTS_MAX: u32 = 100_000;
pub const CALL_STATS_RTT_MAX_MS: u32 = 60_000;
pub const CALL_STATS_AUDIO_STREAMS_MAX: u32 = 200;
pub const CALL_STATS_AUDIO_PACKETS_MAX: u32 = 1_200_000;
pub const CALL_STATS_AUDIO_JITTER_MAX_MS: u32 = 60_000;
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum CallStatsClient {
Chromium = "chromium",
Firefox = "firefox",
Safari = "safari",
Other = "other",
Native = "native",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum CallStatsCandidate {
Host = "host",
Srflx = "srflx",
Prflx = "prflx",
Relay = "relay",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum CallStatsRelayProtocol {
Udp = "udp",
Tcp = "tcp",
Tls = "tls",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct CallStatsSample {
pub interval_ms: u32,
pub client: CallStatsClient,
pub frames_decoded: u32,
pub frames_dropped: u32,
pub freezes: u32,
pub freeze_ms: u32,
pub decrypt_failures: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub candidate: Option<CallStatsCandidate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub relay_protocol: Option<CallStatsRelayProtocol>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rtt_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_played_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_concealed_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_packets_expected: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_packets_lost: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_jitter_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub audio_longest_gap_ms: Option<u32>,
}
impl CallStatsSample {
pub fn new(client: CallStatsClient) -> Self {
CallStatsSample {
interval_ms: 0,
client,
frames_decoded: 0,
frames_dropped: 0,
freezes: 0,
freeze_ms: 0,
decrypt_failures: 0,
candidate: None,
relay_protocol: None,
rtt_ms: None,
audio_played_ms: None,
audio_concealed_ms: None,
audio_packets_expected: None,
audio_packets_lost: None,
audio_jitter_ms: None,
audio_longest_gap_ms: None,
}
}
}
impl Validate for CallStatsSample {
fn validate(&self) -> Result<(), ValidationError> {
if self.interval_ms == 0 || self.interval_ms > CALL_STATS_WINDOW_MAX_MS {
return Err(ValidationError::invalid(
"interval_ms",
"between 1 and 120000",
));
}
for (field, v, max) in [
("frames_decoded", self.frames_decoded, CALL_STATS_FRAMES_MAX),
("frames_dropped", self.frames_dropped, CALL_STATS_FRAMES_MAX),
("freezes", self.freezes, CALL_STATS_EVENTS_MAX),
(
"decrypt_failures",
self.decrypt_failures,
CALL_STATS_EVENTS_MAX,
),
] {
if v > max {
return Err(ValidationError::invalid(field, "too large for one sample"));
}
}
if u64::from(self.freeze_ms) > u64::from(self.interval_ms) * 25 {
return Err(ValidationError::invalid(
"freeze_ms",
"longer than the window allows",
));
}
if self.rtt_ms.is_some_and(|r| r > CALL_STATS_RTT_MAX_MS) {
return Err(ValidationError::invalid("rtt_ms", "at most 60000"));
}
if self.relay_protocol.is_some() && self.candidate != Some(CallStatsCandidate::Relay) {
return Err(ValidationError::invalid(
"relay_protocol",
"only with a relay candidate",
));
}
self.validate_audio()
}
}
impl CallStatsSample {
pub fn has_audio_fields(&self) -> bool {
self.audio_played_ms.is_some()
|| self.audio_concealed_ms.is_some()
|| self.audio_packets_expected.is_some()
|| self.audio_packets_lost.is_some()
|| self.audio_jitter_ms.is_some()
|| self.audio_longest_gap_ms.is_some()
}
fn validate_audio(&self) -> Result<(), ValidationError> {
let window = u64::from(self.interval_ms);
let ms_max = window * u64::from(CALL_STATS_AUDIO_STREAMS_MAX);
for (field, v) in [
("audio_played_ms", self.audio_played_ms),
("audio_concealed_ms", self.audio_concealed_ms),
] {
if v.is_some_and(|v| u64::from(v) > ms_max) {
return Err(ValidationError::invalid(
field,
"longer than the window allows",
));
}
}
if let (Some(c), Some(p)) = (self.audio_concealed_ms, self.audio_played_ms)
&& c > p
{
return Err(ValidationError::invalid(
"audio_concealed_ms",
"at most audio_played_ms",
));
}
for (field, v) in [
("audio_packets_expected", self.audio_packets_expected),
("audio_packets_lost", self.audio_packets_lost),
] {
if v.is_some_and(|v| v > CALL_STATS_AUDIO_PACKETS_MAX) {
return Err(ValidationError::invalid(field, "too large for one sample"));
}
}
if let (Some(l), Some(e)) = (self.audio_packets_lost, self.audio_packets_expected)
&& l > e
{
return Err(ValidationError::invalid(
"audio_packets_lost",
"at most audio_packets_expected",
));
}
if self
.audio_jitter_ms
.is_some_and(|j| j > CALL_STATS_AUDIO_JITTER_MAX_MS)
{
return Err(ValidationError::invalid("audio_jitter_ms", "at most 60000"));
}
if self
.audio_longest_gap_ms
.is_some_and(|g| u64::from(g) > window)
{
return Err(ValidationError::invalid(
"audio_longest_gap_ms",
"longer than the window",
));
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VoiceSelfStateRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub self_mute: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub self_deaf: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub self_video: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub self_stream: Option<bool>,
}
impl Validate for VoiceSelfStateRequest {
fn validate(&self) -> Result<(), ValidationError> {
if self.self_mute.is_none()
&& self.self_deaf.is_none()
&& self.self_video.is_none()
&& self.self_stream.is_none()
{
return Err(ValidationError::invalid(
"self_mute",
"set at least one of self_mute, self_deaf, self_video and self_stream",
));
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VoiceFlagsRequest {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_mute: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_deaf: Option<bool>,
}
impl Validate for VoiceFlagsRequest {
fn validate(&self) -> Result<(), ValidationError> {
if self.server_mute.is_none() && self.server_deaf.is_none() {
return Err(ValidationError::invalid(
"server_mute",
"set server_mute, server_deaf or both",
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct VoiceFlags {
pub space_id: Id,
pub member_id: Id,
pub server_mute: bool,
pub server_deaf: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VoiceMoveRequest {
#[serde(default, skip_serializing_if = "Patch::is_keep")]
pub channel_id: Patch<Id>,
}
impl Validate for VoiceMoveRequest {
fn validate(&self) -> Result<(), ValidationError> {
if self.channel_id.is_keep() {
return Err(ValidationError::invalid(
"channel_id",
"channel_id is required (null disconnects)",
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct VoiceStateUpdated {
pub member_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub space_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub previous_channel_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<VoiceState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<VoiceLeaveReason>,
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum KeyJoinMode {
Required = "required",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct VoiceMoveKeyJoin {
pub call_id: CallId,
pub join_id: JoinIdHex,
pub key_join: KeyJoinMode,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct VoiceServerUpdated {
pub channel_id: Id,
pub room: CallId,
pub url: String,
pub token: String,
pub expires_at: Timestamp,
pub e2ee: VoiceMoveKeyJoin,
pub reason: VoiceLeaveReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media: Option<MediaPolicy>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub call_id: Option<Id>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recording: Option<crate::recording::Recording>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct ReadyVoiceChannel {
pub id: Id,
pub space_id: Id,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category_id: Option<Id>,
pub slug: Slug,
pub name: String,
pub position: u32,
pub user_limit: u8,
pub my_perms: Perms,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub voice_invites: Vec<crate::voice_notify::VoiceInvite>,
}
impl ReadyVoiceChannel {
pub fn new(
id: Id,
space_id: Id,
slug: Slug,
name: String,
position: u32,
my_perms: Perms,
) -> Self {
ReadyVoiceChannel {
id,
space_id,
category_id: None,
slug,
name,
position,
user_limit: 0,
my_perms,
voice_invites: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct MeVoice {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<VoiceState>,
}
pub type VoiceStatePage = Page<VoiceState>;
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum VoiceEngineState {
Up = "up",
Down = "down",
Draining = "draining",
Syncing = "syncing",
Error = "error",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct VoiceEngineStatus {
pub state: VoiceEngineState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
pub rooms: u64,
pub participants: u64,
pub panics_1h: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub down_since: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_event_at: Option<Timestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_snapshot_at: Option<Timestamp>,
pub drift_fixes_1h: u64,
}
impl VoiceEngineStatus {
pub fn new(state: VoiceEngineState) -> Self {
VoiceEngineStatus {
state,
version: None,
rooms: 0,
participants: 0,
panics_1h: 0,
down_since: None,
last_event_at: None,
last_snapshot_at: None,
drift_fixes_1h: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct VoiceStatus {
pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub public_url: Option<String>,
pub calls: u64,
pub participants: u64,
pub secure_participants: u64,
pub reconnecting: u64,
pub engine: VoiceEngineStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub e2ee: Option<StatusVoiceE2ee>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media_path: Option<crate::mgmt::VoiceMediaPathStatus>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media: Option<VoiceMediaStatus>,
}
impl VoiceStatus {
pub fn new(engine: VoiceEngineStatus) -> Self {
VoiceStatus {
enabled: false,
public_url: None,
calls: 0,
participants: 0,
secure_participants: 0,
reconnecting: 0,
engine,
e2ee: None,
media_path: None,
media: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct VoiceMediaStatus {
pub calls_active: u64,
pub video_publishers: u64,
pub screen_publishers: u64,
pub media_tier: MediaTier,
pub budget_source: BudgetSource,
pub egress_mbps: f64,
pub egress_budget_mbps: u64,
pub forward_estimate_mbps: f64,
pub engine_cpu_pct: Option<f64>,
pub video_enabled: bool,
}
impl VoiceMediaStatus {
pub fn new(media_tier: MediaTier, budget_source: BudgetSource) -> Self {
VoiceMediaStatus {
calls_active: 0,
video_publishers: 0,
screen_publishers: 0,
media_tier,
budget_source,
egress_mbps: 0.0,
egress_budget_mbps: 0,
forward_estimate_mbps: 0.0,
engine_cpu_pct: None,
video_enabled: false,
}
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum BudgetSource {
Engine = "engine",
Estimate = "estimate",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum MediaTier {
Normal = "normal",
Constrained = "constrained",
Critical = "critical",
}
}
unit_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub enum VideoCodec {
Vp8 = "vp8",
H264 = "h264",
Vp9 = "vp9",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LayerHint {
pub rid: String,
pub height: u32,
pub max_kbps: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TrackHint {
pub max_width: u32,
pub max_height: u32,
pub max_fps: u32,
pub layers: Vec<LayerHint>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Vp9Hint {
pub scalability_mode: String,
pub requires_dd: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[non_exhaustive]
pub struct MediaPolicy {
pub tier: MediaTier,
pub video_enabled: bool,
pub e2ee: String,
pub audio_codecs: Vec<String>,
pub codecs: Vec<VideoCodec>,
pub backup_codec: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vp9: Option<Vp9Hint>,
pub camera: TrackHint,
pub screen: TrackHint,
pub dynacast: bool,
pub adaptive_stream: bool,
#[serde(default = "default_allowed")]
pub camera_allowed: bool,
#[serde(default = "default_allowed")]
pub screen_allowed: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub relay_only: bool,
}
impl MediaPolicy {
pub fn new(tier: MediaTier, camera: TrackHint, screen: TrackHint) -> MediaPolicy {
MediaPolicy {
tier,
video_enabled: false,
e2ee: "required".to_owned(),
audio_codecs: vec!["opus".to_owned()],
codecs: Vec::new(),
backup_codec: false,
vp9: None,
camera,
screen,
dynacast: false,
adaptive_stream: false,
camera_allowed: true,
screen_allowed: true,
relay_only: false,
}
}
}
fn default_allowed() -> bool {
true
}
fn is_false(v: &bool) -> bool {
!*v
}
pub mod reasons {
pub const NOT_VOICE_CHANNEL: &str = "not_voice_channel";
pub const CHANNEL_FULL: &str = "channel_full";
pub const NOT_IN_VOICE: &str = "not_in_voice";
pub const AGENTS_NOT_IN_VOICE: &str = "agents_not_in_voice";
pub const TARGET_CANNOT_CONNECT: &str = "target_cannot_connect";
pub const VOICE_DISABLED: &str = "voice_disabled";
pub const VOICE_UNAVAILABLE: &str = "voice_unavailable";
pub const VOICE_CAPACITY: &str = "voice_capacity";
pub const RECORDING_CONSENT_REQUIRED: &str = crate::e2ee::RECORDING_CONSENT_REQUIRED;
pub const VIDEO_DISABLED: &str = "video_disabled";
pub const VIDEO_SLOTS_FULL: &str = "video_slots_full";
pub const SCREEN_SLOTS_FULL: &str = "screen_slots_full";
pub const MEDIA_BUSY: &str = "media_busy";
pub const MEDIA_CAPACITY: &str = "media_capacity";
pub const CALL_STATS_OFF: &str = "call_stats_off";
pub const CHANNEL_CLOSING: &str = "channel_closing";
pub const CHANNEL_ARCHIVED: &str = "channel_archived";
pub const CALL_CREDENTIAL_SCOPE: &str = "call_credential_scope";
pub const CALL_CREDENTIAL_STALE: &str = "call_credential_stale";
pub const CALL_ENDED: &str = "call_ended";
pub const SIGNED_OUT: &str = "signed_out";
pub const EXPIRED: &str = "expired";
pub const ORIGIN_NOT_LISTED: &str = "origin_not_listed";
}
pub mod engine_detail {
pub const DOWN: &str = "down";
pub const DRAINING: &str = "draining";
pub const SYNCING: &str = "syncing";
pub const ERROR: &str = "error";
pub const MEDIA_PATH_DOWN: &str = "media_path_down";
pub const MEDIA_PATH_REASON: &str = "media_path_reason";
}
pub(crate) fn check_user_limit(v: Option<u8>) -> Result<(), ValidationError> {
match v {
Some(n) if n > USER_LIMIT_MAX => Err(ValidationError::invalid(
"user_limit",
format!("user_limit must be 0–{USER_LIMIT_MAX}"),
)),
_ => Ok(()),
}
}