1use std::collections::{BTreeMap, HashMap, HashSet};
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11
12use bytes::Bytes;
13use sew_lkproto::livekit::{
14 ParticipantInfo, SignalRequest, StreamState, StreamStateInfo, TrackInfo, TrackSource,
15 TrackType, UpdateTrackSettings, signal_request,
16};
17use tokio::sync::mpsc;
18
19use super::codec_pref::CodecSet;
20use super::keyframe::{KeyframeAsk, KeyframeLimiter};
21use super::reorder::{Pushed, Reorder};
22use super::rtp::h264::H264Depacketizer;
23use super::rtp::vp8::Vp8Depacketizer;
24use super::rtp::{Frame, RtpIn};
25use super::types::{
26 VideoCodec, VideoFrame, VideoLayerInfo, VideoPause, VideoRecvItem, VideoSinkSpec, VideoSource,
27 VideoTrack, VideoTrackView,
28};
29use crate::call::{CallCounters, CallEvent, Cmd};
30use crate::e2ee::{CryptoError, KeySession};
31
32pub(crate) const SETTINGS_DEBOUNCE: Duration = Duration::from_millis(250);
35
36#[derive(Debug)]
38pub struct VideoFrameStream(pub(crate) mpsc::Receiver<VideoRecvItem>);
39
40impl VideoFrameStream {
41 pub async fn recv(&mut self) -> Option<VideoRecvItem> {
43 self.0.recv().await
44 }
45
46 pub fn try_recv(&mut self) -> Option<VideoRecvItem> {
48 self.0.try_recv().ok()
49 }
50}
51
52#[derive(Debug)]
54pub(crate) enum SinkCmd {
55 Open {
56 id: u64,
57 track_sid: String,
58 spec: VideoSinkSpec,
59 },
60 Update {
61 id: u64,
62 spec: VideoSinkSpec,
63 },
64 Keyframe {
65 id: u64,
66 },
67 Close {
68 id: u64,
69 },
70}
71
72#[derive(Debug)]
78pub struct VideoSink {
79 pub(crate) id: u64,
80 pub(crate) cmd: mpsc::UnboundedSender<Cmd>,
81}
82
83impl VideoSink {
84 pub fn update(&self, spec: VideoSinkSpec) {
86 let _ = self
87 .cmd
88 .send(Cmd::Video(SinkCmd::Update { id: self.id, spec }));
89 }
90
91 pub fn request_keyframe(&self) {
93 let _ = self.cmd.send(Cmd::Video(SinkCmd::Keyframe { id: self.id }));
94 }
95
96 pub fn close(self) {}
98}
99
100impl Drop for VideoSink {
101 fn drop(&mut self) {
102 let _ = self.cmd.send(Cmd::Video(SinkCmd::Close { id: self.id }));
103 }
104}
105
106#[derive(Debug, Default)]
108pub(crate) struct Out {
109 pub(crate) requests: Vec<SignalRequest>,
110 pub(crate) keyframes: Vec<(u32, bool)>,
112 pub(crate) items: Vec<VideoRecvItem>,
113 pub(crate) events: Vec<CallEvent>,
114 pub(crate) stalled: Vec<String>,
116}
117
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub(crate) struct Settings {
121 pub(crate) disabled: bool,
122 pub(crate) width: u32,
123 pub(crate) height: u32,
124 pub(crate) fps: u32,
125 pub(crate) priority: u32,
126}
127
128impl Settings {
129 const DISABLED: Settings = Settings {
130 disabled: true,
131 width: 0,
132 height: 0,
133 fps: 0,
134 priority: 0,
135 };
136}
137
138pub(crate) fn settings_for<'a>(
142 sinks: impl Iterator<Item = &'a VideoSinkSpec>,
143 source: VideoSource,
144 speaking: bool,
145) -> Settings {
146 let mut s = Settings::DISABLED;
147 for k in sinks.filter(|k| k.visible) {
148 s.disabled = false;
149 s.width = s.width.max(k.width);
150 s.height = s.height.max(k.height);
151 s.fps = s.fps.max(if k.large { 30 } else { 15 });
152 }
153 if !s.disabled {
154 let base = match source {
155 VideoSource::ScreenShare => 2,
156 VideoSource::Camera => 0,
157 };
158 s.priority = base + u32::from(speaking);
159 }
160 s
161}
162
163#[derive(Debug)]
165struct Pkt {
166 seq: u64,
167 timestamp: u32,
168 marker: bool,
169 payload: Arc<[u8]>,
170 at: Instant,
171}
172
173#[derive(Debug)]
174enum Depack {
175 Vp8(Vp8Depacketizer),
176 H264(H264Depacketizer),
177}
178
179impl Depack {
180 fn new(codec: VideoCodec) -> Depack {
181 match codec {
182 VideoCodec::Vp8 => Depack::Vp8(Vp8Depacketizer::new()),
183 VideoCodec::H264 => Depack::H264(H264Depacketizer::new()),
184 }
185 }
186
187 fn codec(&self) -> VideoCodec {
188 match self {
189 Depack::Vp8(_) => VideoCodec::Vp8,
190 Depack::H264(_) => VideoCodec::H264,
191 }
192 }
193
194 fn push(&mut self, p: RtpIn<'_>) -> Option<Frame> {
195 match self {
196 Depack::Vp8(d) => d.push(p),
197 Depack::H264(d) => d.push(p),
198 }
199 }
200
201 fn dropped(&self) -> u64 {
202 match self {
203 Depack::Vp8(d) => d.dropped(),
204 Depack::H264(d) => d.dropped(),
205 }
206 }
207}
208
209#[derive(Debug)]
211struct Track {
212 info: VideoTrack,
213 participant_sid: String,
214 ssrc: Option<u32>,
215 reorder: Reorder<Pkt>,
216 depack: Option<Depack>,
217 flowing: bool,
219 need_key: bool,
221 kf: KeyframeLimiter,
222 sent: Option<Settings>,
223 settings_due: Option<Instant>,
224 codec_from_pt: bool,
226}
227
228impl Track {
229 fn new(info: VideoTrack, participant_sid: String) -> Track {
230 Track {
231 info,
232 participant_sid,
233 ssrc: None,
234 reorder: Reorder::new(),
235 depack: None,
236 flowing: false,
237 need_key: true,
238 kf: KeyframeLimiter::new(),
239 sent: None,
240 settings_due: None,
241 codec_from_pt: false,
242 }
243 }
244
245 fn want_key(&mut self, out: &mut Out) {
247 if !self.kf.waiting() && self.flowing {
248 out.items.push(VideoRecvItem::KeyframeNeeded {
249 track: self.info.id,
250 });
251 }
252 self.kf.request();
253 }
254
255 fn broken(&mut self, out: &mut Out) {
257 if !self.need_key && self.flowing {
258 out.items.push(VideoRecvItem::Broken {
259 track: self.info.id,
260 });
261 }
262 self.need_key = true;
263 self.want_key(out);
264 }
265}
266
267fn source_of(t: &TrackInfo) -> Option<VideoSource> {
268 if t.r#type != TrackType::Video as i32 {
269 return None;
270 }
271 Some(if t.source == TrackSource::ScreenShare as i32 {
272 VideoSource::ScreenShare
273 } else {
274 VideoSource::Camera
275 })
276}
277
278fn codecs_of(t: &TrackInfo) -> Vec<VideoCodec> {
281 let mut v = Vec::new();
282 let named =
283 std::iter::once(t.mime_type.as_str()).chain(t.codecs.iter().map(|c| c.mime_type.as_str()));
284 for c in named.filter_map(VideoCodec::from_mime) {
285 if !v.contains(&c) {
286 v.push(c);
287 }
288 }
289 v
290}
291
292fn codec_for(t: &TrackInfo, decode: CodecSet) -> (Option<VideoCodec>, bool) {
297 let named = codecs_of(t);
298 match named.iter().find(|c| decode.contains(**c)) {
299 Some(c) => (Some(*c), false),
300 None => (named.first().copied(), !named.is_empty()),
301 }
302}
303
304fn layers_of(t: &TrackInfo) -> Vec<VideoLayerInfo> {
306 let layers = match t.codecs.iter().find(|c| !c.layers.is_empty()) {
307 Some(c) => &c.layers,
308 #[allow(deprecated)]
309 None => &t.layers,
310 };
311 let mut v: Vec<VideoLayerInfo> = layers
312 .iter()
313 .map(|l| VideoLayerInfo {
314 width: l.width,
315 height: l.height,
316 bitrate: l.bitrate,
317 })
318 .collect();
319 v.sort_by_key(|l| (l.height, l.width));
320 v
321}
322
323fn request(m: signal_request::Message) -> SignalRequest {
324 SignalRequest { message: Some(m) }
325}
326
327fn settings_request(sid: &str, s: Settings) -> SignalRequest {
328 request(signal_request::Message::TrackSetting(UpdateTrackSettings {
329 track_sids: vec![sid.to_owned()],
330 disabled: s.disabled,
331 width: s.width,
332 height: s.height,
333 fps: s.fps,
334 priority: s.priority,
335 ..UpdateTrackSettings::default()
336 }))
337}
338
339#[derive(Debug)]
341pub(crate) struct Subscriptions {
342 epoch: Instant,
343 tracks: BTreeMap<String, Track>,
344 next_id: u64,
345 sinks: HashMap<u64, (String, VideoSinkSpec)>,
347 speaking: HashSet<String>,
349 decode: CodecSet,
351}
352
353impl Subscriptions {
354 pub(crate) fn new(epoch: Instant) -> Subscriptions {
355 Subscriptions {
356 epoch,
357 tracks: BTreeMap::new(),
358 next_id: 1,
359 sinks: HashMap::new(),
360 speaking: HashSet::new(),
361 decode: CodecSet::ALL,
362 }
363 }
364
365 pub(crate) fn decoding(mut self, decode: CodecSet) -> Subscriptions {
367 self.decode = decode;
368 self
369 }
370
371 pub(crate) fn views(&self, identity: &str) -> (Option<VideoTrackView>, Option<VideoTrackView>) {
373 let mut camera = None;
374 let mut screen = None;
375 for t in self.tracks.values().filter(|t| t.info.identity == identity) {
376 match t.info.source {
377 VideoSource::Camera => camera = camera.or(Some(t.info.view())),
378 VideoSource::ScreenShare => screen = screen.or(Some(t.info.view())),
379 }
380 }
381 (camera, screen)
382 }
383
384 pub(crate) fn roster(
387 &mut self,
388 now: Instant,
389 remotes: &BTreeMap<String, ParticipantInfo>,
390 members: &HashMap<String, String>,
391 out: &mut Out,
392 ) {
393 let mut live = HashSet::new();
394 let decode = self.decode;
395 for p in remotes.values() {
396 for t in &p.tracks {
397 let Some(source) = source_of(t) else {
398 continue;
399 };
400 live.insert(t.sid.clone());
401 let member_id = members.get(&p.identity).cloned();
402 match self.tracks.get_mut(&t.sid) {
403 None => {
404 let id = self.next_id;
405 self.next_id += 1;
406 let (codec, unsupported) = codec_for(t, decode);
407 let info = VideoTrack {
408 id,
409 identity: p.identity.clone(),
410 member_id,
411 source,
412 track_sid: t.sid.clone(),
413 codec,
414 width: t.width,
415 height: t.height,
416 muted: t.muted,
417 paused: None,
418 layers: layers_of(t),
419 unsupported,
420 };
421 out.events.push(CallEvent::VideoAdded(info.clone()));
422 out.requests
424 .push(settings_request(&t.sid, Settings::DISABLED));
425 let mut track = Track::new(info, p.sid.clone());
426 track.sent = Some(Settings::DISABLED);
427 self.tracks.insert(t.sid.clone(), track);
428 if self.sinks.values().any(|(s, _)| *s == t.sid) {
430 self.sinks_changed(now, &t.sid, out);
431 }
432 }
433 Some(track) => {
434 let mut info = track.info.clone();
435 info.member_id = member_id.or(info.member_id);
436 info.muted = t.muted;
437 info.width = t.width;
438 info.height = t.height;
439 info.layers = layers_of(t);
440 if !track.codec_from_pt {
441 let (codec, unsupported) = codec_for(t, decode);
444 info.codec = codec.or(info.codec);
445 info.unsupported = unsupported;
446 }
447 track.participant_sid = p.sid.clone();
448 if info != track.info {
449 track.info = info.clone();
450 out.events.push(CallEvent::VideoChanged(info));
451 }
452 }
453 }
454 }
455 }
456 let gone: Vec<String> = self
457 .tracks
458 .keys()
459 .filter(|k| !live.contains(*k))
460 .cloned()
461 .collect();
462 for sid in gone {
463 if let Some(t) = self.tracks.remove(&sid) {
464 if t.flowing {
465 out.items.push(VideoRecvItem::Removed { track: t.info.id });
466 }
467 out.events.push(CallEvent::VideoRemoved {
468 id: t.info.id,
469 track_sid: sid,
470 });
471 }
472 }
473 }
474
475 pub(crate) fn speakers(&mut self, now: Instant, speaking: HashSet<String>, out: &mut Out) {
477 if speaking == self.speaking {
478 return;
479 }
480 self.speaking = speaking;
481 let sids: Vec<String> = self
482 .tracks
483 .iter()
484 .filter(|(_, t)| t.enabled())
485 .map(|(s, _)| s.clone())
486 .collect();
487 for sid in sids {
488 self.schedule(now, &sid, false, out);
489 }
490 }
491
492 pub(crate) fn stream_states(&mut self, states: &[StreamStateInfo], out: &mut Out) {
494 for s in states {
495 let Some(t) = self.tracks.get_mut(&s.track_sid) else {
496 continue;
497 };
498 let paused = (s.state == StreamState::Paused as i32).then_some(VideoPause::Congestion);
499 if t.info.paused != paused {
500 t.info.paused = paused;
501 out.events.push(CallEvent::VideoChanged(t.info.clone()));
502 }
503 }
504 }
505
506 pub(crate) fn sink(&mut self, now: Instant, cmd: SinkCmd, out: &mut Out) {
508 match cmd {
509 SinkCmd::Open {
510 id,
511 track_sid,
512 spec,
513 } => {
514 self.sinks.insert(id, (track_sid.clone(), spec));
515 self.sinks_changed(now, &track_sid, out);
516 }
517 SinkCmd::Update { id, spec } => {
518 let Some((sid, s)) = self.sinks.get_mut(&id) else {
519 return;
520 };
521 *s = spec;
522 let sid = sid.clone();
523 self.sinks_changed(now, &sid, out);
524 }
525 SinkCmd::Keyframe { id } => {
526 let Some((sid, _)) = self.sinks.get(&id) else {
527 return;
528 };
529 if let Some(t) = self.tracks.get_mut(sid)
530 && t.flowing
531 {
532 t.want_key(out);
533 }
534 }
535 SinkCmd::Close { id } => {
536 if let Some((sid, _)) = self.sinks.remove(&id) {
537 self.sinks_changed(now, &sid, out);
538 }
539 }
540 }
541 }
542
543 fn sinks_of<'a>(&'a self, sid: &'a str) -> impl Iterator<Item = &'a VideoSinkSpec> + 'a {
544 self.sinks
545 .values()
546 .filter(move |(s, _)| s == sid)
547 .map(|(_, spec)| spec)
548 }
549
550 fn sinks_changed(&mut self, now: Instant, sid: &str, out: &mut Out) {
553 let want = self.sinks_of(sid).any(|k| k.visible);
554 let Some(t) = self.tracks.get_mut(sid) else {
555 return;
556 };
557 match (t.flowing, want) {
558 (false, true) => {
559 t.flowing = true;
560 t.need_key = true;
561 out.items.push(VideoRecvItem::Added {
562 track: t.info.id,
563 codec: t
564 .depack
565 .as_ref()
566 .map_or(t.info.codec.unwrap_or(VideoCodec::Vp8), Depack::codec),
567 });
568 t.want_key(out);
569 self.schedule(now, sid, true, out);
570 }
571 (true, false) => {
572 t.flowing = false;
573 t.kf.cancel();
574 t.reorder.reset();
575 t.depack = None;
576 out.items.push(VideoRecvItem::Removed { track: t.info.id });
577 self.schedule(now, sid, true, out);
578 }
579 _ => self.schedule(now, sid, false, out),
580 }
581 }
582
583 fn schedule(&mut self, now: Instant, sid: &str, at_once: bool, out: &mut Out) {
585 if at_once {
586 if let Some(t) = self.tracks.get_mut(sid) {
587 t.settings_due = None;
588 }
589 self.send_settings(sid, out);
590 } else if let Some(t) = self.tracks.get_mut(sid) {
591 t.settings_due.get_or_insert(now + SETTINGS_DEBOUNCE);
592 }
593 }
594
595 fn send_settings(&mut self, sid: &str, out: &mut Out) {
596 let Some(t) = self.tracks.get(sid) else {
597 return;
598 };
599 let speaking = self.speaking.contains(&t.participant_sid);
600 let s = settings_for(self.sinks_of(sid), t.info.source, speaking);
601 if let Some(t) = self.tracks.get_mut(sid)
602 && t.sent != Some(s)
603 {
604 t.sent = Some(s);
605 out.requests.push(settings_request(sid, s));
606 }
607 }
608
609 pub(crate) fn resend_settings(&mut self, out: &mut Out) {
611 let sids: Vec<String> = self.tracks.keys().cloned().collect();
612 for sid in sids {
613 if let Some(t) = self.tracks.get_mut(&sid) {
614 t.sent = None;
615 t.settings_due = None;
616 }
617 self.send_settings(&sid, out);
618 }
619 }
620
621 pub(crate) fn set_rtt(&mut self, rtt: Duration) {
623 for t in self.tracks.values_mut() {
624 t.reorder.set_rtt(rtt);
625 }
626 }
627
628 pub(crate) fn media_reset(&mut self, out: &mut Out) {
630 for t in self.tracks.values_mut() {
631 t.ssrc = None;
632 t.reorder.reset();
633 t.depack = None;
634 t.kf.cancel();
635 if t.flowing {
636 t.broken(out);
637 }
638 }
639 }
640
641 pub(crate) fn resumed(&mut self, out: &mut Out) {
644 for t in self.tracks.values_mut().filter(|t| t.flowing) {
645 t.want_key(out);
646 }
647 }
648
649 #[allow(clippy::too_many_arguments)]
651 pub(crate) fn on_rtp(
652 &mut self,
653 now: Instant,
654 track_sid: &str,
655 identity: &str,
656 r: &crate::pc::RtpRx,
657 codec: VideoCodec,
658 keys: &dyn KeySession,
659 counters: &mut CallCounters,
660 out: &mut Out,
661 ) {
662 let Some(t) = self.tracks.get_mut(track_sid) else {
663 counters.video_packets_unwanted += 1;
664 return;
665 };
666 t.codec_from_pt = true;
667 if t.info.codec != Some(codec) || t.info.unsupported {
668 t.info.codec = Some(codec);
670 t.info.unsupported = false;
671 out.events.push(CallEvent::VideoChanged(t.info.clone()));
672 }
673 if !t.flowing {
674 counters.video_packets_unwanted += 1;
676 return;
677 }
678 if t.ssrc != Some(r.ssrc) || t.depack.as_ref().map(Depack::codec) != Some(codec) {
679 if t.ssrc.is_some() {
681 t.reorder.reset();
682 }
683 t.ssrc = Some(r.ssrc);
684 t.depack = Some(Depack::new(codec));
685 }
686 let mut ready = Vec::new();
687 let skipped = t.reorder.skipped;
688 let pushed = t.reorder.push(
689 r.seq,
690 now,
691 Pkt {
692 seq: r.seq,
693 timestamp: r.timestamp,
694 marker: r.marker,
695 payload: r.payload.clone(),
696 at: now,
697 },
698 &mut ready,
699 );
700 if pushed == Pushed::Late {
701 counters.video_packets_late += 1;
702 }
703 Self::gap_skipped(t, skipped, counters, out);
704 let epoch = self.epoch;
705 for p in ready {
706 Self::depacketise(epoch, t, p, identity, keys, counters, out);
707 }
708 }
709
710 fn gap_skipped(t: &mut Track, skipped: u64, counters: &mut CallCounters, out: &mut Out) {
715 if t.reorder.skipped > skipped {
716 counters.video_packets_lost += t.reorder.skipped - skipped;
717 t.broken(out);
718 }
719 }
720
721 fn depacketise(
722 epoch: Instant,
723 t: &mut Track,
724 p: Pkt,
725 identity: &str,
726 keys: &dyn KeySession,
727 counters: &mut CallCounters,
728 out: &mut Out,
729 ) {
730 let Some(d) = t.depack.as_mut() else {
731 return;
732 };
733 let codec = d.codec();
734 let before = d.dropped();
735 let frame = d.push(RtpIn {
736 seq: p.seq as u16,
737 timestamp: p.timestamp,
738 marker: p.marker,
739 payload: &p.payload,
740 });
741 let lost = d.dropped() - before;
742 if lost > 0 {
743 counters.video_frames_dropped += lost;
746 t.broken(out);
747 }
748 let Some(f) = frame else {
749 return;
750 };
751 if t.need_key && !f.keyframe {
752 counters.video_frames_dropped += 1;
753 return;
754 }
755 let mut plain = Vec::with_capacity(f.data.len());
756 match keys.decrypt_video(identity, codec, &f.data, &mut plain) {
757 Ok(()) if !plain.is_empty() => {}
758 Ok(()) => {
759 counters.video_decrypt_failures += 1;
760 t.broken(out);
761 return;
762 }
763 Err(e) => {
764 match e {
765 CryptoError::KeyPending => counters.video_frames_before_key += 1,
766 CryptoError::NoKey => counters.refused_frames += 1,
767 _ => counters.video_decrypt_failures += 1,
768 }
769 t.broken(out);
770 return;
771 }
772 }
773 let size = if f.keyframe {
774 match codec {
775 VideoCodec::Vp8 => super::size::vp8(&plain),
776 VideoCodec::H264 => super::size::h264(&plain),
777 }
778 } else {
779 None
780 };
781 if f.keyframe {
782 t.need_key = false;
783 t.kf.on_keyframe();
784 }
785 counters.video_frames_received += 1;
786 out.items.push(VideoRecvItem::Frame(VideoFrame {
787 track: t.info.id,
788 codec,
789 data: Bytes::from(plain),
790 keyframe: f.keyframe,
791 rtp_ts: f.timestamp,
792 arrival_us: p.at.saturating_duration_since(epoch).as_micros() as u64,
793 width: size.map(|s| s.0),
794 height: size.map(|s| s.1),
795 }));
796 }
797
798 pub(crate) fn frame_not_delivered(&mut self, track: u64, out: &mut Out) {
800 if let Some(t) = self.tracks.values_mut().find(|t| t.info.id == track) {
801 t.broken(out);
802 }
803 }
804
805 pub(crate) fn tick(
807 &mut self,
808 now: Instant,
809 keys: Option<&dyn KeySession>,
810 counters: &mut CallCounters,
811 out: &mut Out,
812 ) {
813 let epoch = self.epoch;
814 let due: Vec<String> = self
815 .tracks
816 .iter()
817 .filter(|(_, t)| t.settings_due.is_some_and(|d| d <= now))
818 .map(|(s, _)| s.clone())
819 .collect();
820 for sid in due {
821 if let Some(t) = self.tracks.get_mut(&sid) {
822 t.settings_due = None;
823 }
824 self.send_settings(&sid, out);
825 }
826 for (sid, t) in self.tracks.iter_mut() {
827 if !t.flowing {
828 continue;
829 }
830 let mut ready = Vec::new();
831 let skipped = t.reorder.skipped;
832 t.reorder.poll(now, &mut ready);
833 Self::gap_skipped(t, skipped, counters, out);
834 if !ready.is_empty()
835 && let Some(keys) = keys
836 {
837 let identity = t.info.identity.clone();
839 for p in ready {
840 Self::depacketise(epoch, t, p, &identity, keys, counters, out);
841 }
842 }
843 let Some(ssrc) = t.ssrc else {
844 continue;
845 };
846 let d = t.kf.poll(now);
847 match d.ask {
848 Some(KeyframeAsk::Pli) => {
849 counters.video_plis += 1;
850 out.keyframes.push((ssrc, false));
851 }
852 Some(KeyframeAsk::Fir) => {
853 counters.video_firs += 1;
854 out.keyframes.push((ssrc, true));
855 }
856 None => {}
857 }
858 if d.stalled {
859 out.stalled.push(sid.clone());
860 }
861 }
862 }
863
864 pub(crate) fn deadline(&self) -> Option<Instant> {
866 let mut d: Option<Instant> = None;
867 for t in self.tracks.values() {
868 let mut take = |x: Option<Instant>| {
869 if let Some(x) = x {
870 d = Some(d.map_or(x, |y| y.min(x)));
871 }
872 };
873 take(t.settings_due);
874 if t.flowing {
875 take(t.reorder.deadline());
876 if t.ssrc.is_some() {
877 take(t.kf.deadline());
878 }
879 }
880 }
881 d
882 }
883}
884
885impl Track {
886 fn enabled(&self) -> bool {
888 self.sent.is_some_and(|s| !s.disabled)
889 }
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895
896 fn sink(w: u32, h: u32, large: bool, visible: bool) -> VideoSinkSpec {
897 VideoSinkSpec::new(w, h, large).visible(visible)
898 }
899
900 #[test]
901 fn no_visible_sink_disables_the_track() {
902 assert_eq!(
903 settings_for([].iter(), VideoSource::Camera, false),
904 Settings::DISABLED
905 );
906 let hidden = [sink(640, 360, true, false)];
907 assert!(settings_for(hidden.iter(), VideoSource::Camera, true).disabled);
908 }
909
910 #[test]
911 fn the_largest_visible_sink_sets_the_size_and_a_large_tile_30_fps() {
912 let sinks = [
913 sink(320, 180, false, true),
914 sink(1280, 720, true, false),
915 sink(640, 400, false, true),
916 ];
917 let s = settings_for(sinks.iter(), VideoSource::Camera, false);
918 assert_eq!(
919 s,
920 Settings {
921 disabled: false,
922 width: 640,
923 height: 400,
924 fps: 15,
925 priority: 0
926 }
927 );
928 let sinks = [sink(320, 180, false, true), sink(960, 540, true, true)];
929 let s = settings_for(sinks.iter(), VideoSource::Camera, false);
930 assert_eq!((s.width, s.height, s.fps), (960, 540, 30));
931 }
932
933 #[test]
934 fn screens_rank_above_cameras_and_the_speaker_above_others() {
935 let sinks = [sink(320, 180, false, true)];
936 let cam = settings_for(sinks.iter(), VideoSource::Camera, false).priority;
937 let cam_speaking = settings_for(sinks.iter(), VideoSource::Camera, true).priority;
938 let screen = settings_for(sinks.iter(), VideoSource::ScreenShare, false).priority;
939 assert!(cam_speaking > cam);
940 assert!(screen > cam_speaking);
941 }
942
943 fn camera(sid: &str, muted: bool) -> TrackInfo {
944 TrackInfo {
945 sid: sid.to_owned(),
946 r#type: TrackType::Video as i32,
947 source: TrackSource::Camera as i32,
948 mime_type: "video/VP8".to_owned(),
949 width: 1280,
950 height: 720,
951 muted,
952 ..TrackInfo::default()
953 }
954 }
955
956 fn roster(tracks: Vec<TrackInfo>) -> BTreeMap<String, ParticipantInfo> {
957 let mut m = BTreeMap::new();
958 m.insert(
959 "PA_a".to_owned(),
960 ParticipantInfo {
961 sid: "PA_a".to_owned(),
962 identity: "p_a".to_owned(),
963 tracks,
964 ..ParticipantInfo::default()
965 },
966 );
967 m
968 }
969
970 fn setting(r: &SignalRequest) -> Option<&UpdateTrackSettings> {
971 match &r.message {
972 Some(signal_request::Message::TrackSetting(s)) => Some(s),
973 _ => None,
974 }
975 }
976
977 #[test]
978 fn a_new_track_is_announced_and_disabled_until_a_sink_opens() {
979 let t0 = Instant::now();
980 let mut s = Subscriptions::new(t0);
981 let mut out = Out::default();
982 s.roster(
983 t0,
984 &roster(vec![camera("TR_c", false)]),
985 &HashMap::new(),
986 &mut out,
987 );
988 assert!(
989 matches!(&out.events[..], [CallEvent::VideoAdded(v)] if v.track_sid == "TR_c"
990 && v.codec == Some(VideoCodec::Vp8) && v.source == VideoSource::Camera)
991 );
992 let u = setting(&out.requests[0]).unwrap();
993 assert!(u.disabled);
994 assert_eq!(u.track_sids, vec!["TR_c".to_owned()]);
995 assert!(out.items.is_empty(), "nothing flows without a sink");
996 let mut out = Out::default();
998 s.sink(
999 t0,
1000 SinkCmd::Open {
1001 id: 1,
1002 track_sid: "TR_c".to_owned(),
1003 spec: VideoSinkSpec::new(640, 360, false),
1004 },
1005 &mut out,
1006 );
1007 assert!(matches!(
1008 out.items[0],
1009 VideoRecvItem::Added {
1010 codec: VideoCodec::Vp8,
1011 ..
1012 }
1013 ));
1014 assert!(matches!(out.items[1], VideoRecvItem::KeyframeNeeded { .. }));
1015 let u = setting(&out.requests[0]).unwrap();
1016 assert!(!u.disabled);
1017 assert_eq!((u.width, u.height, u.fps), (640, 360, 15));
1018 let mut out = Out::default();
1020 s.sink(
1021 t0,
1022 SinkCmd::Update {
1023 id: 1,
1024 spec: VideoSinkSpec::new(1280, 720, true),
1025 },
1026 &mut out,
1027 );
1028 assert!(out.requests.is_empty());
1029 assert_eq!(s.deadline(), Some(t0 + SETTINGS_DEBOUNCE));
1030 let mut c = CallCounters::default();
1031 let mut out = Out::default();
1032 s.tick(t0 + SETTINGS_DEBOUNCE, None, &mut c, &mut out);
1033 let u = setting(&out.requests[0]).unwrap();
1034 assert_eq!((u.width, u.height, u.fps), (1280, 720, 30));
1035 let mut out = Out::default();
1037 s.sink(t0, SinkCmd::Close { id: 1 }, &mut out);
1038 assert!(matches!(out.items[..], [VideoRecvItem::Removed { .. }]));
1039 assert!(setting(&out.requests[0]).unwrap().disabled);
1040 }
1041
1042 #[test]
1043 fn mute_size_and_congestion_are_changes_and_a_gone_track_is_removed() {
1044 let t0 = Instant::now();
1045 let mut s = Subscriptions::new(t0);
1046 let mut out = Out::default();
1047 s.roster(
1048 t0,
1049 &roster(vec![camera("TR_c", false)]),
1050 &HashMap::new(),
1051 &mut out,
1052 );
1053 let mut out = Out::default();
1054 s.roster(
1055 t0,
1056 &roster(vec![camera("TR_c", true)]),
1057 &HashMap::new(),
1058 &mut out,
1059 );
1060 assert!(matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.muted));
1061 let mut out = Out::default();
1062 s.stream_states(
1063 &[StreamStateInfo {
1064 participant_sid: "PA_a".to_owned(),
1065 track_sid: "TR_c".to_owned(),
1066 state: StreamState::Paused as i32,
1067 }],
1068 &mut out,
1069 );
1070 assert!(
1071 matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.paused == Some(VideoPause::Congestion))
1072 );
1073 assert_eq!(
1074 s.views("p_a").0.unwrap().paused,
1075 Some(VideoPause::Congestion)
1076 );
1077 let mut out = Out::default();
1078 s.roster(t0, &roster(vec![]), &HashMap::new(), &mut out);
1079 assert!(
1080 matches!(&out.events[..], [CallEvent::VideoRemoved { track_sid, .. }] if track_sid == "TR_c")
1081 );
1082 assert_eq!(s.views("p_a"), (None, None));
1083 }
1084
1085 struct EchoKeys;
1088
1089 impl KeySession for EchoKeys {
1090 fn encrypt(&self, _: &[u8], _: u32, _: u32, _: &mut Vec<u8>) -> Result<(), CryptoError> {
1091 Err(CryptoError::NoSendKey)
1092 }
1093 fn decrypt(&self, _: &str, _: &[u8], _: &mut Vec<u8>) -> Result<(), CryptoError> {
1094 Err(CryptoError::NoKey)
1095 }
1096 fn decrypt_video(
1097 &self,
1098 _: &str,
1099 _: VideoCodec,
1100 frame: &[u8],
1101 out: &mut Vec<u8>,
1102 ) -> Result<(), CryptoError> {
1103 out.extend_from_slice(frame);
1104 Ok(())
1105 }
1106 fn may_subscribe(&self, _: &str, _: &crate::e2ee::RemoteTrack) -> crate::e2ee::Subscribe {
1107 crate::e2ee::Subscribe::Yes
1108 }
1109 fn close(&self) -> crate::provider::BoxFuture<'_, ()> {
1110 Box::pin(async {})
1111 }
1112 }
1113
1114 fn vp8_packet(seq: u64, key: bool) -> crate::pc::RtpRx {
1116 let mut payload = vec![0x10, if key { 0x00 } else { 0x01 }];
1117 payload.extend_from_slice(&[0x9d, 0x01, 0x2a, 0x40, 0x01, 0xb4, 0x00, 0x55, 0x55]);
1118 crate::pc::RtpRx {
1119 mid: "1".to_owned(),
1120 ssrc: 7,
1121 seq,
1122 timestamp: seq as u32 * 3_000,
1123 marker: true,
1124 video: Some(VideoCodec::Vp8),
1125 payload: Arc::from(payload),
1126 }
1127 }
1128
1129 #[test]
1130 fn whole_frames_lost_on_a_frame_boundary_break_the_track() {
1131 let t0 = Instant::now();
1132 let mut s = Subscriptions::new(t0);
1133 let mut out = Out::default();
1134 s.roster(
1135 t0,
1136 &roster(vec![camera("TR_c", false)]),
1137 &HashMap::new(),
1138 &mut out,
1139 );
1140 s.sink(
1141 t0,
1142 SinkCmd::Open {
1143 id: 1,
1144 track_sid: "TR_c".to_owned(),
1145 spec: VideoSinkSpec::new(640, 360, false),
1146 },
1147 &mut out,
1148 );
1149 let mut c = CallCounters::default();
1150 let rx = |s: &mut Subscriptions, seq, key, at, out: &mut Out, c: &mut CallCounters| {
1151 let r = vp8_packet(seq, key);
1152 s.on_rtp(at, "TR_c", "p_a", &r, VideoCodec::Vp8, &EchoKeys, c, out);
1153 };
1154 let mut out = Out::default();
1155 rx(&mut s, 10, true, t0, &mut out, &mut c);
1156 rx(&mut s, 11, false, t0, &mut out, &mut c);
1157 let frames = |o: &Out| {
1158 o.items
1159 .iter()
1160 .filter(|i| matches!(i, VideoRecvItem::Frame(_)))
1161 .count()
1162 };
1163 assert_eq!(frames(&out), 2);
1164 let mut out = Out::default();
1167 rx(&mut s, 15, false, t0, &mut out, &mut c);
1168 assert_eq!(frames(&out), 0, "held for the gap");
1169 s.tick(
1170 t0 + Duration::from_millis(200),
1171 Some(&EchoKeys),
1172 &mut c,
1173 &mut out,
1174 );
1175 assert!(
1176 out.items
1177 .iter()
1178 .any(|i| matches!(i, VideoRecvItem::Broken { .. })),
1179 "{:?}",
1180 out.items
1181 );
1182 assert_eq!(frames(&out), 0, "a delta frame after the loss");
1183 assert_eq!(c.video_packets_lost, 3);
1184 let mut out = Out::default();
1185 rx(
1186 &mut s,
1187 16,
1188 true,
1189 t0 + Duration::from_millis(210),
1190 &mut out,
1191 &mut c,
1192 );
1193 assert_eq!(frames(&out), 1, "the keyframe restarts the track");
1194 }
1195
1196 fn break_then(key15: bool) -> (Out, CallCounters) {
1200 let t0 = Instant::now();
1201 let mut s = Subscriptions::new(t0);
1202 let mut out = Out::default();
1203 s.roster(
1204 t0,
1205 &roster(vec![camera("TR_c", false)]),
1206 &HashMap::new(),
1207 &mut out,
1208 );
1209 s.sink(
1210 t0,
1211 SinkCmd::Open {
1212 id: 1,
1213 track_sid: "TR_c".to_owned(),
1214 spec: VideoSinkSpec::new(640, 360, false),
1215 },
1216 &mut out,
1217 );
1218 let mut c = CallCounters::default();
1219 let mut out = Out::default();
1220 for (seq, key) in [(10, true), (11, false), (15, key15)] {
1221 let r = vp8_packet(seq, key);
1222 s.on_rtp(
1223 t0,
1224 "TR_c",
1225 "p_a",
1226 &r,
1227 VideoCodec::Vp8,
1228 &EchoKeys,
1229 &mut c,
1230 &mut out,
1231 );
1232 }
1233 let plis_before = c.video_plis;
1234 let mut out = Out::default();
1235 s.tick(
1236 t0 + Duration::from_millis(200),
1237 Some(&EchoKeys),
1238 &mut c,
1239 &mut out,
1240 );
1241 assert!(
1242 out.items
1243 .iter()
1244 .any(|i| matches!(i, VideoRecvItem::Broken { .. })),
1245 "the loss breaks the track: {:?}",
1246 out.items
1247 );
1248 c.video_plis -= plis_before;
1249 (out, c)
1250 }
1251
1252 #[test]
1254 fn a_break_without_a_keyframe_sends_a_pli() {
1255 let (out, c) = break_then(false);
1256 assert_eq!(c.video_plis, 1);
1257 assert_eq!(out.keyframes, vec![(7, false)]);
1258 assert!(
1259 !out.items
1260 .iter()
1261 .any(|i| matches!(i, VideoRecvItem::Frame(_))),
1262 "a delta frame after the loss is not handed out"
1263 );
1264 }
1265
1266 #[test]
1269 fn a_keyframe_right_after_the_break_sends_no_pli() {
1270 let (out, c) = break_then(true);
1271 assert_eq!(c.video_plis, 0);
1272 assert!(out.keyframes.is_empty(), "{:?}", out.keyframes);
1273 assert!(
1274 out.items
1275 .iter()
1276 .any(|i| matches!(i, VideoRecvItem::Frame(f) if f.keyframe)),
1277 "the keyframe restarts the track: {:?}",
1278 out.items
1279 );
1280 }
1281
1282 fn camera_in(sid: &str, primary: &str, codecs: &[&str]) -> TrackInfo {
1284 let mut t = camera(sid, false);
1285 t.mime_type = primary.to_owned();
1286 t.codecs = codecs
1287 .iter()
1288 .map(|m| sew_lkproto::livekit::SimulcastCodecInfo {
1289 mime_type: (*m).to_owned(),
1290 ..Default::default()
1291 })
1292 .collect();
1293 t
1294 }
1295
1296 #[test]
1297 fn the_codec_before_the_first_packet_is_the_first_one_this_device_receives() {
1298 let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
1299 let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
1300 let named_none = camera_in("TR_c", "", &[]);
1301 assert_eq!(
1302 codecs_of(&both),
1303 vec![VideoCodec::H264, VideoCodec::Vp8],
1304 "the primary first, each once"
1305 );
1306 assert_eq!(
1307 codec_for(&both, CodecSet::ALL),
1308 (Some(VideoCodec::H264), false)
1309 );
1310 assert_eq!(
1311 codec_for(&both, CodecSet::VP8_ONLY),
1312 (Some(VideoCodec::Vp8), false),
1313 "the VP8 backup"
1314 );
1315 assert_eq!(
1316 codec_for(&h264_only, CodecSet::VP8_ONLY),
1317 (Some(VideoCodec::H264), true),
1318 "nothing this device receives"
1319 );
1320 assert_eq!(
1321 codec_for(&h264_only, CodecSet::ALL),
1322 (Some(VideoCodec::H264), false)
1323 );
1324 assert_eq!(codec_for(&named_none, CodecSet::VP8_ONLY), (None, false));
1325 }
1326
1327 #[test]
1328 fn a_track_this_device_cannot_receive_is_unsupported_until_a_packet_arrives() {
1329 let t0 = Instant::now();
1330 let mut s = Subscriptions::new(t0).decoding(CodecSet::VP8_ONLY);
1331 let mut out = Out::default();
1332 let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
1333 s.roster(t0, &roster(vec![h264_only]), &HashMap::new(), &mut out);
1334 assert!(
1335 matches!(&out.events[..], [CallEvent::VideoAdded(v)]
1336 if v.codec == Some(VideoCodec::H264) && v.unsupported),
1337 "{:?}",
1338 out.events
1339 );
1340 assert!(s.views("p_a").0.is_some_and(|v| v.unsupported));
1341 let mut out = Out::default();
1343 let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
1344 s.roster(t0, &roster(vec![both]), &HashMap::new(), &mut out);
1345 assert!(
1346 matches!(&out.events[..], [CallEvent::VideoChanged(v)]
1347 if v.codec == Some(VideoCodec::Vp8) && !v.unsupported),
1348 "{:?}",
1349 out.events
1350 );
1351 let mut out = Out::default();
1353 let h264_only = camera_in("TR_c", "video/H264", &["video/H264"]);
1354 s.roster(
1355 t0,
1356 &roster(vec![h264_only.clone()]),
1357 &HashMap::new(),
1358 &mut out,
1359 );
1360 assert!(
1361 matches!(&out.events[..], [CallEvent::VideoChanged(v)] if v.unsupported),
1362 "{:?}",
1363 out.events
1364 );
1365 let mut out = Out::default();
1368 let mut c = CallCounters::default();
1369 let r = vp8_packet(1, true);
1370 s.on_rtp(
1371 t0,
1372 "TR_c",
1373 "p_a",
1374 &r,
1375 VideoCodec::Vp8,
1376 &EchoKeys,
1377 &mut c,
1378 &mut out,
1379 );
1380 assert!(
1381 matches!(&out.events[..], [CallEvent::VideoChanged(v)]
1382 if v.codec == Some(VideoCodec::Vp8) && !v.unsupported),
1383 "{:?}",
1384 out.events
1385 );
1386 let mut out = Out::default();
1387 s.roster(t0, &roster(vec![h264_only]), &HashMap::new(), &mut out);
1388 assert!(out.events.is_empty(), "{:?}", out.events);
1389 }
1390
1391 #[test]
1392 fn with_h264_received_an_h264_primary_is_shown_as_h264() {
1393 let t0 = Instant::now();
1394 let mut s = Subscriptions::new(t0).decoding(CodecSet::ALL);
1395 let mut out = Out::default();
1396 let both = camera_in("TR_c", "video/H264", &["video/H264", "video/VP8"]);
1397 s.roster(t0, &roster(vec![both]), &HashMap::new(), &mut out);
1398 assert!(
1399 matches!(&out.events[..], [CallEvent::VideoAdded(v)]
1400 if v.codec == Some(VideoCodec::H264) && !v.unsupported),
1401 "{:?}",
1402 out.events
1403 );
1404 }
1405}