use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use bytes::Bytes;
use serde::Serialize;
use tokio::sync::{broadcast, mpsc, oneshot};
use crate::config::ClientConfig;
use crate::e2ee::E2eeProvider;
use crate::engine;
use crate::provider::{
ConsentRequired, JoinProvider, JoinRequest, ProviderError, RecordingControl,
};
use crate::stats::{CallStatsReport, PlayoutStats, StatsWindow};
use sew_proto::recording::RecordingTrigger;
pub(crate) const SEND_QUEUE: usize = 50;
pub(crate) const RECV_QUEUE: usize = 1024;
pub(crate) const VIDEO_RECV_QUEUE: usize = 256;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EndReason {
Left,
SigninRequired,
Network,
E2eeRefused,
CredentialLost,
CredentialExpired,
Kicked,
RoomClosed,
Removed(String),
Refused(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
#[non_exhaustive]
pub enum CallState {
Connecting,
Connected,
Reconnecting {
attempt: u32,
},
ConsentRequired {
recording_id: String,
notice_version: u32,
},
Ended {
reason: EndReason,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Participant {
pub identity: String,
pub member_id: Option<String>,
pub is_self: bool,
pub muted: bool,
pub deafened: bool,
pub server_muted: bool,
pub server_deafened: bool,
pub speak_denied: bool,
pub recorder: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub camera: Option<crate::video::VideoTrackView>,
#[serde(skip_serializing_if = "Option::is_none")]
pub screen: Option<crate::video::VideoTrackView>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RecordingConsent {
Pending,
Granted,
Declined,
Withdrawn,
}
impl RecordingConsent {
pub fn from_sew(c: Option<sew_proto::recording::Consent>) -> RecordingConsent {
use sew_proto::recording::Consent as C;
match c {
None | Some(C::Pending) => RecordingConsent::Pending,
Some(C::Granted) => RecordingConsent::Granted,
Some(C::Withdrawn) => RecordingConsent::Withdrawn,
Some(_) => RecordingConsent::Declined,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct RecordingMember {
pub member_id: String,
pub consent: RecordingConsent,
pub recorded: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallRecording {
pub recording_id: String,
pub auto: bool,
pub started_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub started_at: Option<sew_proto::time::Timestamp>,
pub audio_keep_days: u16,
pub my_consent: RecordingConsent,
pub consent_prompt: Option<sew_proto::recording::ConsentPrompt>,
pub participants: Vec<RecordingMember>,
pub trigger: RecordingTrigger,
pub required: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub my_controls: Option<ServerControls>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ServerControls {
pub can_record: bool,
pub can_stop: bool,
pub rev: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub record_unavailable: Option<sew_proto::recording::RecordUnavailable>,
}
impl ServerControls {
pub fn from_sew(c: &sew_proto::recording::RecordingControls) -> ServerControls {
ServerControls {
can_record: c.can_record,
can_stop: c.can_stop,
rev: c.rev,
record_unavailable: c.record_unavailable,
}
}
pub fn new(can_record: bool, can_stop: bool) -> ServerControls {
ServerControls {
can_record,
can_stop,
rev: 0,
record_unavailable: None,
}
}
}
fn trigger_of(r: &sew_proto::recording::Recording) -> RecordingTrigger {
if r.auto && r.trigger == RecordingTrigger::Manual {
RecordingTrigger::Auto
} else {
r.trigger
}
}
fn prompt_required(p: &sew_proto::recording::ConsentPrompt) -> bool {
p.required
}
impl CallRecording {
pub fn from_sew(r: &sew_proto::recording::Recording) -> CallRecording {
use sew_proto::recording::Capture;
let trigger = trigger_of(r);
CallRecording {
recording_id: r.id.to_string(),
auto: r.auto,
started_by: Some(r.started_by.to_string()),
started_at: Some(r.started_at),
audio_keep_days: r.audio_keep_days,
my_consent: RecordingConsent::from_sew(r.my_consent),
consent_prompt: r.consent_prompt.clone(),
participants: r
.participants
.iter()
.map(|p| RecordingMember {
member_id: p.member_id.to_string(),
consent: RecordingConsent::from_sew(Some(p.consent)),
recorded: p.capture == Some(Capture::Recorded),
})
.collect(),
trigger,
required: trigger == RecordingTrigger::Required
|| r.consent_prompt.as_ref().is_some_and(prompt_required),
my_controls: r.my_controls.as_ref().map(ServerControls::from_sew),
}
}
pub fn from_consent_required(c: &ConsentRequired) -> CallRecording {
match &c.recording {
Some(r) => {
let mut out = CallRecording::from_sew(r);
out.consent_prompt = Some(c.consent_prompt.clone());
out.my_consent = RecordingConsent::Pending;
out.required |= prompt_required(&c.consent_prompt);
out
}
None => {
let required = prompt_required(&c.consent_prompt);
CallRecording {
recording_id: c.consent_prompt.recording_id.to_string(),
auto: c.auto,
started_by: c
.consent_prompt
.started_by
.as_ref()
.map(|m| m.member_id.to_string()),
started_at: None,
audio_keep_days: c.consent_prompt.audio_keep_days,
my_consent: RecordingConsent::Pending,
consent_prompt: Some(c.consent_prompt.clone()),
participants: Vec::new(),
trigger: if required && !c.auto {
RecordingTrigger::Required
} else {
RecordingTrigger::from_auto(c.auto)
},
required,
my_controls: None,
}
}
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Speaking {
pub identity: String,
pub member_id: Option<String>,
pub level: f32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallErrorEvent {
pub code: String,
pub detail: String,
}
impl CallErrorEvent {
pub fn new(code: impl Into<String>, detail: impl Into<String>) -> CallErrorEvent {
CallErrorEvent {
code: code.into(),
detail: detail.into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum CallEvent {
State(CallState),
Participants(Vec<Participant>),
Speaking(Vec<Speaking>),
Error(CallErrorEvent),
Moved(CallMoved),
Stats(Box<StatsWindow>),
Recording(Option<Box<CallRecording>>),
RecordingControls(Option<ServerControls>),
Security(CallSecurity),
VideoAdded(crate::video::VideoTrack),
VideoRemoved {
id: u64,
track_sid: String,
},
VideoChanged(crate::video::VideoTrack),
LocalVideo(crate::video::LocalVideo),
MediaPolicy(Box<sew_proto::voice::MediaPolicy>),
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallSecurity {
pub state: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub epoch: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub since_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub show_after_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
impl CallSecurity {
pub fn new(state: impl Into<String>) -> CallSecurity {
CallSecurity {
state: state.into(),
..CallSecurity::default()
}
}
pub fn active(epoch: u64, code: Option<String>) -> CallSecurity {
CallSecurity {
state: "active".to_owned(),
epoch: Some(epoch),
code,
..CallSecurity::default()
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallMoved {
pub channel_id: String,
pub call_id: Option<String>,
pub media_room: String,
}
impl CallMoved {
pub fn from_update(u: &sew_proto::voice::VoiceServerUpdated) -> CallMoved {
CallMoved {
channel_id: u.channel_id.to_string(),
call_id: u.call_id.map(|c| c.to_string()),
media_room: u.room.as_str().to_owned(),
}
}
pub fn room(&self) -> &str {
&self.channel_id
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct CallCounters {
pub frames_sent: u64,
pub frames_not_sent: u64,
pub send_queue_drops: u64,
pub frames_received: u64,
pub decrypt_failures: u64,
pub frames_before_key: u64,
pub refused_frames: u64,
pub recv_queue_drops: u64,
pub lost_marks: u64,
pub resumes: u64,
pub full_reconnects: u64,
pub rejoins: u64,
pub turn_allocations: u64,
pub credential_renewals: u64,
pub network_changes: u64,
pub video_frames_received: u64,
pub video_decrypt_failures: u64,
pub video_frames_before_key: u64,
pub video_frames_dropped: u64,
pub video_packets_unwanted: u64,
pub video_packets_lost: u64,
pub video_packets_late: u64,
pub video_recv_queue_drops: u64,
pub video_plis: u64,
pub video_firs: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct CallSnapshot {
pub state: CallState,
pub participants: Vec<Participant>,
pub relay: Option<String>,
pub relay_only: bool,
pub counters: CallCounters,
#[serde(skip_serializing_if = "Option::is_none")]
pub moved: Option<CallMoved>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recording: Option<CallRecording>,
#[serde(skip_serializing_if = "Option::is_none")]
pub security: Option<CallSecurity>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recording_controls: Option<ServerControls>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub server_controls: bool,
}
impl Default for CallSnapshot {
fn default() -> CallSnapshot {
CallSnapshot {
state: CallState::Connecting,
participants: Vec::new(),
relay: None,
relay_only: false,
counters: CallCounters::default(),
moved: None,
recording: None,
security: None,
recording_controls: None,
server_controls: false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct OpusFrame {
pub payload: Bytes,
pub ts48k: u32,
pub vad: bool,
pub level_dbov: f32,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct RecvOpus {
pub participant: u64,
pub identity: String,
pub payload: Bytes,
pub seq: u16,
pub ts48k: u32,
pub arrival: Instant,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum RecvItem {
Added {
participant: u64,
identity: String,
},
Removed {
participant: u64,
},
Frame(RecvOpus),
Lost {
participant: u64,
seq: u16,
},
Capture(bool),
Deafened(bool),
}
#[derive(Debug)]
pub struct FrameStream(pub(crate) mpsc::Receiver<RecvItem>);
impl FrameStream {
pub async fn recv(&mut self) -> Option<RecvItem> {
self.0.recv().await
}
pub fn try_recv(&mut self) -> Option<RecvItem> {
self.0.try_recv().ok()
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum CallError {
#[error("already_in_call")]
AlreadyInCall,
#[error(transparent)]
Provider(#[from] ProviderError),
#[error("the call has ended")]
Ended,
#[error("setup: {0}")]
Setup(String),
#[error("no_recording")]
NoRecording,
}
pub(crate) enum Cmd {
Mute {
muted: Option<bool>,
deafened: Option<bool>,
reply: oneshot::Sender<()>,
},
Leave(oneshot::Sender<()>),
Dropped,
Consent {
granted: bool,
notice_version: Option<u32>,
reply: oneshot::Sender<Result<(), CallError>>,
},
Recording {
control: RecordingControl,
reply: oneshot::Sender<Result<(), CallError>>,
},
NetworkChanged,
Video(crate::video::subscribe::SinkCmd),
Publish(crate::video::publish::VideoCmd),
}
pub struct CallClient {
cfg: ClientConfig,
e2ee: Arc<dyn E2eeProvider>,
busy: Arc<AtomicBool>,
codecs: Arc<crate::video::codec_pref::CodecSettings>,
}
impl std::fmt::Debug for CallClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CallClient")
.field("cfg", &self.cfg)
.finish_non_exhaustive()
}
}
impl CallClient {
pub fn new(cfg: ClientConfig, e2ee: Arc<dyn E2eeProvider>) -> CallClient {
CallClient {
cfg,
e2ee,
busy: Arc::new(AtomicBool::new(false)),
codecs: Arc::default(),
}
}
pub fn set_video_codec_preference(&self, pref: crate::VideoCodecPreference) {
self.codecs.set_preference(pref);
}
pub fn video_codec_preference(&self) -> crate::VideoCodecPreference {
self.codecs.preference()
}
pub fn set_video_decode(&self, codecs: &[crate::VideoCodec]) {
self.codecs.set_decode(codecs);
}
pub fn video_decode(&self) -> Option<Vec<crate::VideoCodec>> {
self.codecs.decode()
}
pub fn with_mls(cfg: ClientConfig) -> CallClient {
let keys =
crate::e2ee::MlsKeys::new(cfg.device_store.clone()).with_platform(cfg.device_platform);
CallClient::new(cfg, Arc::new(keys))
}
pub fn known_device_keys(
&self,
) -> Result<Vec<crate::device::DeviceKeyId>, crate::device::DeviceError> {
crate::device::known_device_keys(&self.cfg.data_dir)
}
pub async fn forget_server(
&self,
install_id: u64,
) -> Result<Vec<crate::device::DeviceKeyId>, crate::device::DeviceError> {
if self.busy.swap(true, Ordering::AcqRel) {
return Err(crate::device::DeviceError::InCall);
}
let _busy = BusyGuard(self.busy.clone());
let vault = crate::device::VaultConfig {
data_dir: self.cfg.data_dir.clone(),
app_id: self.cfg.app_id.clone(),
store: self.cfg.device_store.clone(),
label: String::new(),
platform: self.cfg.device_platform,
};
crate::device::forget_install(&vault, install_id).await
}
pub async fn join(
&self,
provider: Arc<dyn JoinProvider>,
req: JoinRequest,
) -> Result<Call, CallError> {
if self.busy.swap(true, Ordering::AcqRel) {
return Err(CallError::AlreadyInCall);
}
let busy = BusyGuard(self.busy.clone());
let first = match provider.join(req.clone()).await {
Ok(answer) => engine::First::Answer(Box::new(answer)),
Err(ProviderError::ConsentRequired(c)) => engine::First::Held(c),
Err(e) => return Err(e.into()),
};
let (events, _) = broadcast::channel(256);
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (push_tx, push_rx) = mpsc::channel(SEND_QUEUE);
let (frames_tx, frames_rx) = mpsc::channel(RECV_QUEUE);
let (video_tx, video_rx) = mpsc::channel(VIDEO_RECV_QUEUE);
let snapshot = Arc::new(Mutex::new(CallSnapshot::default()));
let shared = Arc::new(engine::Shared {
events: events.clone(),
snapshot: snapshot.clone(),
send_queue_drops: std::sync::atomic::AtomicU64::new(0),
stats: Mutex::new(CallStatsReport::default()),
playout: Mutex::new(None),
noise: Mutex::new(None),
beacon_stopped: AtomicBool::new(false),
policy: Mutex::new(None),
video_stats: Arc::new(Mutex::new(crate::video::VideoSendStats::default())),
video_codecs: self.codecs.negotiated(self.cfg.video_h264),
codec_settings: Arc::clone(&self.codecs),
});
if let engine::First::Held(c) = &first {
engine::preset_held(&snapshot, c);
}
engine::spawn(engine::Start {
cfg: self.cfg.clone(),
e2ee: self.e2ee.clone(),
provider,
req,
first,
shared: shared.clone(),
cmd_rx,
push_rx,
frames_tx,
video_tx,
busy,
})
.map_err(CallError::Setup)?;
Ok(Call {
cmd: cmd_tx,
push: push_tx,
shared,
frames: Mutex::new(Some(FrameStream(frames_rx))),
video: Mutex::new(Some(crate::video::VideoFrameStream(video_rx))),
next_sink: std::sync::atomic::AtomicU64::new(1),
id: NEXT_CALL.fetch_add(1, Ordering::Relaxed),
})
}
}
static NEXT_CALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
pub(crate) struct BusyGuard(Arc<AtomicBool>);
impl Drop for BusyGuard {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
#[derive(Clone)]
pub struct CallLeaver {
cmd: mpsc::UnboundedSender<Cmd>,
id: u64,
}
impl std::fmt::Debug for CallLeaver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CallLeaver").finish_non_exhaustive()
}
}
impl CallLeaver {
pub async fn leave(&self) -> Result<(), CallError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Leave(reply))
.map_err(|_| CallError::Ended)?;
rx.await.map_err(|_| CallError::Ended)
}
pub fn local_id(&self) -> u64 {
self.id
}
}
#[derive(Clone)]
pub struct FrameSender {
push: mpsc::Sender<OpusFrame>,
shared: Arc<engine::Shared>,
}
impl std::fmt::Debug for FrameSender {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameSender").finish_non_exhaustive()
}
}
impl FrameSender {
pub fn push_opus(&self, f: OpusFrame) {
if self.push.try_send(f).is_err() {
self.shared.send_queue_drops.fetch_add(1, Ordering::Relaxed);
}
}
}
pub struct Call {
cmd: mpsc::UnboundedSender<Cmd>,
push: mpsc::Sender<OpusFrame>,
shared: Arc<engine::Shared>,
frames: Mutex<Option<FrameStream>>,
video: Mutex<Option<crate::video::VideoFrameStream>>,
next_sink: std::sync::atomic::AtomicU64,
id: u64,
}
impl Drop for Call {
fn drop(&mut self) {
let _ = self.cmd.send(Cmd::Dropped);
}
}
impl std::fmt::Debug for Call {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Call").finish_non_exhaustive()
}
}
impl Call {
pub fn events(&self) -> broadcast::Receiver<CallEvent> {
self.shared.events.subscribe()
}
pub fn snapshot(&self) -> CallSnapshot {
let mut s = self
.shared
.snapshot
.lock()
.map(|s| s.clone())
.unwrap_or_default();
s.counters.send_queue_drops = self.shared.send_queue_drops.load(Ordering::Relaxed);
s
}
pub fn stats(&self) -> CallStatsReport {
self.shared
.stats
.lock()
.map(|s| s.clone())
.unwrap_or_default()
}
pub fn set_playout_stats(&self, source: Arc<dyn PlayoutStats>) {
if let Ok(mut p) = self.shared.playout.lock() {
*p = Some(source);
}
}
pub fn noise_removal(&self) -> Option<crate::NoiseRemovalState> {
self.shared.noise_removal()
}
#[cfg(feature = "audio-core")]
pub(crate) fn set_noise_source(&self, source: Arc<dyn crate::noise::NoiseSource>) {
if let Ok(mut n) = self.shared.noise.lock() {
*n = Some(source);
}
}
#[cfg_attr(not(feature = "video-core"), allow(dead_code))]
pub(crate) fn noise_grace(&self) {
let src = self.shared.noise.lock().ok().and_then(|n| n.clone());
if let Some(src) = src {
src.grace();
}
}
pub async fn mute(&self, muted: Option<bool>, deafened: Option<bool>) -> Result<(), CallError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Mute {
muted,
deafened,
reply,
})
.map_err(|_| CallError::Ended)?;
rx.await.map_err(|_| CallError::Ended)
}
pub fn recording(&self) -> Option<CallRecording> {
self.shared
.snapshot
.lock()
.ok()
.and_then(|s| s.recording.clone())
}
pub fn recording_controls(&self) -> Option<ServerControls> {
self.shared
.snapshot
.lock()
.ok()
.and_then(|s| s.recording_controls)
}
pub fn server_controls(&self) -> bool {
self.shared.snapshot.lock().is_ok_and(|s| s.server_controls)
}
pub async fn consent(&self, granted: bool, notice_version: u32) -> Result<(), CallError> {
self.answer(granted, Some(notice_version)).await
}
pub async fn withdraw_consent(&self) -> Result<(), CallError> {
self.answer(false, None).await
}
pub async fn start_recording(&self) -> Result<(), CallError> {
self.control(RecordingControl::Start).await
}
pub async fn stop_recording(&self) -> Result<(), CallError> {
self.control(RecordingControl::Stop).await
}
async fn control(&self, control: RecordingControl) -> Result<(), CallError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Recording { control, reply })
.map_err(|_| CallError::Ended)?;
rx.await.map_err(|_| CallError::Ended)?
}
async fn answer(&self, granted: bool, notice_version: Option<u32>) -> Result<(), CallError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Consent {
granted,
notice_version,
reply,
})
.map_err(|_| CallError::Ended)?;
rx.await.map_err(|_| CallError::Ended)?
}
pub fn network_changed(&self) {
let _ = self.cmd.send(Cmd::NetworkChanged);
}
pub async fn leave(self) -> Result<(), CallError> {
self.leaver().leave().await
}
pub fn leaver(&self) -> CallLeaver {
CallLeaver {
cmd: self.cmd.clone(),
id: self.id,
}
}
pub fn local_id(&self) -> u64 {
self.id
}
pub fn push_opus(&self, f: OpusFrame) {
self.frame_sender().push_opus(f);
}
pub fn frame_sender(&self) -> FrameSender {
FrameSender {
push: self.push.clone(),
shared: self.shared.clone(),
}
}
pub fn frames(&self) -> Option<FrameStream> {
self.frames.lock().ok().and_then(|mut f| f.take())
}
pub fn video_frames(&self) -> Option<crate::video::VideoFrameStream> {
self.video.lock().ok().and_then(|mut f| f.take())
}
pub fn video_codecs(&self) -> Vec<crate::VideoCodec> {
if crate::pc::VIDEO {
self.shared.video_codecs.codecs()
} else {
Vec::new()
}
}
pub fn video_codec_preference(&self) -> crate::VideoCodecPreference {
self.shared.codec_settings.preference()
}
pub fn video_sink(
&self,
track_sid: &str,
spec: crate::video::VideoSinkSpec,
) -> crate::video::VideoSink {
let id = self.next_sink.fetch_add(1, Ordering::Relaxed);
let _ = self
.cmd
.send(Cmd::Video(crate::video::subscribe::SinkCmd::Open {
id,
track_sid: track_sid.to_owned(),
spec,
}));
crate::video::VideoSink {
id,
cmd: self.cmd.clone(),
}
}
pub fn media_policy(&self) -> Option<sew_proto::voice::MediaPolicy> {
self.shared.policy.lock().ok().and_then(|p| p.clone())
}
#[cfg(feature = "video-core")]
pub(crate) fn decodes_h264(&self) -> bool {
self.shared.video_codecs.contains(crate::VideoCodec::H264)
}
pub fn video_stats(&self) -> crate::video::VideoSendStats {
self.shared
.video_stats
.lock()
.map(|s| s.clone())
.unwrap_or_default()
}
async fn video(
&self,
cmd: impl FnOnce(
oneshot::Sender<Result<(), crate::video::VideoError>>,
) -> crate::video::publish::VideoCmd,
) -> Result<(), crate::video::VideoError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Publish(cmd(reply)))
.map_err(|_| crate::video::VideoError::Ended)?;
rx.await.map_err(|_| crate::video::VideoError::Ended)?
}
pub async fn set_video_lease(
&self,
source: crate::video::VideoSource,
on: bool,
) -> Result<(), crate::video::VideoError> {
self.video(|reply| crate::video::publish::VideoCmd::Lease { source, on, reply })
.await
}
pub async fn publish_video(
&self,
req: crate::video::VideoPublish,
) -> Result<crate::video::VideoPublication, crate::video::VideoError> {
let (reply, rx) = oneshot::channel();
self.cmd
.send(Cmd::Publish(crate::video::publish::VideoCmd::Publish {
req,
reply,
}))
.map_err(|_| crate::video::VideoError::Ended)?;
rx.await.map_err(|_| crate::video::VideoError::Ended)?
}
pub async fn unpublish_video(
&self,
source: crate::video::VideoSource,
release_lease: bool,
) -> Result<(), crate::video::VideoError> {
self.unpublish_video_because(source, release_lease, crate::video::publish::UNPUBLISHED)
.await
}
pub async fn unpublish_video_because(
&self,
source: crate::video::VideoSource,
release_lease: bool,
reason: &str,
) -> Result<(), crate::video::VideoError> {
let reason = reason.to_owned();
self.video(|reply| crate::video::publish::VideoCmd::Unpublish {
source,
release: release_lease,
reason,
reply,
})
.await
}
#[cfg(feature = "video-core")]
pub(crate) fn video_ctl(&self) -> crate::video::publish::VideoCtl {
crate::video::publish::VideoCtl::new(self.cmd.clone())
}
pub fn set_video_muted(&self, source: crate::video::VideoSource, muted: bool) {
let _ = self
.cmd
.send(Cmd::Publish(crate::video::publish::VideoCmd::Mute {
source,
muted,
}));
}
pub fn set_video_caps(&self, caps: crate::video::VideoCaps) {
let _ = self
.cmd
.send(Cmd::Publish(crate::video::publish::VideoCmd::Caps(caps)));
}
}