1use std::collections::BTreeMap;
56use std::sync::{Arc, Mutex};
57use std::time::{Duration, Instant};
58
59use bytes::Bytes;
60use serde::Serialize;
61use sew_lk_compat::Session;
62use sew_lkproto::livekit::{
63 AddTrackRequest, SimulcastCodec, SubscribedQualityUpdate, TrackInfo, TrackSource, TrackType,
64 VideoLayer,
65};
66use sew_proto::voice::{MediaPolicy, TrackHint};
67use tokio::sync::{broadcast, mpsc, oneshot};
68
69use super::alloc::{AllocLayer, Allocator};
70use super::rtp::MTU;
71use super::rtp::h264::H264Sender;
72use super::rtp::normalise::{check, normalise};
73use super::rtp::vp8::{FrameLayer, Vp8Sender, Vp8Starts};
74use super::types::{VideoCodec, VideoSource};
75use crate::call::CallEvent;
76use crate::e2ee::{KeySession, Leases, PublishRefused, VideoFrameCodec, check_publish};
77use crate::pc::{BWE_INITIAL_BPS, Pc};
78
79pub(crate) const VIDEO_QUEUE: usize = 96;
81pub(crate) const UNPUBLISHED: &str = "unpublished";
83pub(crate) const PUBLISHER_GONE: &str = "publisher_gone";
86const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10);
88const KEYFRAME_EVERY: Duration = Duration::from_millis(300);
91
92fn mime(c: VideoCodec) -> &'static str {
94 match c {
95 VideoCodec::Vp8 => "video/VP8",
96 VideoCodec::H264 => "video/H264",
97 }
98}
99
100fn frame_codec(c: VideoCodec) -> VideoFrameCodec {
101 match c {
102 VideoCodec::Vp8 => VideoFrameCodec::Vp8,
103 VideoCodec::H264 => VideoFrameCodec::H264,
104 }
105}
106
107pub(crate) fn codec_of_policy(c: sew_proto::voice::VideoCodec) -> Option<VideoCodec> {
109 match c {
110 sew_proto::voice::VideoCodec::Vp8 => Some(VideoCodec::Vp8),
111 sew_proto::voice::VideoCodec::H264 => Some(VideoCodec::H264),
112 _ => None,
113 }
114}
115
116fn track_source(s: VideoSource) -> TrackSource {
117 match s {
118 VideoSource::Camera => TrackSource::Camera,
119 VideoSource::ScreenShare => TrackSource::ScreenShare,
120 }
121}
122
123fn track_name(s: VideoSource) -> &'static str {
124 match s {
125 VideoSource::Camera => "camera",
126 VideoSource::ScreenShare => "screen",
127 }
128}
129
130pub(crate) fn hint_of(s: VideoSource, policy: &MediaPolicy) -> &TrackHint {
132 match s {
133 VideoSource::Camera => &policy.camera,
134 VideoSource::ScreenShare => &policy.screen,
135 }
136}
137
138fn allowed(s: VideoSource, policy: &MediaPolicy) -> bool {
139 match s {
140 VideoSource::Camera => policy.camera_allowed,
141 VideoSource::ScreenShare => policy.screen_allowed,
142 }
143}
144
145#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
147#[non_exhaustive]
148pub struct LayerSpec {
149 pub rid: String,
151 pub width: u32,
153 pub height: u32,
155 pub max_kbps: u32,
157 pub fps: u32,
159 pub temporal_layers: u8,
161}
162
163impl LayerSpec {
164 pub fn new(rid: &str, width: u32, height: u32, max_kbps: u32, fps: u32) -> LayerSpec {
166 LayerSpec {
167 rid: rid.to_owned(),
168 width,
169 height,
170 max_kbps,
171 fps,
172 temporal_layers: 1,
173 }
174 }
175}
176
177fn even(v: u64) -> u32 {
178 u32::try_from(v & !1).unwrap_or(u32::MAX - 1)
179}
180
181pub fn plan_layers(hint: &TrackHint, capture_width: u32, capture_height: u32) -> Vec<LayerSpec> {
188 let (cw, ch) = (capture_width.max(2), capture_height.max(2));
189 let portrait = ch > cw;
190 let (short, long) = if portrait { (cw, ch) } else { (ch, cw) };
191 let fps = hint.max_fps.max(1);
192 let mut out: Vec<LayerSpec> = hint
193 .layers
194 .iter()
195 .filter(|l| l.height <= short && l.height > 0)
196 .map(|l| {
197 let s = even(u64::from(l.height));
198 let g = even(u64::from(l.height) * u64::from(long) / u64::from(short)).max(2);
199 let (width, height) = if portrait { (s, g) } else { (g, s) };
200 LayerSpec::new(&l.rid, width, height, l.max_kbps, fps)
201 })
202 .collect();
203 if out.is_empty()
204 && let Some(l) = hint.layers.first()
205 {
206 out.push(LayerSpec::new(
207 &l.rid,
208 even(cw.into()),
209 even(ch.into()),
210 l.max_kbps,
211 fps,
212 ));
213 }
214 out
215}
216
217pub fn plan_screen_layers(
228 hint: &TrackHint,
229 capture_width: u32,
230 capture_height: u32,
231) -> Vec<LayerSpec> {
232 let mut out = plan_layers(hint, capture_width, capture_height);
233 let (cw, ch) = (
234 even(capture_width.max(2).into()),
235 even(capture_height.max(2).into()),
236 );
237 let short = cw.min(ch);
238 let Some(top) = out.last() else {
239 return out;
240 };
241 let top_short = top.width.min(top.height);
242 if u64::from(short) * 4 <= u64::from(top_short) * 5 {
243 return out;
244 }
245 let Some(next) = hint.layers.iter().find(|l| l.height > short) else {
247 return out;
248 };
249 let hint_short = u64::from(next.height);
250 let scaled =
251 u64::from(next.max_kbps) * u64::from(short) * u64::from(short) / (hint_short * hint_short);
252 let max_kbps = u32::try_from(scaled)
253 .unwrap_or(next.max_kbps)
254 .max(top.max_kbps);
255 let fps = top.fps;
256 out.push(LayerSpec::new(&next.rid, cw, ch, max_kbps, fps));
257 out
258}
259
260pub(crate) fn plan_source_layers(
263 source: VideoSource,
264 hint: &TrackHint,
265 width: u32,
266 height: u32,
267) -> Vec<LayerSpec> {
268 match source {
269 VideoSource::Camera => plan_layers(hint, width, height),
270 VideoSource::ScreenShare => plan_screen_layers(hint, width, height),
271 }
272}
273
274#[derive(Clone, Debug, PartialEq, Eq)]
276#[non_exhaustive]
277pub struct VideoPublish {
278 pub source: VideoSource,
280 pub codec: VideoCodec,
282 pub layers: Vec<LayerSpec>,
284 pub capture_width: u32,
286 pub capture_height: u32,
288 pub backup: Option<BackupSpec>,
290}
291
292#[derive(Clone, Debug, PartialEq, Eq)]
295#[non_exhaustive]
296pub struct BackupSpec {
297 pub codec: VideoCodec,
299 pub layers: Vec<LayerSpec>,
302}
303
304impl BackupSpec {
305 pub fn new(codec: VideoCodec, layers: Vec<LayerSpec>) -> BackupSpec {
307 BackupSpec { codec, layers }
308 }
309}
310
311impl VideoPublish {
312 pub fn new(
314 source: VideoSource,
315 codec: VideoCodec,
316 layers: Vec<LayerSpec>,
317 capture_width: u32,
318 capture_height: u32,
319 ) -> VideoPublish {
320 VideoPublish {
321 source,
322 codec,
323 layers,
324 capture_width,
325 capture_height,
326 backup: None,
327 }
328 }
329
330 pub fn with_backup(mut self, backup: BackupSpec) -> VideoPublish {
334 self.backup = Some(backup);
335 self
336 }
337}
338
339#[derive(Clone, Debug, PartialEq, Eq)]
341#[non_exhaustive]
342pub struct EncodedVideo {
343 pub rid: String,
345 pub codec: VideoCodec,
347 pub data: Bytes,
349 pub keyframe: bool,
351 pub capture_us: u64,
353 pub temporal_id: u8,
355 pub layer_sync: bool,
357 pub width: u32,
359 pub height: u32,
361}
362
363impl EncodedVideo {
364 pub fn new(
366 rid: &str,
367 codec: VideoCodec,
368 data: Bytes,
369 keyframe: bool,
370 capture_us: u64,
371 width: u32,
372 height: u32,
373 ) -> EncodedVideo {
374 EncodedVideo {
375 rid: rid.to_owned(),
376 codec,
377 data,
378 keyframe,
379 capture_us,
380 temporal_id: 0,
381 layer_sync: keyframe,
382 width,
383 height,
384 }
385 }
386
387 pub fn with_layer(mut self, temporal_id: u8, layer_sync: bool) -> EncodedVideo {
389 self.temporal_id = temporal_id;
390 self.layer_sync = layer_sync;
391 self
392 }
393}
394
395#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
397#[non_exhaustive]
398pub struct LayerRate {
399 pub rid: String,
401 pub active: bool,
403 pub bitrate_bps: u32,
405 pub fps: u32,
407}
408
409#[derive(Clone, Debug, PartialEq, Eq)]
411#[non_exhaustive]
412pub enum VideoControl {
413 Keyframe {
415 rid: String,
417 },
418 Rates(Vec<LayerRate>),
420 Republish(Vec<LayerSpec>),
423 Ended {
426 reason: String,
428 },
429 BackupStart(Vec<LayerSpec>),
432 BackupRates(Vec<LayerRate>),
435 BackupKeyframe {
437 rid: String,
439 },
440 BackupStop,
442}
443
444#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
446#[non_exhaustive]
447pub enum VideoError {
448 #[error("video_not_allowed")]
451 NotAllowed,
452 #[error("video_disabled")]
454 Disabled,
455 #[error("video_slots_full")]
457 VideoSlotsFull,
458 #[error("screen_slots_full")]
460 ScreenSlotsFull,
461 #[error("media_busy")]
463 MediaBusy {
464 retry_after: Option<u64>,
466 },
467 #[error("media_capacity")]
469 MediaCapacity,
470 #[error("no_lease")]
472 NoLease,
473 #[error("e2ee_downgraded")]
475 Downgraded,
476 #[error("codec_unavailable")]
478 CodecUnavailable,
479 #[error("camera_denied")]
481 CameraDenied,
482 #[error("camera_busy")]
484 CameraBusy,
485 #[error("camera_not_found")]
487 CameraNotFound,
488 #[error("no_frames")]
491 NoFrames,
492 #[error("already_published")]
494 AlreadyPublished,
495 #[error("not_published")]
497 NotPublished,
498 #[error("publish_failed: {0}")]
500 PublishFailed(String),
501 #[error("lease_failed: {status} {code}")]
504 Lease {
505 status: u16,
507 code: String,
509 },
510 #[error("ended")]
512 Ended,
513}
514
515impl VideoError {
516 pub fn code(&self) -> &'static str {
518 match self {
519 VideoError::NotAllowed => "video_not_allowed",
520 VideoError::Disabled => "video_disabled",
521 VideoError::VideoSlotsFull => "video_slots_full",
522 VideoError::ScreenSlotsFull => "screen_slots_full",
523 VideoError::MediaBusy { .. } => "media_busy",
524 VideoError::MediaCapacity => "media_capacity",
525 VideoError::NoLease => "no_lease",
526 VideoError::Downgraded => "e2ee_downgraded",
527 VideoError::CodecUnavailable => "codec_unavailable",
528 VideoError::CameraDenied => "camera_denied",
529 VideoError::CameraBusy => "camera_busy",
530 VideoError::CameraNotFound => "camera_not_found",
531 VideoError::NoFrames => "no_frames",
532 VideoError::AlreadyPublished => "already_published",
533 VideoError::NotPublished => "not_published",
534 VideoError::PublishFailed(_) => "publish_failed",
535 VideoError::Lease { .. } => "lease_failed",
536 VideoError::Ended => "ended",
537 }
538 }
539
540 pub(crate) fn from_lease(r: &crate::api::LeaseRefused) -> VideoError {
542 use sew_proto::voice::reasons as vr;
543 match (r.status, r.reason.as_deref()) {
544 (_, Some(vr::VIDEO_SLOTS_FULL)) => VideoError::VideoSlotsFull,
545 (_, Some(vr::SCREEN_SLOTS_FULL)) => VideoError::ScreenSlotsFull,
546 (_, Some(vr::MEDIA_BUSY)) => VideoError::MediaBusy {
547 retry_after: r.retry_after,
548 },
549 (_, Some(vr::MEDIA_CAPACITY)) => VideoError::MediaCapacity,
550 (_, Some(vr::VIDEO_DISABLED)) => VideoError::Disabled,
551 (status, _) => VideoError::Lease {
552 status,
553 code: r
554 .code
555 .clone()
556 .unwrap_or_else(|| r.detail.clone())
557 .chars()
558 .take(64)
559 .collect(),
560 },
561 }
562 }
563}
564
565#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
567#[non_exhaustive]
568pub struct LocalVideo {
569 pub source: VideoSource,
571 pub on: bool,
573 pub reason: Option<String>,
575}
576
577impl LocalVideo {
578 pub fn new(source: VideoSource, on: bool, reason: Option<String>) -> LocalVideo {
580 LocalVideo { source, on, reason }
581 }
582}
583
584#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
586#[non_exhaustive]
587pub struct VideoSendStats {
588 pub frames_sent: BTreeMap<String, u64>,
590 pub packets_sent: u64,
592 pub keyframes_sent: u64,
594 pub frames_not_sent: u64,
597 pub malformed: u64,
599 pub keyframes_asked: u64,
601 pub sfu_keyframe_requests: u64,
603 pub sfu_keyframe_requests_by_layer: BTreeMap<String, u64>,
606 pub republishes: u64,
608 pub estimate_bps: u64,
610 pub frames_by_codec: BTreeMap<String, u64>,
613 pub keyframes_by_codec: BTreeMap<String, u64>,
615 pub backup_starts: u64,
617 pub backup_stops: u64,
619 pub backup_ms: u64,
621}
622
623#[derive(Debug)]
625pub(crate) struct VideoIn {
626 pub(crate) publication: u64,
627 pub(crate) frame: EncodedVideo,
628}
629
630#[derive(Debug)]
632pub struct VideoPublication {
633 source: VideoSource,
634 id: u64,
635 track_sid: String,
636 published_mime: String,
637 frames: mpsc::Sender<VideoIn>,
638 control: mpsc::UnboundedReceiver<VideoControl>,
639 stats: Arc<Mutex<VideoSendStats>>,
640 ends: mpsc::UnboundedSender<ProducerEnd>,
641 fallbacks: mpsc::UnboundedSender<ProducerFallback>,
642}
643
644impl VideoPublication {
645 pub fn source(&self) -> VideoSource {
647 self.source
648 }
649
650 pub fn track_sid(&self) -> &str {
652 &self.track_sid
653 }
654
655 pub fn published_mime(&self) -> &str {
659 &self.published_mime
660 }
661
662 pub fn push(&self, frame: EncodedVideo) {
664 self.sender().push(frame);
665 }
666
667 pub fn sender(&self) -> VideoSender {
669 VideoSender {
670 id: self.id,
671 frames: self.frames.clone(),
672 stats: self.stats.clone(),
673 }
674 }
675
676 pub fn try_control(&mut self) -> Option<VideoControl> {
678 self.control.try_recv().ok()
679 }
680
681 pub async fn control(&mut self) -> Option<VideoControl> {
683 self.control.recv().await
684 }
685
686 pub fn end(&self, reason: &str) {
691 let _ = self.ends.send(ProducerEnd {
692 publication: self.id,
693 reason: reason.to_owned(),
694 });
695 }
696
697 pub fn republish_without_backup(&self, codec: VideoCodec, layers: Vec<LayerSpec>) {
703 let _ = self.fallbacks.send(ProducerFallback {
704 publication: self.id,
705 codec,
706 layers,
707 });
708 }
709}
710
711#[derive(Debug)]
713pub(crate) struct ProducerEnd {
714 pub(crate) publication: u64,
715 pub(crate) reason: String,
716}
717
718#[derive(Debug)]
720pub(crate) struct ProducerFallback {
721 pub(crate) publication: u64,
722 pub(crate) codec: VideoCodec,
723 pub(crate) layers: Vec<LayerSpec>,
724}
725
726#[cfg(all(test, feature = "video-core"))]
727impl VideoPublication {
728 pub(crate) fn for_test(
731 source: VideoSource,
732 ) -> (
733 VideoPublication,
734 mpsc::Receiver<VideoIn>,
735 mpsc::UnboundedSender<VideoControl>,
736 ) {
737 let (p, rx, ctl, _) = VideoPublication::for_test_with_ends(source);
738 (p, rx, ctl)
739 }
740
741 #[allow(clippy::type_complexity)]
744 pub(crate) fn for_test_with_ends(
745 source: VideoSource,
746 ) -> (
747 VideoPublication,
748 mpsc::Receiver<VideoIn>,
749 mpsc::UnboundedSender<VideoControl>,
750 mpsc::UnboundedReceiver<ProducerEnd>,
751 ) {
752 let (p, rx, ctl, ends, _) = VideoPublication::for_test_with_fallbacks(source);
753 (p, rx, ctl, ends)
754 }
755
756 #[allow(clippy::type_complexity)]
759 pub(crate) fn for_test_with_fallbacks(
760 source: VideoSource,
761 ) -> (
762 VideoPublication,
763 mpsc::Receiver<VideoIn>,
764 mpsc::UnboundedSender<VideoControl>,
765 mpsc::UnboundedReceiver<ProducerEnd>,
766 mpsc::UnboundedReceiver<ProducerFallback>,
767 ) {
768 let (frames, rx) = mpsc::channel(VIDEO_QUEUE);
769 let (ctl, control) = mpsc::unbounded_channel();
770 let (ends, ends_rx) = mpsc::unbounded_channel();
771 let (fallbacks, fallbacks_rx) = mpsc::unbounded_channel();
772 let p = VideoPublication {
773 source,
774 id: 1,
775 track_sid: "TR_test".to_owned(),
776 published_mime: "video/VP8".to_owned(),
777 frames,
778 control,
779 stats: Arc::default(),
780 ends,
781 fallbacks,
782 };
783 (p, rx, ctl, ends_rx, fallbacks_rx)
784 }
785}
786
787#[derive(Clone)]
789pub struct VideoSender {
790 id: u64,
791 frames: mpsc::Sender<VideoIn>,
792 stats: Arc<Mutex<VideoSendStats>>,
793}
794
795impl std::fmt::Debug for VideoSender {
796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
797 f.debug_struct("VideoSender").finish_non_exhaustive()
798 }
799}
800
801impl VideoSender {
802 pub fn push(&self, frame: EncodedVideo) {
804 if self
805 .frames
806 .try_send(VideoIn {
807 publication: self.id,
808 frame,
809 })
810 .is_err()
811 && let Ok(mut s) = self.stats.lock()
812 {
813 s.frames_not_sent += 1;
814 }
815 }
816}
817
818#[derive(Clone, Copy, Debug, PartialEq, Eq)]
820#[non_exhaustive]
821pub struct VideoCaps {
822 pub bitrate_pct: u8,
825 pub max_layers: Option<u8>,
827 pub max_fps: Option<u32>,
829}
830
831impl Default for VideoCaps {
832 fn default() -> VideoCaps {
833 VideoCaps {
834 bitrate_pct: 100,
835 max_layers: None,
836 max_fps: None,
837 }
838 }
839}
840
841impl VideoCaps {
842 pub fn none() -> VideoCaps {
844 VideoCaps::default()
845 }
846
847 pub fn new(bitrate_pct: u8, max_layers: Option<u8>, max_fps: Option<u32>) -> VideoCaps {
849 VideoCaps {
850 bitrate_pct: bitrate_pct.clamp(1, 100),
851 max_layers,
852 max_fps,
853 }
854 }
855}
856
857#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
860pub(crate) struct BackupCaps {
861 pub(crate) max_layers: Option<u8>,
862 pub(crate) max_fps: Option<u32>,
863}
864
865pub(crate) enum VideoCmd {
867 Lease {
868 source: VideoSource,
869 on: bool,
870 reply: oneshot::Sender<Result<(), VideoError>>,
871 },
872 Publish {
873 req: VideoPublish,
874 reply: oneshot::Sender<Result<VideoPublication, VideoError>>,
875 },
876 Unpublish {
877 source: VideoSource,
878 release: bool,
879 reason: String,
881 reply: oneshot::Sender<Result<(), VideoError>>,
882 },
883 Caps(VideoCaps),
884 #[cfg_attr(not(feature = "video-core"), allow(dead_code))]
886 BackupCaps(BackupCaps),
887 Mute {
890 source: VideoSource,
891 muted: bool,
892 },
893}
894
895impl VideoCmd {
896 pub(crate) fn refuse(self) {
898 match self {
899 VideoCmd::Lease { reply, .. } | VideoCmd::Unpublish { reply, .. } => {
900 let _ = reply.send(Err(VideoError::Ended));
901 }
902 VideoCmd::Publish { reply, .. } => {
903 let _ = reply.send(Err(VideoError::Ended));
904 }
905 VideoCmd::Caps(_) | VideoCmd::BackupCaps(_) | VideoCmd::Mute { .. } => {}
906 }
907 }
908}
909
910#[cfg(feature = "video-core")]
913#[derive(Clone)]
914pub(crate) struct VideoCtl {
915 cmd: mpsc::UnboundedSender<crate::call::Cmd>,
916}
917
918#[cfg(feature = "video-core")]
919impl VideoCtl {
920 pub(crate) fn new(cmd: mpsc::UnboundedSender<crate::call::Cmd>) -> VideoCtl {
921 VideoCtl { cmd }
922 }
923
924 pub(crate) fn backup_caps(&self, caps: BackupCaps) {
926 let _ = self
927 .cmd
928 .send(crate::call::Cmd::Publish(VideoCmd::BackupCaps(caps)));
929 }
930
931 pub(crate) fn end(&self, source: VideoSource, reason: &'static str) {
933 let (reply, _) = oneshot::channel();
934 let _ = self
935 .cmd
936 .send(crate::call::Cmd::Publish(VideoCmd::Unpublish {
937 source,
938 release: true,
939 reason: reason.to_owned(),
940 reply,
941 }));
942 }
943}
944
945pub(crate) struct LeaseDone {
947 source: VideoSource,
948 on: bool,
949 result: Result<(), VideoError>,
950 reply: Option<oneshot::Sender<Result<(), VideoError>>>,
951 relink: bool,
953}
954
955pub(crate) enum VideoStep {
957 Frame(VideoIn),
958 Lease(LeaseDone),
959 End(ProducerEnd),
961 Fallback(ProducerFallback),
963}
964
965pub(crate) struct Ctx<'a> {
967 pub(crate) pc: Option<&'a mut Pc>,
968 pub(crate) session: &'a mut Session,
969 pub(crate) keys: Option<&'a Arc<dyn KeySession>>,
970 pub(crate) stream: &'a str,
972 pub(crate) media_up: bool,
973 pub(crate) joined: bool,
975 pub(crate) now: Instant,
976 pub(crate) events: &'a broadcast::Sender<CallEvent>,
977}
978
979#[derive(Clone)]
981pub(crate) struct LeaseApi {
982 pub(crate) http: reqwest::Client,
983 pub(crate) base: url::Url,
984 pub(crate) token: Option<String>,
985}
986
987enum Packetiser {
988 Vp8(Vp8Sender),
989 H264(H264Sender),
990}
991
992struct Layer {
993 spec: LayerSpec,
994 ssrc: Option<u32>,
995 seq: u64,
996 pack: Packetiser,
997 wanted: bool,
999 rate: Option<u64>,
1001 need_key: bool,
1003 last_key_ask: Option<Instant>,
1004 key_sent_since_ask: bool,
1007 told: Option<LayerRate>,
1009}
1010
1011impl Layer {
1012 fn new(spec: LayerSpec, codec: VideoCodec, first_seq: u64, wanted: bool) -> Layer {
1013 let size = (
1014 u16::try_from(spec.width).unwrap_or(u16::MAX),
1015 u16::try_from(spec.height).unwrap_or(u16::MAX),
1016 );
1017 let pack = match codec {
1018 VideoCodec::Vp8 => Packetiser::Vp8(Vp8Sender::new(
1019 MTU,
1020 spec.temporal_layers,
1021 Vp8Starts {
1022 picture_id: rand::random::<u16>() & 0x7fff,
1023 tl0_pic_idx: rand::random(),
1024 frame_number: rand::random(),
1025 },
1026 size,
1027 )),
1028 VideoCodec::H264 => Packetiser::H264(H264Sender::new(MTU, rand::random(), size)),
1029 };
1030 Layer {
1031 spec,
1032 ssrc: None,
1033 seq: first_seq,
1034 pack,
1035 wanted,
1036 rate: None,
1037 need_key: true,
1038 last_key_ask: None,
1039 key_sent_since_ask: false,
1040 told: None,
1041 }
1042 }
1043
1044 fn active(&self) -> bool {
1045 self.wanted && self.rate.is_some()
1046 }
1047}
1048
1049struct Lane {
1053 codec: VideoCodec,
1054 cid: String,
1056 mid: Option<String>,
1057 pt: Option<u8>,
1058 layers: Vec<Layer>,
1059 backup: bool,
1060 on: bool,
1062 exempt: bool,
1065 since: Option<Instant>,
1067}
1068
1069impl Lane {
1070 fn new(codec: VideoCodec, specs: Vec<LayerSpec>, cid: String, backup: bool) -> Lane {
1071 Lane {
1072 codec,
1073 cid,
1074 mid: None,
1075 pt: None,
1076 layers: specs
1077 .into_iter()
1078 .map(|l| Layer::new(l, codec, first_seq(), !backup))
1079 .collect(),
1080 backup,
1081 on: false,
1082 exempt: false,
1083 since: None,
1084 }
1085 }
1086
1087 fn rids(&self) -> Vec<String> {
1088 self.layers.iter().map(|l| l.spec.rid.clone()).collect()
1089 }
1090
1091 fn video_layers(&self) -> Vec<VideoLayer> {
1092 self.layers
1093 .iter()
1094 .enumerate()
1095 .map(|(k, l)| VideoLayer {
1096 quality: quality(k),
1097 width: l.spec.width,
1098 height: l.spec.height,
1099 bitrate: l.spec.max_kbps.saturating_mul(1000),
1100 rid: l.spec.rid.clone(),
1101 ..VideoLayer::default()
1102 })
1103 .collect()
1104 }
1105
1106 fn reset_send(&mut self) {
1108 self.mid = None;
1109 self.pt = None;
1110 for l in &mut self.layers {
1111 l.ssrc = None;
1112 }
1113 }
1114}
1115
1116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1117enum State {
1118 Pending,
1120 Requested { since: Instant },
1122 Published,
1124 Live,
1126}
1127
1128type Reply = (
1130 oneshot::Sender<Result<VideoPublication, VideoError>>,
1131 mpsc::UnboundedReceiver<VideoControl>,
1132);
1133
1134struct Publication {
1135 id: u64,
1136 source: VideoSource,
1137 capture: (u32, u32),
1138 state: State,
1139 track_sid: Option<String>,
1140 lanes: Vec<Lane>,
1142 rtp_base: u32,
1143 control: mpsc::UnboundedSender<VideoControl>,
1144 reply: Option<Reply>,
1146 replaces: Vec<String>,
1148 unconfirmed: Option<TrackInfo>,
1151 muted: bool,
1153}
1154
1155impl Publication {
1156 fn tell(&self, c: VideoControl) {
1157 let _ = self.control.send(c);
1158 }
1159
1160 fn rtp_ts(&self, capture_us: u64) -> u32 {
1161 let ticks = capture_us.wrapping_mul(90) / 1000;
1163 self.rtp_base.wrapping_add(ticks as u32)
1164 }
1165
1166 fn cid(&self) -> &str {
1168 &self.lanes[0].cid
1169 }
1170
1171 fn codec(&self) -> VideoCodec {
1173 self.lanes[0].codec
1174 }
1175
1176 fn take_mids(&mut self) -> Vec<String> {
1178 self.lanes.iter_mut().filter_map(|l| l.mid.take()).collect()
1179 }
1180
1181 fn add_track(&self) -> AddTrackRequest {
1184 let layers = self.lanes[0].video_layers();
1185 let (w, h) = self.lanes[0]
1186 .layers
1187 .last()
1188 .map_or((0, 0), |l| (l.spec.width, l.spec.height));
1189 AddTrackRequest {
1190 cid: self.cid().to_owned(),
1191 name: track_name(self.source).to_owned(),
1192 r#type: TrackType::Video as i32,
1193 source: track_source(self.source) as i32,
1194 width: w,
1195 height: h,
1196 layers,
1197 simulcast_codecs: self
1198 .lanes
1199 .iter()
1200 .map(|l| SimulcastCodec {
1201 codec: mime(l.codec).to_owned(),
1202 cid: l.cid.clone(),
1203 layers: l.video_layers(),
1204 ..SimulcastCodec::default()
1205 })
1206 .collect(),
1207 ..AddTrackRequest::default()
1208 }
1209 }
1210}
1211
1212fn new_cid(source: VideoSource) -> String {
1213 let p = match source {
1214 VideoSource::Camera => "cam",
1215 VideoSource::ScreenShare => "scr",
1216 };
1217 format!("{p}-{:08x}", rand::random::<u32>())
1218}
1219
1220fn first_seq() -> u64 {
1221 u64::from(rand::random::<u16>() & 0x7fff)
1222}
1223
1224fn quality(i: usize) -> i32 {
1226 i.min(2) as i32
1227}
1228
1229fn names_codec(name: &str, codec: VideoCodec) -> bool {
1231 let n = name.rsplit('/').next().unwrap_or(name);
1232 n.eq_ignore_ascii_case(codec.as_str())
1233}
1234
1235#[allow(deprecated)]
1240fn lane_wanted(
1241 u: &SubscribedQualityUpdate,
1242 codec: VideoCodec,
1243 backup: bool,
1244 n: usize,
1245) -> Vec<bool> {
1246 let named = u
1247 .subscribed_codecs
1248 .iter()
1249 .find(|c| names_codec(&c.codec, codec))
1250 .map(|c| c.qualities.as_slice());
1251 let qualities = match named {
1252 Some(q) => q,
1253 None if backup => &[],
1254 None => u.subscribed_qualities.as_slice(),
1255 };
1256 (0..n)
1257 .map(|k| {
1258 let q = qualities.iter().find(|q| q.quality == quality(k));
1259 if backup {
1260 q.is_some_and(|q| q.enabled)
1261 } else {
1262 q.is_none_or(|q| q.enabled)
1263 }
1264 })
1265 .collect()
1266}
1267
1268pub(crate) fn backup_layers_for(plan: &[LayerSpec], old: &[LayerSpec]) -> Vec<LayerSpec> {
1272 let tl = old.first().map_or(1, |l| l.temporal_layers);
1273 let mut out: Vec<LayerSpec> = plan
1274 .iter()
1275 .filter_map(|n| {
1276 let o = old.iter().find(|o| o.rid == n.rid)?;
1277 let mut l = n.clone();
1278 l.temporal_layers = o.temporal_layers;
1279 Some(l)
1280 })
1281 .collect();
1282 if out.is_empty()
1283 && let Some(l) = plan.first()
1284 {
1285 let mut l = l.clone();
1286 l.temporal_layers = tl;
1287 out.push(l);
1288 }
1289 out
1290}
1291
1292pub(crate) struct Publisher {
1294 frames_tx: mpsc::Sender<VideoIn>,
1295 frames_rx: mpsc::Receiver<VideoIn>,
1296 lease_tx: mpsc::UnboundedSender<LeaseDone>,
1297 lease_rx: mpsc::UnboundedReceiver<LeaseDone>,
1298 ends_tx: mpsc::UnboundedSender<ProducerEnd>,
1299 ends_rx: mpsc::UnboundedReceiver<ProducerEnd>,
1300 fallback_tx: mpsc::UnboundedSender<ProducerFallback>,
1301 fallback_rx: mpsc::UnboundedReceiver<ProducerFallback>,
1302 pubs: Vec<Publication>,
1303 next_id: u64,
1304 leases: Leases,
1305 released_on_end: Leases,
1310 policy: Option<MediaPolicy>,
1312 allowed: (bool, bool),
1314 alloc: Allocator,
1315 estimate: Option<u64>,
1316 desired: u64,
1317 caps: VideoCaps,
1318 backup_caps: BackupCaps,
1320 pub(crate) stats: Arc<Mutex<VideoSendStats>>,
1321 malformed_logged: bool,
1322 backup_done_ms: u64,
1324}
1325
1326impl std::fmt::Debug for Publisher {
1327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1328 f.debug_struct("Publisher")
1329 .field("publications", &self.pubs.len())
1330 .field("leases", &self.leases)
1331 .finish_non_exhaustive()
1332 }
1333}
1334
1335fn with(leases: Leases, source: VideoSource, on: bool) -> Leases {
1337 let (c, s) = (leases.camera, leases.screen);
1338 match source {
1339 VideoSource::Camera => Leases::new(on, s),
1340 VideoSource::ScreenShare => Leases::new(c, on),
1341 }
1342}
1343
1344fn has(leases: Leases, source: VideoSource) -> bool {
1346 match source {
1347 VideoSource::Camera => leases.camera,
1348 VideoSource::ScreenShare => leases.screen,
1349 }
1350}
1351
1352impl Publisher {
1353 pub(crate) fn new(stats: Arc<Mutex<VideoSendStats>>) -> Publisher {
1354 let (frames_tx, frames_rx) = mpsc::channel(VIDEO_QUEUE);
1355 let (lease_tx, lease_rx) = mpsc::unbounded_channel();
1356 let (ends_tx, ends_rx) = mpsc::unbounded_channel();
1357 let (fallback_tx, fallback_rx) = mpsc::unbounded_channel();
1358 Publisher {
1359 frames_tx,
1360 frames_rx,
1361 lease_tx,
1362 lease_rx,
1363 ends_tx,
1364 ends_rx,
1365 fallback_tx,
1366 fallback_rx,
1367 pubs: Vec::new(),
1368 next_id: 1,
1369 leases: Leases::none(),
1370 released_on_end: Leases::none(),
1371 policy: None,
1372 allowed: (false, false),
1373 alloc: Allocator::default(),
1374 estimate: None,
1375 desired: 0,
1376 caps: VideoCaps::default(),
1377 backup_caps: BackupCaps::default(),
1378 stats,
1379 malformed_logged: false,
1380 backup_done_ms: 0,
1381 }
1382 }
1383
1384 pub(crate) async fn recv(&mut self) -> VideoStep {
1386 tokio::select! {
1387 Some(f) = self.frames_rx.recv() => VideoStep::Frame(f),
1388 Some(l) = self.lease_rx.recv() => VideoStep::Lease(l),
1389 Some(e) = self.ends_rx.recv() => VideoStep::End(e),
1390 Some(b) = self.fallback_rx.recv() => VideoStep::Fallback(b),
1391 }
1392 }
1393
1394 pub(crate) fn joined_with(&mut self, policy: Option<&MediaPolicy>) {
1397 self.allowed = policy.map_or((false, false), |p| (p.camera_allowed, p.screen_allowed));
1398 self.policy = policy.cloned();
1399 }
1400
1401 pub(crate) fn may_send(&self) -> bool {
1403 cfg!(feature = "video-core")
1405 && self
1406 .policy
1407 .as_ref()
1408 .is_some_and(|p| p.video_enabled && (self.allowed.0 || self.allowed.1))
1409 }
1410
1411 fn set_lease(&mut self, source: VideoSource, on: bool) {
1412 self.leases = with(self.leases, source, on);
1413 }
1414
1415 fn effective_policy(&self) -> Option<MediaPolicy> {
1416 let mut p = self.policy.clone()?;
1417 p.camera_allowed = self.allowed.0;
1418 p.screen_allowed = self.allowed.1;
1419 Some(p)
1420 }
1421
1422 fn stat(&self, f: impl FnOnce(&mut VideoSendStats)) {
1423 if let Ok(mut s) = self.stats.lock() {
1424 f(&mut s);
1425 }
1426 }
1427
1428 fn backup_ms(&self, now: Instant) -> u64 {
1430 let running: u64 = self
1431 .pubs
1432 .iter()
1433 .flat_map(|p| &p.lanes)
1434 .filter_map(|l| l.since.filter(|_| l.on))
1435 .map(|t| now.saturating_duration_since(t).as_millis() as u64)
1436 .sum();
1437 self.backup_done_ms + running
1438 }
1439
1440 pub(crate) fn command(&mut self, cx: &mut Ctx<'_>, api: LeaseApi, cmd: VideoCmd) {
1443 match cmd {
1444 VideoCmd::Lease { source, on, reply } => {
1445 if on {
1446 match self.effective_policy() {
1447 Some(p) if p.video_enabled && allowed(source, &p) => {}
1448 _ => {
1449 let _ = reply.send(Err(VideoError::NotAllowed));
1450 return;
1451 }
1452 }
1453 }
1454 if on {
1455 self.released_on_end = with(self.released_on_end, source, false);
1456 }
1457 self.lease(api, source, on, Some(reply), false);
1458 }
1459 VideoCmd::Publish { req, reply } => self.publish(cx, req, reply),
1460 VideoCmd::Unpublish {
1461 source,
1462 release,
1463 reason,
1464 reply,
1465 } => {
1466 let found = self.pubs.iter().position(|p| p.source == source);
1467 match found {
1468 Some(i) => {
1469 let p = self.pubs.remove(i);
1470 tracing::info!(target: "sew_call_client", source = ?source, %reason, release, "video unpublished by the app");
1471 self.end(cx, p, &reason);
1472 }
1473 None if !release => {
1474 let _ = reply.send(Err(VideoError::NotPublished));
1475 return;
1476 }
1477 None => {}
1478 }
1479 if release && found.is_none() && has(self.released_on_end, source) {
1480 let _ = reply.send(Ok(()));
1482 } else if release {
1483 self.released_on_end = with(self.released_on_end, source, true);
1484 self.lease(api, source, false, Some(reply), false);
1485 } else {
1486 let _ = reply.send(Ok(()));
1487 }
1488 }
1489 VideoCmd::Caps(c) => {
1490 self.caps = c;
1491 self.reallocate(cx);
1492 }
1493 VideoCmd::BackupCaps(c) => {
1494 if c != self.backup_caps {
1495 self.backup_caps = c;
1496 self.reallocate(cx);
1497 }
1498 }
1499 VideoCmd::Mute { source, muted } => {
1500 for p in self.pubs.iter_mut().filter(|p| p.source == source) {
1501 if p.muted == muted {
1502 continue;
1503 }
1504 p.muted = muted;
1505 if p.state == State::Published
1506 && let Some(sid) = &p.track_sid
1507 {
1508 cx.session.mute(sid, muted);
1509 }
1510 tracing::info!(target: "sew_call_client", source = ?source, muted, "video muted");
1511 }
1512 }
1513 }
1514 }
1515
1516 fn lease(
1517 &mut self,
1518 api: LeaseApi,
1519 source: VideoSource,
1520 on: bool,
1521 reply: Option<oneshot::Sender<Result<(), VideoError>>>,
1522 relink: bool,
1523 ) {
1524 let Some(token) = api.token else {
1525 if let Some(r) = reply {
1526 let _ = r.send(Err(VideoError::Lease {
1527 status: 0,
1528 code: "no_call_credential".to_owned(),
1529 }));
1530 }
1531 return;
1532 };
1533 let tx = self.lease_tx.clone();
1534 let (video, stream) = match source {
1535 VideoSource::Camera => (Some(on), None),
1536 VideoSource::ScreenShare => (None, Some(on)),
1537 };
1538 tokio::spawn(async move {
1539 let result = crate::api::video_state(&api.http, &api.base, &token, video, stream)
1540 .await
1541 .map_err(|r| VideoError::from_lease(&r));
1542 let _ = tx.send(LeaseDone {
1543 source,
1544 on,
1545 result,
1546 reply,
1547 relink,
1548 });
1549 });
1550 }
1551
1552 pub(crate) fn on_producer_end(&mut self, cx: &mut Ctx<'_>, api: LeaseApi, e: ProducerEnd) {
1555 let Some(i) = self.pubs.iter().position(|p| p.id == e.publication) else {
1556 return;
1557 };
1558 let p = self.pubs.remove(i);
1559 let source = p.source;
1560 tracing::info!(target: "sew_call_client", source = ?source, reason = %e.reason, "the producer ended its video");
1561 self.end(cx, p, &e.reason);
1562 self.released_on_end = with(self.released_on_end, source, true);
1563 self.lease(api, source, false, None, false);
1564 }
1565
1566 pub(crate) fn on_producer_fallback(&mut self, cx: &mut Ctx<'_>, f: ProducerFallback) {
1570 let Some(i) = self.pubs.iter().position(|p| p.id == f.publication) else {
1571 return;
1572 };
1573 if f.layers.is_empty() {
1574 return;
1575 }
1576 let now = cx.now;
1577 self.backup_stop(i, now);
1578 let p = &mut self.pubs[i];
1579 tracing::info!(target: "sew_call_client", source = ?p.source, from = p.codec().as_str(), to = f.codec.as_str(), "video published again in one codec");
1580 p.lanes.truncate(1);
1581 p.lanes[0].codec = f.codec;
1582 self.republish(cx, i, f.layers);
1583 }
1584
1585 pub(crate) fn on_lease(&mut self, cx: &mut Ctx<'_>, d: LeaseDone) {
1586 if d.result.is_ok() {
1587 self.set_lease(d.source, d.on);
1588 tracing::info!(target: "sew_call_client", source = ?d.source, on = d.on, "video lease");
1589 } else if d.on {
1590 tracing::info!(target: "sew_call_client", source = ?d.source, error = ?d.result, "video lease refused");
1591 }
1592 if d.relink {
1593 match &d.result {
1594 Ok(()) => {
1595 for i in 0..self.pubs.len() {
1596 if self.pubs[i].source == d.source && self.pubs[i].state == State::Pending {
1597 self.request(cx, i);
1598 }
1599 }
1600 }
1601 Err(e) => {
1602 let reason = e.code().to_owned();
1603 let gone: Vec<Publication> = {
1604 let (gone, keep) = std::mem::take(&mut self.pubs)
1605 .into_iter()
1606 .partition(|p| p.source == d.source);
1607 self.pubs = keep;
1608 gone
1609 };
1610 for p in gone {
1611 self.end(cx, p, &reason);
1612 }
1613 }
1614 }
1615 }
1616 if let Some(r) = d.reply {
1617 let _ = r.send(d.result);
1618 }
1619 }
1620
1621 fn publish(
1622 &mut self,
1623 cx: &mut Ctx<'_>,
1624 req: VideoPublish,
1625 reply: oneshot::Sender<Result<VideoPublication, VideoError>>,
1626 ) {
1627 match self.effective_policy() {
1628 Some(p)
1630 if cfg!(feature = "video-core") && p.video_enabled && allowed(req.source, &p) => {}
1631 _ => {
1632 let _ = reply.send(Err(VideoError::NotAllowed));
1633 return;
1634 }
1635 }
1636 if self.pubs.iter().any(|p| p.source == req.source) {
1637 let _ = reply.send(Err(VideoError::AlreadyPublished));
1638 return;
1639 }
1640 if req.layers.is_empty() {
1641 let _ = reply.send(Err(VideoError::CodecUnavailable));
1642 return;
1643 }
1644 let id = self.next_id;
1645 self.next_id += 1;
1646 let (control, control_rx) = mpsc::unbounded_channel();
1647 let mut lanes = vec![Lane::new(req.codec, req.layers, new_cid(req.source), false)];
1648 if let Some(b) = req
1650 .backup
1651 .filter(|b| b.codec != req.codec && !b.layers.is_empty())
1652 {
1653 lanes.push(Lane::new(b.codec, b.layers, new_cid(req.source), true));
1654 }
1655 self.pubs.push(Publication {
1656 id,
1657 source: req.source,
1658 capture: (req.capture_width, req.capture_height),
1659 state: State::Pending,
1660 track_sid: None,
1661 lanes,
1662 rtp_base: rand::random(),
1663 control,
1664 reply: Some((reply, control_rx)),
1665 replaces: Vec::new(),
1666 unconfirmed: None,
1667 muted: false,
1668 });
1669 let i = self.pubs.len() - 1;
1670 self.request(cx, i);
1671 }
1672
1673 fn request(&mut self, cx: &mut Ctx<'_>, i: usize) {
1676 if !cx.joined || cx.pc.is_none() {
1677 self.pubs[i].state = State::Pending;
1678 return;
1679 }
1680 let leases = self.leases;
1681 let p = &mut self.pubs[i];
1682 let mut add = p.add_track();
1683 match check_publish(&mut add, leases) {
1684 Ok(()) => {
1685 cx.session.add_track(add);
1686 p.state = State::Requested { since: cx.now };
1687 }
1688 Err(e) => {
1689 let p = self.pubs.remove(i);
1690 let err = match e {
1691 PublishRefused::NoLease => VideoError::NoLease,
1692 PublishRefused::Downgraded => VideoError::Downgraded,
1693 other => VideoError::PublishFailed(other.to_string()),
1694 };
1695 self.fail(cx, p, err);
1696 }
1697 }
1698 }
1699
1700 fn fail(&mut self, cx: &mut Ctx<'_>, mut p: Publication, err: VideoError) {
1702 self.alloc.forget(p.id);
1703 let code = err.code().to_owned();
1704 match p.reply.take() {
1705 Some((reply, _)) => {
1706 let _ = reply.send(Err(err));
1707 }
1708 None => self.end(cx, p, &code),
1709 }
1710 }
1711
1712 fn end(&mut self, cx: &mut Ctx<'_>, mut p: Publication, reason: &str) {
1714 self.alloc.forget(p.id);
1715 for l in p.lanes.iter_mut().filter(|l| l.on) {
1716 l.on = false;
1717 if let Some(t) = l.since.take() {
1718 self.backup_done_ms += cx.now.saturating_duration_since(t).as_millis() as u64;
1719 }
1720 }
1721 if let Some(pc) = cx.pc.as_deref_mut() {
1722 for mid in p.take_mids() {
1723 pc.stop_send(&mid);
1724 }
1725 for mid in std::mem::take(&mut p.replaces) {
1726 pc.stop_send(&mid);
1727 }
1728 }
1729 if let Some((reply, _)) = p.reply.take() {
1730 let _ = reply.send(Err(VideoError::PublishFailed(reason.to_owned())));
1731 }
1732 p.tell(VideoControl::Ended {
1733 reason: reason.to_owned(),
1734 });
1735 let _ = cx.events.send(CallEvent::LocalVideo(LocalVideo {
1736 source: p.source,
1737 on: false,
1738 reason: Some(reason.to_owned()),
1739 }));
1740 self.reallocate(cx);
1741 }
1742
1743 fn backup_transitions(&mut self, i: usize, now: Instant) {
1749 let p = &mut self.pubs[i];
1750 let Some(b) = p.lanes.get_mut(1) else {
1751 return;
1752 };
1753 let any = b.layers.iter().any(|l| l.wanted);
1754 if any && !b.on {
1755 b.on = true;
1756 b.exempt = true;
1757 b.since = Some(now);
1758 let mut start = Vec::new();
1759 for l in &mut b.layers {
1760 l.need_key = true;
1761 l.rate = None;
1762 l.told = None;
1763 if l.wanted {
1764 start.push(l.spec.clone());
1765 }
1766 }
1767 tracing::info!(target: "sew_call_client", source = ?p.source, codec = b.codec.as_str(), layers = start.len(), "the backup starts");
1768 p.tell(VideoControl::BackupStart(start));
1769 self.stat(|s| s.backup_starts += 1);
1770 } else if !any && b.on {
1771 self.backup_stop(i, now);
1772 }
1773 }
1774
1775 fn backup_stop(&mut self, i: usize, now: Instant) {
1777 let p = &mut self.pubs[i];
1778 let Some(b) = p.lanes.get_mut(1).filter(|b| b.on) else {
1779 return;
1780 };
1781 b.on = false;
1782 b.exempt = false;
1783 for l in &mut b.layers {
1784 l.rate = None;
1785 l.told = None;
1786 }
1787 let ran = b
1788 .since
1789 .take()
1790 .map_or(0, |t| now.saturating_duration_since(t).as_millis() as u64);
1791 tracing::info!(target: "sew_call_client", source = ?p.source, ran_ms = ran, "the backup stops");
1792 p.tell(VideoControl::BackupStop);
1793 self.backup_done_ms += ran;
1794 let total = self.backup_ms(now);
1795 self.stat(|s| {
1796 s.backup_stops += 1;
1797 s.backup_ms = total;
1798 });
1799 }
1800
1801 fn backup_reset(&mut self, i: usize, now: Instant) {
1804 self.backup_stop(i, now);
1805 if let Some(b) = self.pubs[i].lanes.get_mut(1) {
1806 for l in &mut b.layers {
1807 l.wanted = false;
1808 }
1809 }
1810 }
1811
1812 pub(crate) fn on_track_published(
1816 &mut self,
1817 cx: &mut Ctx<'_>,
1818 cid: &str,
1819 track: &TrackInfo,
1820 ) -> bool {
1821 let Some(i) = self.pubs.iter().position(|p| p.cid() == cid) else {
1822 return false;
1823 };
1824 if !matches!(self.pubs[i].state, State::Requested { .. }) {
1825 return true;
1826 }
1827 let gcm = track.encryption == sew_lkproto::livekit::encryption::Type::Gcm as i32;
1828 let confirmed = match cx.keys {
1829 Some(k) => k.published(track),
1830 None => gcm,
1833 };
1834 if !confirmed {
1835 let p = self.pubs.remove(i);
1837 self.fail(cx, p, VideoError::Downgraded);
1838 return true;
1839 }
1840 let p = &mut self.pubs[i];
1841 if p.lanes.len() > 1
1842 && !track.codecs.is_empty()
1843 && !track
1844 .codecs
1845 .iter()
1846 .any(|c| names_codec(&c.mime_type, p.lanes[1].codec))
1847 {
1848 tracing::info!(target: "sew_call_client", source = ?p.source, "the SFU took no backup codec: one codec");
1850 p.lanes.truncate(1);
1851 }
1852 p.unconfirmed = cx.keys.is_none().then(|| track.clone());
1853 p.track_sid = Some(track.sid.clone());
1854 p.state = State::Published;
1855 for l in &mut p.lanes {
1856 l.reset_send();
1857 }
1858 if let Some(pc) = cx.pc.as_deref_mut() {
1859 for l in &p.lanes {
1861 pc.add_send_video(cx.stream, &l.cid, &l.rids());
1862 }
1863 }
1864 tracing::info!(target: "sew_call_client", source = ?p.source, codec = p.codec().as_str(), backup = p.lanes.get(1).map(|l| l.codec.as_str()), layers = p.lanes[0].layers.len(), "video published");
1865 if p.muted {
1866 cx.session.mute(&track.sid, true);
1868 }
1869 if let Some((reply, control)) = p.reply.take() {
1870 let handle = VideoPublication {
1871 source: p.source,
1872 id: p.id,
1873 track_sid: track.sid.clone(),
1874 published_mime: if track.mime_type.is_empty() {
1875 track
1876 .codecs
1877 .first()
1878 .map(|c| c.mime_type.clone())
1879 .unwrap_or_default()
1880 } else {
1881 track.mime_type.clone()
1882 },
1883 frames: self.frames_tx.clone(),
1884 control,
1885 stats: self.stats.clone(),
1886 ends: self.ends_tx.clone(),
1887 fallbacks: self.fallback_tx.clone(),
1888 };
1889 if reply.send(Ok(handle)).is_err() {
1890 let p = self.pubs.remove(i);
1892 tracing::info!(target: "sew_call_client", source = ?p.source, "video published with nobody to produce it");
1893 self.end(cx, p, PUBLISHER_GONE);
1894 return true;
1895 }
1896 }
1897 let p = &self.pubs[i];
1898 let _ = cx.events.send(CallEvent::LocalVideo(LocalVideo {
1899 source: p.source,
1900 on: true,
1901 reason: None,
1902 }));
1903 true
1904 }
1905
1906 pub(crate) fn on_answer(&mut self, cx: &mut Ctx<'_>) {
1908 let Some(pc) = cx.pc.as_deref_mut() else {
1909 return;
1910 };
1911 let resolve = |pc: &mut Pc, l: &Lane| -> Option<(String, u8, Vec<u32>)> {
1913 let mid = pc.mid_for_track(&l.cid)?;
1914 let pt = pc.video_pt(&mid, l.codec)?;
1915 let ssrcs: Option<Vec<u32>> = l
1916 .layers
1917 .iter()
1918 .map(|x| pc.tx_ssrc_rid(&mid, &x.spec.rid))
1919 .collect();
1920 Some((mid, pt, ssrcs?))
1921 };
1922 let mut live = false;
1923 for p in &mut self.pubs {
1924 if p.state != State::Published {
1925 continue;
1926 }
1927 let Some(primary) = resolve(pc, &p.lanes[0]) else {
1928 continue;
1929 };
1930 let backup = p.lanes.get(1).map(|l| resolve(pc, l));
1931 if let Some(None) = backup {
1932 tracing::warn!(target: "sew_call_client", source = ?p.source, "the backup's send section was not negotiated: one codec");
1934 if let Some(mid) = pc.mid_for_track(&p.lanes[1].cid) {
1935 pc.stop_send(&mid);
1936 }
1937 if p.lanes[1].on {
1938 p.tell(VideoControl::BackupStop);
1939 }
1940 p.lanes.truncate(1);
1941 }
1942 let found = std::iter::once(primary).chain(backup.flatten());
1943 for (l, (mid, pt, ssrcs)) in p.lanes.iter_mut().zip(found) {
1944 for (x, s) in l.layers.iter_mut().zip(ssrcs) {
1945 x.ssrc = Some(s);
1946 x.need_key = true;
1947 }
1948 l.mid = Some(mid);
1949 l.pt = Some(pt);
1950 }
1951 p.state = State::Live;
1952 for old in std::mem::take(&mut p.replaces) {
1953 pc.stop_send(&old);
1954 }
1955 live = true;
1956 }
1957 if live {
1958 self.reallocate(cx);
1959 for i in 0..self.pubs.len() {
1960 if self.pubs[i].state != State::Live {
1961 continue;
1962 }
1963 for n in 0..self.pubs[i].lanes.len() {
1964 let rids = self.pubs[i].lanes[n].rids();
1965 for rid in rids {
1966 self.ask_keyframe(i, n, &rid, cx.now, true);
1967 }
1968 }
1969 }
1970 }
1971 }
1972
1973 pub(crate) fn on_keys(&mut self, cx: &mut Ctx<'_>) {
1976 let Some(k) = cx.keys else { return };
1977 let refused: Vec<usize> = self
1978 .pubs
1979 .iter_mut()
1980 .enumerate()
1981 .filter_map(|(i, p)| {
1982 let t = p.unconfirmed.take()?;
1983 (!k.published(&t)).then_some(i)
1984 })
1985 .collect();
1986 for i in refused.into_iter().rev() {
1987 let p = self.pubs.remove(i);
1988 self.end(cx, p, VideoError::Downgraded.code());
1989 }
1990 }
1991
1992 pub(crate) fn on_track_unpublished(&mut self, cx: &mut Ctx<'_>, sid: &str) {
1994 let Some(i) = self
1995 .pubs
1996 .iter()
1997 .position(|p| p.track_sid.as_deref() == Some(sid))
1998 else {
1999 return;
2000 };
2001 let p = self.pubs.remove(i);
2002 tracing::info!(target: "sew_call_client", source = ?p.source, "the SFU unpublished our video");
2003 self.end(cx, p, "server_unpublished");
2004 }
2005
2006 pub(crate) fn on_subscribed_quality(&mut self, cx: &mut Ctx<'_>, u: &SubscribedQualityUpdate) {
2009 if self.policy.as_ref().is_some_and(|p| !p.dynacast) {
2010 return;
2011 }
2012 let Some(i) = self
2013 .pubs
2014 .iter()
2015 .position(|p| p.track_sid.as_deref() == Some(u.track_sid.as_str()))
2016 else {
2017 return;
2018 };
2019 let mut changed = false;
2020 for lane in &mut self.pubs[i].lanes {
2021 let wanted = lane_wanted(u, lane.codec, lane.backup, lane.layers.len());
2022 for (l, w) in lane.layers.iter_mut().zip(wanted) {
2023 if w != l.wanted {
2024 l.wanted = w;
2025 changed = true;
2026 }
2027 }
2028 }
2029 if changed {
2030 tracing::debug!(target: "sew_call_client", track = %u.track_sid, "dynacast");
2031 self.backup_transitions(i, cx.now);
2032 self.reallocate(cx);
2033 }
2034 }
2035
2036 pub(crate) fn on_keyframe_request(&mut self, now: Instant, mid: &str, rid: Option<&str>) {
2039 let Some((i, n)) = self.pubs.iter().enumerate().find_map(|(i, p)| {
2040 p.lanes
2041 .iter()
2042 .position(|l| l.mid.as_deref() == Some(mid))
2043 .map(|n| (i, n))
2044 }) else {
2045 return;
2046 };
2047 self.stat(|s| s.sfu_keyframe_requests += 1);
2048 let rids: Vec<String> = match rid {
2049 Some(r) => vec![r.to_owned()],
2050 None => self.pubs[i].lanes[n].rids(),
2051 };
2052 let (source, backup) = (self.pubs[i].source, self.pubs[i].lanes[n].backup);
2053 for r in &rids {
2054 let key = if backup {
2055 format!("{}/backup/{r}", source_name(source))
2056 } else {
2057 format!("{}/{r}", source_name(source))
2058 };
2059 self.stat(|s| *s.sfu_keyframe_requests_by_layer.entry(key).or_default() += 1);
2060 }
2061 for r in rids {
2062 self.ask_keyframe(i, n, &r, now, false);
2063 }
2064 }
2065
2066 fn ask_keyframe(&mut self, i: usize, n: usize, rid: &str, now: Instant, force: bool) {
2067 let p = &mut self.pubs[i];
2068 let Some(lane) = p.lanes.get_mut(n) else {
2069 return;
2070 };
2071 if lane.backup && !lane.on {
2072 return;
2074 }
2075 let backup = lane.backup;
2076 let Some(l) = lane.layers.iter_mut().find(|l| l.spec.rid == rid) else {
2077 return;
2078 };
2079 if !force
2080 && !l.key_sent_since_ask
2081 && l.last_key_ask
2082 .is_some_and(|t| now.saturating_duration_since(t) < KEYFRAME_EVERY)
2083 {
2084 return;
2085 }
2086 l.last_key_ask = Some(now);
2087 l.key_sent_since_ask = false;
2088 let rid = rid.to_owned();
2089 p.tell(if backup {
2090 VideoControl::BackupKeyframe { rid }
2091 } else {
2092 VideoControl::Keyframe { rid }
2093 });
2094 self.stat(|s| s.keyframes_asked += 1);
2095 }
2096
2097 pub(crate) fn on_estimate(&mut self, cx: &mut Ctx<'_>, bps: u64) {
2099 self.estimate = Some(bps);
2100 self.stat(|s| s.estimate_bps = bps);
2101 self.reallocate(cx);
2102 }
2103
2104 pub(crate) fn on_policy(&mut self, cx: &mut Ctx<'_>, api: &LeaseApi, policy: MediaPolicy) {
2106 let enabled = policy.video_enabled;
2107 self.policy = Some(policy);
2108 if !enabled {
2109 let gone = std::mem::take(&mut self.pubs);
2110 let sources: Vec<VideoSource> = gone.iter().map(|p| p.source).collect();
2111 for p in gone {
2112 self.end(cx, p, sew_proto::voice::reasons::VIDEO_DISABLED);
2113 }
2114 for s in sources {
2115 self.released_on_end = with(self.released_on_end, s, true);
2116 self.lease(api.clone(), s, false, None, false);
2117 }
2118 return;
2119 }
2120 let Some(policy) = self.policy.clone() else {
2121 return;
2122 };
2123 let backup_allowed = |c: VideoCodec| {
2126 policy.backup_codec
2127 && policy.dynacast
2128 && policy.codecs.iter().any(|p| codec_of_policy(*p) == Some(c))
2129 };
2130 for i in 0..self.pubs.len() {
2131 let p = &self.pubs[i];
2132 let mut plan = plan_source_layers(
2133 p.source,
2134 hint_of(p.source, &policy),
2135 p.capture.0,
2136 p.capture.1,
2137 );
2138 for l in &mut plan {
2139 if let Some(old) = p.lanes[0].layers.iter().find(|o| o.spec.rid == l.rid) {
2140 l.temporal_layers = old.spec.temporal_layers;
2141 }
2142 }
2143 let drop_backup = p.lanes.get(1).is_some_and(|b| !backup_allowed(b.codec));
2144 let same = plan.len() == p.lanes[0].layers.len()
2145 && plan.iter().zip(&p.lanes[0].layers).all(|(n, o)| {
2146 n.rid == o.spec.rid && n.width == o.spec.width && n.height == o.spec.height
2147 });
2148 if same && !drop_backup {
2149 let p = &mut self.pubs[i];
2151 for lane in &mut p.lanes {
2152 for o in &mut lane.layers {
2153 if let Some(n) = plan.iter().find(|n| n.rid == o.spec.rid) {
2154 o.spec.max_kbps = n.max_kbps;
2155 o.spec.fps = n.fps;
2156 }
2157 }
2158 }
2159 continue;
2160 }
2161 if drop_backup {
2162 tracing::info!(target: "sew_call_client", source = ?p.source, "the policy no longer allows the backup: one codec");
2163 self.backup_stop(i, cx.now);
2164 self.pubs[i].lanes.truncate(1);
2165 }
2166 self.republish(cx, i, plan);
2167 }
2168 self.reallocate(cx);
2169 }
2170
2171 fn republish(&mut self, cx: &mut Ctx<'_>, i: usize, plan: Vec<LayerSpec>) {
2175 if plan.is_empty() {
2176 return;
2177 }
2178 self.stat(|s| s.republishes += 1);
2179 self.backup_reset(i, cx.now);
2180 let p = &mut self.pubs[i];
2181 tracing::info!(target: "sew_call_client", source = ?p.source, layers = plan.len(), "video republished");
2182 self.alloc.forget(p.id);
2183 p.tell(VideoControl::Republish(plan.clone()));
2184 let mids = p.take_mids();
2185 if !mids.is_empty() {
2186 if let Some(pc) = cx.pc.as_deref_mut() {
2188 for old in std::mem::take(&mut p.replaces) {
2189 pc.stop_send(&old);
2190 }
2191 }
2192 p.replaces = mids;
2193 }
2194 let source = p.source;
2195 let backup = p.lanes.get(1).map(|b| {
2196 let old: Vec<LayerSpec> = b.layers.iter().map(|l| l.spec.clone()).collect();
2197 (b.codec, backup_layers_for(&plan, &old))
2198 });
2199 if let Some((codec, layers)) = backup {
2200 p.lanes[1] = Lane::new(codec, layers, new_cid(source), true);
2201 }
2202 let codec = p.lanes[0].codec;
2203 p.lanes[0] = Lane::new(codec, plan, new_cid(source), false);
2204 p.track_sid = None;
2205 self.request(cx, i);
2206 }
2207
2208 pub(crate) fn on_new_pc(&mut self, cx: &mut Ctx<'_>) {
2210 for i in 0..self.pubs.len() {
2211 self.backup_reset(i, cx.now);
2212 let p = &mut self.pubs[i];
2213 p.replaces.clear();
2214 p.track_sid = None;
2215 for lane in &mut p.lanes {
2216 lane.reset_send();
2217 lane.cid = new_cid(p.source);
2218 for l in &mut lane.layers {
2219 l.seq = first_seq();
2220 l.need_key = true;
2221 }
2222 }
2223 p.state = State::Pending;
2224 self.alloc.forget(p.id);
2225 self.request(cx, i);
2226 }
2227 }
2228
2229 pub(crate) fn on_teardown(&mut self) {
2231 let now = Instant::now();
2232 for i in 0..self.pubs.len() {
2233 self.backup_reset(i, now);
2234 let p = &mut self.pubs[i];
2235 p.replaces.clear();
2236 p.state = State::Pending;
2237 for lane in &mut p.lanes {
2238 lane.reset_send();
2239 }
2240 }
2241 }
2242
2243 pub(crate) fn on_rejoined(&mut self, policy: Option<&MediaPolicy>, api: &LeaseApi) {
2246 self.joined_with(policy);
2247 self.leases = Leases::none();
2248 let now = Instant::now();
2249 let mut sources: Vec<VideoSource> = Vec::new();
2250 for i in 0..self.pubs.len() {
2251 self.backup_reset(i, now);
2252 let p = &mut self.pubs[i];
2253 p.state = State::Pending;
2254 p.replaces.clear();
2255 for lane in &mut p.lanes {
2256 lane.mid = None;
2257 }
2258 if !sources.contains(&p.source) {
2259 sources.push(p.source);
2260 }
2261 }
2262 for s in sources {
2263 self.lease(api.clone(), s, true, None, true);
2264 }
2265 }
2266
2267 pub(crate) fn close(&mut self, reason: &str) {
2269 for mut p in std::mem::take(&mut self.pubs) {
2270 if let Some((reply, _)) = p.reply.take() {
2271 let _ = reply.send(Err(VideoError::Ended));
2272 }
2273 p.tell(VideoControl::Ended {
2274 reason: reason.to_owned(),
2275 });
2276 }
2277 self.leases = Leases::none();
2278 }
2279
2280 pub(crate) fn deadline(&self) -> Option<Instant> {
2283 let publishing = self
2284 .pubs
2285 .iter()
2286 .filter_map(|p| match p.state {
2287 State::Requested { since } => Some(since + PUBLISH_TIMEOUT),
2288 _ => None,
2289 })
2290 .min();
2291 match (publishing, self.alloc.deadline()) {
2292 (Some(a), Some(b)) => Some(a.min(b)),
2293 (a, b) => a.or(b),
2294 }
2295 }
2296
2297 pub(crate) fn on_timeout(&mut self, cx: &mut Ctx<'_>) {
2298 let late: Vec<usize> = self
2299 .pubs
2300 .iter()
2301 .enumerate()
2302 .filter(|(_, p)| {
2303 matches!(p.state, State::Requested { since } if cx.now >= since + PUBLISH_TIMEOUT)
2304 })
2305 .map(|(i, _)| i)
2306 .collect();
2307 for i in late.into_iter().rev() {
2308 let p = self.pubs.remove(i);
2309 tracing::info!(target: "sew_call_client", source = ?p.source, "no TrackPublished for the video");
2310 self.fail(
2311 cx,
2312 p,
2313 VideoError::PublishFailed("no answer from the media server".to_owned()),
2314 );
2315 }
2316 if self.alloc.deadline().is_some_and(|d| cx.now >= d) {
2317 self.reallocate(cx);
2318 }
2319 }
2320
2321 fn capped_layers(&self) -> Vec<AllocLayer> {
2329 let mut out = Vec::new();
2330 for p in &self.pubs {
2331 if p.state != State::Live {
2332 continue;
2333 }
2334 for (n, lane) in p.lanes.iter().enumerate() {
2335 if lane.backup && !lane.on {
2336 continue;
2337 }
2338 let max_layers = if lane.backup {
2339 let caps = [self.caps.max_layers, self.backup_caps.max_layers];
2340 caps.into_iter().flatten().min()
2341 } else {
2342 self.caps.max_layers
2343 }
2344 .map(|m| m.max(1));
2345 let lowest_wanted = lane.layers.iter().position(|l| l.wanted);
2346 for (k, l) in lane.layers.iter().enumerate() {
2347 if max_layers.is_some_and(|m| k >= usize::from(m)) {
2348 continue;
2349 }
2350 let policy_max = u64::from(l.spec.max_kbps) * 1000;
2351 let mut max = policy_max * u64::from(self.caps.bitrate_pct) / 100;
2352 let min_bps = super::alloc::min_bitrate_bps(l.spec.height.min(l.spec.width));
2353 let lowest = lowest_wanted == Some(k);
2354 if lowest {
2355 max = max.max(policy_max.min(min_bps));
2358 }
2359 out.push(AllocLayer {
2360 key: (p.id, n, k),
2361 screen: p.source == VideoSource::ScreenShare,
2362 max_bps: max.max(10_000),
2363 wanted: l.wanted,
2364 min_bps,
2365 exempt: lane.backup && lane.exempt && lowest,
2366 kept: lowest,
2367 });
2368 }
2369 }
2370 }
2371 out
2372 }
2373
2374 fn fps_of(&self, lane: &Lane, spec: &LayerSpec) -> u32 {
2376 let mut fps = spec.fps;
2377 if let Some(m) = self.caps.max_fps {
2378 fps = fps.min(m.max(1));
2379 }
2380 if lane.backup
2381 && let Some(m) = self.backup_caps.max_fps
2382 {
2383 fps = fps.min(m.max(1));
2384 }
2385 fps
2386 }
2387
2388 fn reallocate(&mut self, cx: &mut Ctx<'_>) {
2391 let layers = self.capped_layers();
2392 let est = self.estimate.unwrap_or(BWE_INITIAL_BPS);
2393 let grants = self.alloc.update(cx.now, est, &layers);
2394 let desired: u64 = layers.iter().filter(|l| l.wanted).map(|l| l.max_bps).sum();
2395 if desired != self.desired {
2396 self.desired = desired;
2397 if let Some(pc) = cx.pc.as_deref_mut() {
2398 pc.set_desired_bitrate(desired);
2399 }
2400 }
2401 let mut resumed: Vec<(usize, usize, String)> = Vec::new();
2402 let mut tells: Vec<(usize, VideoControl)> = Vec::new();
2403 for i in 0..self.pubs.len() {
2404 if self.pubs[i].state != State::Live {
2405 continue;
2406 }
2407 let id = self.pubs[i].id;
2408 for n in 0..self.pubs[i].lanes.len() {
2409 let fps: Vec<u32> = {
2410 let lane = &self.pubs[i].lanes[n];
2411 lane.layers
2412 .iter()
2413 .map(|l| self.fps_of(lane, &l.spec))
2414 .collect()
2415 };
2416 let lane = &mut self.pubs[i].lanes[n];
2417 if lane.backup && !lane.on {
2418 continue;
2419 }
2420 let mut rates = Vec::new();
2421 let mut changed = false;
2422 for (k, l) in lane.layers.iter_mut().enumerate() {
2423 let was = l.active();
2424 l.rate = grants.get(&(id, n, k)).copied();
2425 let rate = LayerRate {
2426 rid: l.spec.rid.clone(),
2427 active: l.active(),
2428 bitrate_bps: l.rate.map_or(0, |r| u32::try_from(r).unwrap_or(u32::MAX)),
2429 fps: fps[k],
2430 };
2431 if l.active() && !was {
2432 l.need_key = true;
2433 resumed.push((i, n, l.spec.rid.clone()));
2434 }
2435 if l.told.as_ref() != Some(&rate) {
2436 changed = true;
2437 l.told = Some(rate.clone());
2438 }
2439 rates.push(rate);
2440 }
2441 if lane.exempt && lane.layers.iter().any(Layer::active) {
2442 lane.exempt = false;
2444 }
2445 if changed {
2446 tells.push((
2447 i,
2448 if lane.backup {
2449 VideoControl::BackupRates(rates)
2450 } else {
2451 VideoControl::Rates(rates)
2452 },
2453 ));
2454 }
2455 }
2456 }
2457 for (i, c) in tells {
2458 self.pubs[i].tell(c);
2459 }
2460 for (i, n, rid) in resumed {
2461 self.ask_keyframe(i, n, &rid, cx.now, true);
2462 }
2463 }
2464
2465 pub(crate) fn on_frame(&mut self, cx: &mut Ctx<'_>, v: VideoIn) {
2470 let not_sent = |s: &mut VideoSendStats| s.frames_not_sent += 1;
2471 let Some(i) = self.pubs.iter().position(|p| p.id == v.publication) else {
2472 self.stat(not_sent);
2473 return;
2474 };
2475 let f = v.frame;
2476 let (Some(pc), Some(keys)) = (cx.pc.as_deref_mut(), cx.keys) else {
2477 self.stat(not_sent);
2478 return;
2479 };
2480 let p = &mut self.pubs[i];
2481 if p.state != State::Live || !cx.media_up || f.data.is_empty() {
2482 self.stat(not_sent);
2483 return;
2484 }
2485 let ts = p.rtp_ts(f.capture_us);
2486 let source = p.source;
2487 let Some(lane) = p.lanes.iter_mut().find(|l| l.codec == f.codec) else {
2488 self.stat(not_sent);
2489 return;
2490 };
2491 if lane.backup && !lane.on {
2492 self.stat(not_sent);
2494 return;
2495 }
2496 let (Some(mid), Some(pt)) = (lane.mid.clone(), lane.pt) else {
2497 self.stat(not_sent);
2498 return;
2499 };
2500 let codec = lane.codec;
2501 let backup = lane.backup;
2502 let Some(l) = lane.layers.iter_mut().find(|l| l.spec.rid == f.rid) else {
2503 self.stat(not_sent);
2504 return;
2505 };
2506 let Some(ssrc) = l.ssrc else {
2507 self.stat(not_sent);
2508 return;
2509 };
2510 if !l.active() || (l.need_key && !f.keyframe) {
2511 self.stat(not_sent);
2512 return;
2513 }
2514 let plain: Vec<u8> = match codec {
2515 VideoCodec::H264 => {
2516 let au = normalise(&f.data);
2517 if let Err(e) = check(&au) {
2518 if !self.malformed_logged {
2519 self.malformed_logged = true;
2520 tracing::warn!(target: "sew_call_client", error = %e, "an H.264 access unit broke the bitstream rules; dropped");
2521 }
2522 if let Ok(mut s) = self.stats.lock() {
2523 s.malformed += 1;
2524 s.frames_not_sent += 1;
2525 }
2526 return;
2527 }
2528 au
2529 }
2530 VideoCodec::Vp8 => f.data.to_vec(),
2531 };
2532 let mut sealed = Vec::with_capacity(plain.len() + 64);
2533 if keys
2534 .encrypt_video(frame_codec(codec), &plain, ssrc, ts, &mut sealed)
2535 .is_err()
2536 || sealed.is_empty()
2537 {
2538 self.stat(not_sent);
2540 return;
2541 }
2542 let packets = match &mut l.pack {
2543 Packetiser::Vp8(s) => s.packetize(
2544 &sealed,
2545 FrameLayer {
2546 keyframe: f.keyframe,
2547 temporal_id: f.temporal_id,
2548 layer_sync: f.layer_sync,
2549 },
2550 ),
2551 Packetiser::H264(s) => match s.packetize(&sealed, f.keyframe) {
2552 Ok(p) => p,
2553 Err(_) => {
2554 self.stat(not_sent);
2555 return;
2556 }
2557 },
2558 };
2559 let n = packets.len() as u64;
2560 let mut ok = true;
2561 for pk in packets {
2562 let seq = l.seq;
2563 l.seq += 1;
2564 if pc
2565 .write_video(
2566 &mid, &f.rid, pt, seq, ts, cx.now, pk.payload, pk.marker, pk.dd,
2567 )
2568 .is_err()
2569 {
2570 ok = false;
2571 }
2572 }
2573 if f.keyframe {
2574 l.need_key = false;
2575 l.key_sent_since_ask = true;
2576 }
2577 let key = if backup {
2578 format!("{}/backup/{}", source_name(source), f.rid)
2579 } else {
2580 format!("{}/{}", source_name(source), f.rid)
2581 };
2582 let backup_ms = backup.then(|| self.backup_ms(cx.now));
2583 if let Ok(mut s) = self.stats.lock() {
2584 if ok {
2585 *s.frames_sent.entry(key).or_default() += 1;
2586 *s.frames_by_codec
2587 .entry(codec.as_str().to_owned())
2588 .or_default() += 1;
2589 s.packets_sent += n;
2590 s.keyframes_sent += u64::from(f.keyframe);
2591 if f.keyframe {
2592 *s.keyframes_by_codec
2593 .entry(codec.as_str().to_owned())
2594 .or_default() += 1;
2595 }
2596 } else {
2597 s.frames_not_sent += 1;
2598 }
2599 if let Some(ms) = backup_ms {
2600 s.backup_ms = ms;
2601 }
2602 }
2603 }
2604}
2605
2606fn source_name(s: VideoSource) -> &'static str {
2607 match s {
2608 VideoSource::Camera => "camera",
2609 VideoSource::ScreenShare => "screen",
2610 }
2611}
2612
2613#[cfg(test)]
2614mod tests {
2615 use super::*;
2616 use sew_proto::voice::LayerHint;
2617
2618 fn hint() -> TrackHint {
2619 TrackHint {
2620 max_width: 1280,
2621 max_height: 720,
2622 max_fps: 30,
2623 layers: vec![
2624 LayerHint {
2625 rid: "q".into(),
2626 height: 180,
2627 max_kbps: 150,
2628 },
2629 LayerHint {
2630 rid: "h".into(),
2631 height: 360,
2632 max_kbps: 500,
2633 },
2634 LayerHint {
2635 rid: "f".into(),
2636 height: 720,
2637 max_kbps: 1700,
2638 },
2639 ],
2640 }
2641 }
2642
2643 #[test]
2644 fn layers_follow_the_hints_up_to_the_capture() {
2645 let l = plan_layers(&hint(), 1280, 720);
2646 let got: Vec<(&str, u32, u32, u32)> = l
2647 .iter()
2648 .map(|l| (l.rid.as_str(), l.width, l.height, l.max_kbps))
2649 .collect();
2650 assert_eq!(
2651 got,
2652 vec![
2653 ("q", 320, 180, 150),
2654 ("h", 640, 360, 500),
2655 ("f", 1280, 720, 1700)
2656 ]
2657 );
2658 assert!(l.iter().all(|l| l.fps == 30 && l.temporal_layers == 1));
2659 let l = plan_layers(&hint(), 640, 480);
2661 let got: Vec<(&str, u32, u32)> = l
2662 .iter()
2663 .map(|l| (l.rid.as_str(), l.width, l.height))
2664 .collect();
2665 assert_eq!(got, vec![("q", 240, 180), ("h", 480, 360)]);
2666 let l = plan_layers(&hint(), 160, 90);
2668 assert_eq!((l.len(), l[0].width, l[0].height), (1, 160, 90));
2669 let l = plan_layers(&hint(), 720, 1280);
2671 let got: Vec<(&str, u32, u32)> = l
2672 .iter()
2673 .map(|l| (l.rid.as_str(), l.width, l.height))
2674 .collect();
2675 assert_eq!(
2676 got,
2677 vec![("q", 180, 320), ("h", 360, 640), ("f", 720, 1280)]
2678 );
2679 }
2680
2681 fn screen_hint() -> TrackHint {
2684 TrackHint {
2685 max_width: 1920,
2686 max_height: 1080,
2687 max_fps: 15,
2688 layers: vec![
2689 LayerHint {
2690 rid: "h".into(),
2691 height: 540,
2692 max_kbps: 600,
2693 },
2694 LayerHint {
2695 rid: "f".into(),
2696 height: 1080,
2697 max_kbps: 2500,
2698 },
2699 ],
2700 }
2701 }
2702
2703 #[test]
2704 fn a_screen_shares_top_layer_is_the_captures_own_size() {
2705 let plan = |w, h| -> Vec<(String, u32, u32, u32, u32)> {
2706 plan_screen_layers(&screen_hint(), w, h)
2707 .into_iter()
2708 .map(|l| (l.rid, l.width, l.height, l.max_kbps, l.fps))
2709 .collect()
2710 };
2711 let l = |rid: &str, w, h, kbps| (rid.to_owned(), w, h, kbps, 15);
2712 assert_eq!(
2714 plan(1920, 1080),
2715 vec![l("h", 960, 540, 600), l("f", 1920, 1080, 2500)]
2716 );
2717 assert_eq!(
2719 plan(1728, 1080),
2720 vec![l("h", 864, 540, 600), l("f", 1728, 1080, 2500)]
2721 );
2722 assert_eq!(
2725 plan(1366, 768),
2726 vec![l("h", 960, 540, 600), l("f", 1366, 768, 1264)]
2727 );
2728 assert_eq!(
2729 plan(1440, 900),
2730 vec![l("h", 864, 540, 600), l("f", 1440, 900, 1736)]
2731 );
2732 assert_eq!(
2733 plan(1280, 800),
2734 vec![l("h", 864, 540, 600), l("f", 1280, 800, 1371)]
2735 );
2736 assert_eq!(
2737 plan(1680, 1050),
2738 vec![l("h", 864, 540, 600), l("f", 1680, 1050, 2363)]
2739 );
2740 assert_eq!(
2742 plan(1201, 801),
2743 vec![l("h", 808, 540, 600), l("f", 1200, 800, 1371)]
2744 );
2745 assert_eq!(plan(1024, 576), vec![l("h", 960, 540, 600)]);
2747 assert_eq!(plan(640, 360), vec![l("h", 640, 360, 600)]);
2749 assert_eq!(
2751 plan_source_layers(VideoSource::Camera, &screen_hint(), 1366, 768),
2752 plan_layers(&screen_hint(), 1366, 768)
2753 );
2754 let constrained = TrackHint {
2756 max_width: 1280,
2757 max_height: 720,
2758 max_fps: 15,
2759 layers: vec![screen_hint().layers[0].clone()],
2760 };
2761 let got = plan_screen_layers(&constrained, 1280, 720);
2762 assert_eq!(
2763 got.iter()
2764 .map(|l| (l.rid.as_str(), l.width, l.height))
2765 .collect::<Vec<_>>(),
2766 vec![("h", 960, 540)]
2767 );
2768 }
2769
2770 #[test]
2771 fn lease_refusals_map_to_the_plugin_codes() {
2772 let r = |status, reason: Option<&str>, retry| crate::api::LeaseRefused {
2773 status,
2774 code: Some("x".to_owned()),
2775 reason: reason.map(str::to_owned),
2776 retry_after: retry,
2777 detail: String::new(),
2778 };
2779 assert_eq!(
2780 VideoError::from_lease(&r(422, Some("video_slots_full"), None)).code(),
2781 "video_slots_full"
2782 );
2783 assert_eq!(
2784 VideoError::from_lease(&r(503, Some("media_busy"), Some(30))),
2785 VideoError::MediaBusy {
2786 retry_after: Some(30)
2787 }
2788 );
2789 assert_eq!(
2790 VideoError::from_lease(&r(503, Some("media_capacity"), None)).code(),
2791 "media_capacity"
2792 );
2793 assert_eq!(
2794 VideoError::from_lease(&r(403, Some("video_disabled"), None)).code(),
2795 "video_disabled"
2796 );
2797 assert_eq!(
2798 VideoError::from_lease(&r(422, Some("screen_slots_full"), None)).code(),
2799 "screen_slots_full"
2800 );
2801 assert_eq!(
2802 VideoError::from_lease(&r(403, None, None)),
2803 VideoError::Lease {
2804 status: 403,
2805 code: "x".to_owned()
2806 }
2807 );
2808 }
2809
2810 #[test]
2811 fn the_rtp_clock_is_the_capture_clock_at_90_khz() {
2812 let (control, _rx) = mpsc::unbounded_channel();
2813 let p = Publication {
2814 id: 1,
2815 source: VideoSource::Camera,
2816 capture: (1280, 720),
2817 state: State::Pending,
2818 track_sid: None,
2819 lanes: vec![Lane::new(VideoCodec::Vp8, Vec::new(), "c".into(), false)],
2820 rtp_base: u32::MAX - 10,
2821 control,
2822 reply: None,
2823 replaces: Vec::new(),
2824 unconfirmed: None,
2825 muted: false,
2826 };
2827 assert_eq!(p.rtp_ts(0), u32::MAX - 10);
2828 assert_eq!(p.rtp_ts(1_000_000), (u32::MAX - 10).wrapping_add(90_000));
2829 assert_eq!(p.rtp_ts(33_333), (u32::MAX - 10).wrapping_add(2_999));
2830 assert_eq!(quality(0), 0);
2831 assert_eq!(quality(2), 2);
2832 assert_eq!(quality(5), 2);
2833 }
2834
2835 fn three() -> Vec<LayerSpec> {
2836 vec![
2837 LayerSpec::new("q", 320, 180, 150, 30),
2838 LayerSpec::new("h", 640, 360, 500, 30),
2839 LayerSpec::new("f", 1280, 720, 1700, 30),
2840 ]
2841 }
2842
2843 fn with_backup(backup: Vec<LayerSpec>) -> Publication {
2845 let (control, _rx) = mpsc::unbounded_channel();
2846 Publication {
2847 id: 7,
2848 source: VideoSource::Camera,
2849 capture: (1280, 720),
2850 state: State::Pending,
2851 track_sid: None,
2852 lanes: vec![
2853 Lane::new(VideoCodec::H264, three(), "cam-a".into(), false),
2854 Lane::new(VideoCodec::Vp8, backup, "cam-b".into(), true),
2855 ],
2856 rtp_base: 0,
2857 control,
2858 reply: None,
2859 replaces: Vec::new(),
2860 unconfirmed: None,
2861 muted: false,
2862 }
2863 }
2864
2865 #[test]
2866 fn a_backup_is_one_add_track_with_two_codecs_on_their_own_cids_under_gcm() {
2867 let mut b = three();
2868 b.truncate(2);
2869 let p = with_backup(b);
2870 let mut add = p.add_track();
2871 check_publish(&mut add, Leases::new(true, false)).expect("leased");
2872 assert_eq!(add.cid, "cam-a");
2873 assert_eq!(
2874 add.encryption,
2875 sew_lkproto::livekit::encryption::Type::Gcm as i32,
2876 "one GCM request covers both codecs"
2877 );
2878 assert_eq!((add.width, add.height), (1280, 720));
2879 assert_eq!(add.layers.len(), 3);
2880 let codecs: Vec<(&str, &str, Vec<&str>)> = add
2881 .simulcast_codecs
2882 .iter()
2883 .map(|c| {
2884 (
2885 c.codec.as_str(),
2886 c.cid.as_str(),
2887 c.layers.iter().map(|l| l.rid.as_str()).collect(),
2888 )
2889 })
2890 .collect();
2891 assert_eq!(
2892 codecs,
2893 vec![
2894 ("video/H264", "cam-a", vec!["q", "h", "f"]),
2895 ("video/VP8", "cam-b", vec!["q", "h"]),
2896 ]
2897 );
2898 assert_eq!(add.simulcast_codecs[1].layers[1].quality, 1);
2899 assert!(p.lanes[1].layers.iter().all(|l| !l.wanted));
2901 assert!(p.lanes[0].layers.iter().all(|l| l.wanted));
2902 let mut add = p.add_track();
2904 assert_eq!(
2905 check_publish(&mut add, Leases::none()),
2906 Err(PublishRefused::NoLease)
2907 );
2908 }
2909
2910 #[test]
2911 #[allow(deprecated)]
2912 fn each_lane_reads_its_own_codecs_entry() {
2913 use sew_lkproto::livekit::{SubscribedCodec, SubscribedQuality};
2914 let q = |quality: i32, enabled: bool| SubscribedQuality { quality, enabled };
2915 let entry = |codec: &str, qs: Vec<SubscribedQuality>| SubscribedCodec {
2916 codec: codec.to_owned(),
2917 qualities: qs,
2918 };
2919 let update =
2920 |codecs: Vec<SubscribedCodec>, flat: Vec<SubscribedQuality>| SubscribedQualityUpdate {
2921 track_sid: "TR_x".to_owned(),
2922 subscribed_qualities: flat,
2923 subscribed_codecs: codecs,
2924 };
2925 let u = update(
2927 vec![entry("h264", vec![q(0, true), q(1, true), q(2, false)])],
2928 vec![],
2929 );
2930 assert_eq!(
2931 lane_wanted(&u, VideoCodec::H264, false, 3),
2932 vec![true, true, false]
2933 );
2934 assert_eq!(
2935 lane_wanted(&u, VideoCodec::Vp8, true, 2),
2936 vec![false, false]
2937 );
2938 let u = update(
2940 vec![
2941 entry("h264", vec![q(0, false), q(1, false), q(2, false)]),
2942 entry("video/vp8", vec![q(0, true), q(1, false)]),
2943 ],
2944 vec![q(0, true), q(1, true), q(2, true)],
2945 );
2946 assert_eq!(
2947 lane_wanted(&u, VideoCodec::H264, false, 3),
2948 vec![false, false, false],
2949 "the primary never takes the backup's entry"
2950 );
2951 assert_eq!(lane_wanted(&u, VideoCodec::Vp8, true, 2), vec![true, false]);
2952 let u = update(
2954 vec![
2955 entry("H264", vec![q(0, true)]),
2956 entry("VP8", vec![q(1, true)]),
2957 ],
2958 vec![],
2959 );
2960 assert_eq!(
2961 lane_wanted(&u, VideoCodec::H264, false, 3),
2962 vec![true, true, true]
2963 );
2964 assert_eq!(
2965 lane_wanted(&u, VideoCodec::Vp8, true, 3),
2966 vec![false, true, false]
2967 );
2968 let u = update(vec![], vec![q(0, true), q(1, false)]);
2970 assert_eq!(
2971 lane_wanted(&u, VideoCodec::H264, false, 3),
2972 vec![true, false, true]
2973 );
2974 assert_eq!(
2975 lane_wanted(&u, VideoCodec::Vp8, true, 3),
2976 vec![false, false, false]
2977 );
2978 assert!(names_codec("video/H264", VideoCodec::H264));
2979 assert!(!names_codec("video/VP8", VideoCodec::H264));
2980 }
2981
2982 #[test]
2983 fn caps_reach_both_lanes_and_heat_never_stops_a_lanes_lowest_layer() {
2984 let mut pb = Publisher::new(Arc::default());
2985 let mut b = three();
2986 b.truncate(2);
2987 let mut p = with_backup(b);
2988 p.state = State::Live;
2989 pb.pubs.push(p);
2990 let keys = |pb: &Publisher| -> Vec<(u64, usize, usize)> {
2991 pb.capped_layers().iter().map(|l| l.key).collect()
2992 };
2993 assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 0, 1), (7, 0, 2)]);
2995 pb.pubs[0].lanes[1].on = true;
2996 for l in &mut pb.pubs[0].lanes[1].layers {
2997 l.wanted = true;
2998 }
2999 assert_eq!(pb.capped_layers().len(), 5);
3000 pb.caps = VideoCaps::new(50, Some(1), Some(20));
3003 let l = pb.capped_layers();
3004 let got: Vec<((u64, usize, usize), u64)> = l.iter().map(|l| (l.key, l.max_bps)).collect();
3005 assert_eq!(got, vec![((7, 0, 0), 150_000), ((7, 1, 0), 150_000)]);
3006 pb.caps = VideoCaps::new(50, None, None);
3009 pb.pubs[0].lanes[0].layers[0].wanted = false;
3010 let l = pb.capped_layers();
3011 let got: Vec<((u64, usize, usize), u64)> = l.iter().map(|l| (l.key, l.max_bps)).collect();
3012 assert_eq!(
3013 &got[..3],
3014 &[
3015 ((7, 0, 0), 75_000),
3016 ((7, 0, 1), 400_000),
3017 ((7, 0, 2), 850_000)
3018 ]
3019 );
3020 pb.pubs[0].lanes[0].layers[0].wanted = true;
3021 pb.caps = VideoCaps::new(50, Some(1), Some(20));
3022 let (prim, backup) = (&pb.pubs[0].lanes[0], &pb.pubs[0].lanes[1]);
3023 assert_eq!(pb.fps_of(prim, &prim.layers[0].spec), 20);
3024 assert_eq!(pb.fps_of(backup, &backup.layers[0].spec), 20);
3025 pb.caps = VideoCaps::new(100, Some(0), None);
3027 assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 1, 0)]);
3028 pb.caps = VideoCaps::none();
3030 pb.backup_caps = BackupCaps {
3031 max_layers: Some(1),
3032 max_fps: Some(15),
3033 };
3034 assert_eq!(keys(&pb), vec![(7, 0, 0), (7, 0, 1), (7, 0, 2), (7, 1, 0)]);
3035 let (prim, backup) = (&pb.pubs[0].lanes[0], &pb.pubs[0].lanes[1]);
3036 assert_eq!(pb.fps_of(prim, &prim.layers[0].spec), 30);
3037 assert_eq!(pb.fps_of(backup, &backup.layers[0].spec), 15);
3038 pb.backup_caps = BackupCaps {
3039 max_layers: Some(0),
3040 max_fps: None,
3041 };
3042 assert_eq!(keys(&pb).last(), Some(&(7, 1, 0)), "never zero layers");
3043 pb.pubs[0].lanes[1].exempt = true;
3045 pb.pubs[0].lanes[1].layers[0].wanted = false;
3046 pb.backup_caps = BackupCaps::default();
3047 let ex: Vec<(u64, usize, usize)> = pb
3048 .capped_layers()
3049 .iter()
3050 .filter(|l| l.exempt)
3051 .map(|l| l.key)
3052 .collect();
3053 assert_eq!(ex, vec![(7, 1, 1)], "the lowest wanted, h here");
3054 pb.pubs[0].lanes[1].exempt = false;
3057 let kept = |pb: &Publisher| -> Vec<(u64, usize, usize)> {
3058 pb.capped_layers()
3059 .iter()
3060 .filter(|l| l.kept)
3061 .map(|l| l.key)
3062 .collect()
3063 };
3064 assert_eq!(kept(&pb), vec![(7, 0, 0), (7, 1, 1)]);
3065 pb.pubs[0].lanes[1].layers[0].wanted = true;
3066 assert_eq!(kept(&pb), vec![(7, 0, 0), (7, 1, 0)]);
3067 pb.pubs[0].lanes[1].on = false;
3068 assert_eq!(
3069 kept(&pb),
3070 vec![(7, 0, 0)],
3071 "the backup off: the primary's q"
3072 );
3073 pb.pubs[0].lanes[0].layers[0].wanted = false;
3075 assert_eq!(kept(&pb), vec![(7, 0, 1)]);
3076 for l in &mut pb.pubs[0].lanes[0].layers {
3077 l.wanted = false;
3078 }
3079 assert!(
3080 kept(&pb).is_empty(),
3081 "nobody wants the primary: nothing kept"
3082 );
3083 }
3084
3085 #[test]
3086 fn a_tier_change_keeps_the_backups_rungs() {
3087 let mut old = three();
3089 old.truncate(2);
3090 for l in &mut old {
3091 l.temporal_layers = 3;
3092 }
3093 let p = with_backup(old);
3094 let old: Vec<LayerSpec> = p.lanes[1].layers.iter().map(|l| l.spec.clone()).collect();
3095 let plan = vec![
3096 LayerSpec::new("q", 320, 180, 120, 24),
3097 LayerSpec::new("h", 640, 360, 400, 24),
3098 ];
3099 let got = backup_layers_for(&plan, &old);
3100 assert_eq!(got.len(), 2);
3101 assert!(got.iter().all(|l| l.temporal_layers == 3 && l.fps == 24));
3102 let got = backup_layers_for(&three(), &old);
3104 let rids: Vec<&str> = got.iter().map(|l| l.rid.as_str()).collect();
3105 assert_eq!(rids, vec!["q", "h"]);
3106 let only_f = vec![LayerSpec::new("f", 1280, 720, 1700, 30)];
3108 let got = backup_layers_for(&only_f, &old);
3109 assert_eq!(
3110 (got.len(), got[0].rid.as_str(), got[0].temporal_layers),
3111 (1, "f", 3)
3112 );
3113 }
3114}