BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / video_layout.rs

video_layout.rs

video_layout.rs 28.0 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use libwebrtc::MediaType;
5use libwebrtc::peer_connection::PeerConnection;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
8use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
9use serde_json::{Value, json};
10
11use crate::error::{Error, Result};
12use crate::sdp::{LineRole, OfferPlan, StreamLine};
13use crate::send_control::capture_macroblocks;
14use crate::video_frame::VideoKey;
15use crate::video_quality::VideoQuality;
16
17pub const RECEIVE_SLOTS: usize = 9;
18pub const CAMERA_MID: &str = "1";
19pub const SHARE_MID: &str = "11";
20pub const ONE_TO_ONE_SHARE_MID: &str = "2";
21
22const CAMERA_LINE_LABEL: &str = "main-video";
23const SHARE_LINE_LABEL: &str = "applicationsharing-video";
24const CAMERA_STREAM: &str = "camera";
25pub const SCREEN_STREAM: &str = "screen";
26const H264: &str = "video/h264";
27const RTX: &str = "video/rtx";
28const NO_SOURCE: i64 = -1;
29const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits {
30 max_fs: 3600,
31 max_fps: 3000,
32 max_mbps: 108_000,
33};
34/// 1080p @ 30: max-fs 8160 macroblocks, mbps ≈ 8160 * 30.
35const STAGE_1080_REQUEST: ReceiveLimits = ReceiveLimits {
36 max_fs: 8160,
37 max_fps: 3000,
38 max_mbps: 244_800,
39};
40const SMALL_REQUEST: ReceiveLimits = ReceiveLimits {
41 max_fs: 920,
42 max_fps: 3000,
43 max_mbps: 27_600,
44};
45const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits {
46 max_fs: 8160,
47 max_fps: 1500,
48 max_mbps: 135_000,
49};
50const SUBSCRIBE_PROFILE: &str = "64001f";
51const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
52const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
53const SIMULCAST_SCALABILITY: &str = "L1T1";
54const THREE_LAYER_MIN_FS: u32 = 2040;
55const SEND_CAPABILITY_FPS: u32 = 30;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum TileDetail {
59 #[default]
60 Stage,
61 Small,
62}
63
64impl TileDetail {
65 fn limits(self, quality: VideoQuality) -> ReceiveLimits {
66 match self {
67 TileDetail::Stage => match quality {
68 VideoQuality::P720 => STAGE_720_REQUEST,
69 VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST,
70 },
71 TileDetail::Small => SMALL_REQUEST,
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct VideoWant {
78 pub mri: String,
79 pub detail: TileDetail,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83struct ReceiveLimits {
84 max_fs: u32,
85 max_fps: u32,
86 max_mbps: u32,
87}
88
89pub fn offer_plan() -> OfferPlan {
90 OfferPlan {
91 screen_share_mids: vec![SHARE_MID.to_owned()],
92 gallery_mids: Vec::new(),
93 fold_groups: Vec::new(),
94 }
95}
96
97pub fn one_to_one_plan() -> OfferPlan {
98 OfferPlan {
99 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
100 gallery_mids: Vec::new(),
101 fold_groups: Vec::new(),
102 }
103}
104
105/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11).
106#[derive(Clone)]
107pub struct VideoLines {
108 pub camera: RtpTransceiver,
109 pub share: Option<RtpTransceiver>,
110}
111
112fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {
113 capabilities
114 .into_iter()
115 .filter(|codec| {
116 let mime = codec.mime_type.to_ascii_lowercase();
117 mime == H264 || mime == RTX
118 })
119 .collect()
120}
121
122fn add_line(
123 peer: &PeerConnection,
124 direction: RtpTransceiverDirection,
125 stream: Option<&str>,
126 codecs: Vec<RtpCodecCapability>,
127 send_encodings: Vec<RtpEncodingParameters>,
128) -> Result<RtpTransceiver> {
129 let init = RtpTransceiverInit {
130 direction,
131 stream_ids: stream.map(str::to_owned).into_iter().collect(),
132 send_encodings,
133 };
134 let transceiver = peer
135 .add_transceiver_for_media(MediaType::Video, init)
136 .map_err(|error| Error::Webrtc(error.to_string()))?;
137 transceiver
138 .set_codec_preferences(codecs)
139 .map_err(|error| Error::Webrtc(error.to_string()))?;
140 Ok(transceiver)
141}
142
143fn simulcast_encodings() -> Vec<RtpEncodingParameters> {
144 SIMULCAST_RIDS
145 .iter()
146 .zip(SIMULCAST_START_SCALES)
147 .map(|(rid, scale)| RtpEncodingParameters {
148 rid: (*rid).to_owned(),
149 scale_resolution_down_by: Some(scale),
150 scalability_mode: Some(SIMULCAST_SCALABILITY.to_owned()),
151 ..RtpEncodingParameters::default()
152 })
153 .collect()
154}
155
156pub fn add_video_lines(
157 peer: &PeerConnection,
158 factory: &PeerConnectionFactory,
159) -> Result<VideoLines> {
160 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
161 let receiving = h264_only(
162 factory
163 .get_rtp_receiver_capabilities(MediaType::Video)
164 .codecs,
165 );
166 let camera = add_line(
167 peer,
168 RtpTransceiverDirection::SendRecv,
169 Some(CAMERA_STREAM),
170 sending.clone(),
171 simulcast_encodings(),
172 )?;
173 for _ in 0..RECEIVE_SLOTS {
174 add_line(
175 peer,
176 RtpTransceiverDirection::RecvOnly,
177 None,
178 receiving.clone(),
179 Vec::new(),
180 )?;
181 }
182 let share = add_line(
183 peer,
184 RtpTransceiverDirection::SendRecv,
185 Some(SCREEN_STREAM),
186 sending,
187 Vec::new(),
188 )?;
189 Ok(VideoLines {
190 camera,
191 share: Some(share),
192 })
193}
194
195/// A sharing line added to a running direct call, the way Teams adds it before its share offer.
196pub fn add_share_line(
197 peer: &PeerConnection,
198 factory: &PeerConnectionFactory,
199) -> Result<RtpTransceiver> {
200 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
201 add_line(
202 peer,
203 RtpTransceiverDirection::SendRecv,
204 Some(SCREEN_STREAM),
205 sending,
206 Vec::new(),
207 )
208}
209
210pub fn add_one_to_one_lines(
211 peer: &PeerConnection,
212 factory: &PeerConnectionFactory,
213) -> Result<VideoLines> {
214 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
215 let camera = add_line(
216 peer,
217 RtpTransceiverDirection::SendRecv,
218 Some(CAMERA_STREAM),
219 sending.clone(),
220 Vec::new(),
221 )?;
222 let share = add_line(
223 peer,
224 RtpTransceiverDirection::SendRecv,
225 Some(SCREEN_STREAM),
226 sending,
227 Vec::new(),
228 )?;
229 Ok(VideoLines {
230 camera,
231 share: Some(share),
232 })
233}
234
235/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct MediaDescription {
238 pub mid: &'static str,
239 pub direction: &'static str,
240 pub label: Option<&'static str>,
241}
242
243impl MediaDescription {
244 pub fn camera(sending: bool) -> Self {
245 Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL)
246 }
247
248 pub fn share(sending: bool) -> Self {
249 Self::line(SHARE_MID, sending, SHARE_LINE_LABEL)
250 }
251
252 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
253 if sending {
254 MediaDescription {
255 mid,
256 direction: "sendrecv",
257 label: Some(label),
258 }
259 } else {
260 MediaDescription {
261 mid,
262 direction: "recvonly",
263 label: None,
264 }
265 }
266 }
267
268 pub fn wire(&self) -> Value {
269 let mut description = json!({"mid": self.mid, "direction": self.direction});
270 if let Some(label) = self.label {
271 description["label"] = json!(label);
272 }
273 description
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct ReceiveSlot {
279 pub mid: String,
280 pub stream_id: u32,
281}
282
283#[derive(Debug, Clone, Default, PartialEq, Eq)]
284pub struct SlotTable {
285 pub people: Vec<ReceiveSlot>,
286 pub screen: Option<ReceiveSlot>,
287}
288
289impl SlotTable {
290 pub fn from_streams(streams: &[StreamLine]) -> Self {
291 let slot = |stream: &StreamLine| {
292 Some(ReceiveSlot {
293 mid: stream.browser_mid.clone(),
294 stream_id: stream.source_stream_id?,
295 })
296 };
297 let people = streams
298 .iter()
299 .filter(|stream| stream.role == LineRole::MainVideo)
300 .skip(1)
301 .filter_map(slot)
302 .take(RECEIVE_SLOTS)
303 .collect();
304 let screen = streams
305 .iter()
306 .find(|stream| stream.role == LineRole::ScreenShare)
307 .and_then(slot);
308 SlotTable { people, screen }
309 }
310
311 pub fn is_empty(&self) -> bool {
312 self.people.is_empty() && self.screen.is_none()
313 }
314}
315
316#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct Assignment {
318 pub mri: String,
319 pub source: u32,
320 pub detail: TileDetail,
321}
322
323impl Assignment {
324 fn same_source(&self, other: &Assignment) -> bool {
325 self.mri == other.mri && self.source == other.source
326 }
327}
328
329pub fn plan_receive(
330 current: &[Option<Assignment>],
331 candidates: &[Assignment],
332) -> Vec<Option<Assignment>> {
333 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
334 let mut next: Vec<Option<Assignment>> = current
335 .iter()
336 .map(|slot| {
337 let held = slot.as_ref()?;
338 wanted
339 .iter()
340 .find(|assignment| assignment.same_source(held))
341 .map(|assignment| (*assignment).clone())
342 })
343 .collect();
344 for assignment in wanted {
345 if next
346 .iter()
347 .flatten()
348 .any(|held| held.same_source(assignment))
349 {
350 continue;
351 }
352 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
353 *free = Some(assignment.clone());
354 }
355 }
356 next
357}
358
359pub fn prioritize(
360 candidates: Vec<(String, u32)>,
361 speaker_history: &[String],
362 wants: Option<&[VideoWant]>,
363) -> Vec<Assignment> {
364 if let Some(wants) = wants {
365 return wants
366 .iter()
367 .filter_map(|want| {
368 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
369 Some(Assignment {
370 mri: mri.clone(),
371 source: *source,
372 detail: want.detail,
373 })
374 })
375 .collect();
376 }
377 let rank = |mri: &str| {
378 speaker_history
379 .iter()
380 .position(|speaker| speaker == mri)
381 .unwrap_or(usize::MAX)
382 };
383 let mut ordered: Vec<Assignment> = candidates
384 .into_iter()
385 .map(|(mri, source)| Assignment {
386 mri,
387 source,
388 detail: TileDetail::Stage,
389 })
390 .collect();
391 ordered.sort_by_key(|assignment| rank(&assignment.mri));
392 ordered
393}
394
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct SourceRequest {
397 pub mid: String,
398 pub stream_id: u32,
399 pub source: Option<u32>,
400 pub screen: bool,
401 pub detail: TileDetail,
402 pub quality: VideoQuality,
403}
404
405pub fn requests_for(
406 current: &[Option<Assignment>],
407 next: &[Option<Assignment>],
408 slots: &[ReceiveSlot],
409 quality: VideoQuality,
410) -> Vec<SourceRequest> {
411 slots
412 .iter()
413 .zip(current.iter().zip(next))
414 .filter(|(_, (before, after))| before != after)
415 .map(|(slot, (_, after))| SourceRequest {
416 mid: slot.mid.clone(),
417 stream_id: slot.stream_id,
418 source: after.as_ref().map(|assignment| assignment.source),
419 screen: false,
420 detail: after
421 .as_ref()
422 .map(|assignment| assignment.detail)
423 .unwrap_or_default(),
424 quality,
425 })
426 .collect()
427}
428
429impl SourceRequest {
430 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
431 pub fn body(&self, sequence_number: u64) -> Value {
432 let limits = if self.screen {
433 SCREEN_REQUEST
434 } else {
435 self.detail.limits(self.quality)
436 };
437 let control = json!({
438 "controlVideoStreaming": {
439 "sequenceNumber": sequence_number,
440 "controlInfo": {
441 "sourceId": self.source.map_or(NO_SOURCE, i64::from),
442 "streamMsid": self.stream_id,
443 "fmtParams": [{
444 "max-fs": limits.max_fs,
445 "max-mbps": limits.max_mbps,
446 "max-fps": limits.max_fps,
447 "profile-level-id": SUBSCRIBE_PROFILE,
448 }],
449 },
450 },
451 });
452 json!({
453 "applyChannelParameters": {
454 "multiChannelParameter": {
455 "mids": [self.mid],
456 "mediaParameter": control.to_string(),
457 },
458 },
459 })
460 }
461}
462
463pub fn send_capabilities_body(
464 width: u32,
465 height: u32,
466 sequence_number: u64,
467 quality: VideoQuality,
468) -> Value {
469 let ceiling = quality.capture_height().max(quality.capture_width());
470 let width = width.min(ceiling);
471 let height = height.min(ceiling);
472 let largest_side = width.max(height);
473 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS {
474 2
475 } else {
476 SIMULCAST_RIDS.len()
477 };
478 let capabilities = json!({
479 "maxVideoSendCapabilities": {
480 "max-width": largest_side,
481 "max-height": largest_side,
482 "max-fps": SEND_CAPABILITY_FPS,
483 "max-streams": SIMULCAST_RIDS.len(),
484 "max-layers": layers,
485 "sequence-number": sequence_number,
486 },
487 });
488 json!({
489 "applyChannelParameters": {
490 "multiChannelParameter": {
491 "mids": [CAMERA_MID],
492 "mediaParameter": capabilities.to_string(),
493 },
494 },
495 })
496}
497
498/// Builds a send-capability body only when the camera size differs from the last one reported.
499#[derive(Debug, Default)]
500pub struct SendCapabilityReporter {
501 last_size: Option<(u32, u32)>,
502 last_quality: Option<VideoQuality>,
503 sequence_number: u64,
504}
505
506impl SendCapabilityReporter {
507 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
508 if self.last_size == Some(size) && self.last_quality == Some(quality) {
509 return None;
510 }
511 self.last_size.replace(size);
512 self.last_quality.replace(quality);
513 self.sequence_number += 1;
514 Some(send_capabilities_body(
515 size.0,
516 size.1,
517 self.sequence_number,
518 quality,
519 ))
520 }
521}
522
523#[derive(Clone, Default)]
524pub struct VideoRouter {
525 keys: Arc<Mutex<HashMap<String, VideoKey>>>,
526}
527
528impl VideoRouter {
529 pub fn set(&self, mid: &str, key: Option<VideoKey>) {
530 let mut keys = self.keys.lock().expect("router lock");
531 match key {
532 Some(key) => keys.insert(mid.to_owned(), key),
533 None => keys.remove(mid),
534 };
535 }
536
537 pub fn key_for(&self, mid: &str) -> Option<VideoKey> {
538 self.keys.lock().expect("router lock").get(mid).cloned()
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545
546 fn assignment(name: &str, source: u32) -> Assignment {
547 Assignment {
548 mri: format!("8:orgid:{name}"),
549 source,
550 detail: TileDetail::Stage,
551 }
552 }
553
554 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
555 StreamLine {
556 mid: mid.into(),
557 browser_mid: mid.into(),
558 role,
559 source_stream_id: id,
560 }
561 }
562
563 #[test]
564 fn slots_are_the_main_video_lines_after_the_camera_line() {
565 let streams = vec![
566 stream("0", LineRole::MainAudio, Some(201)),
567 stream("1", LineRole::MainVideo, Some(202)),
568 stream("2", LineRole::MainVideo, Some(203)),
569 stream("3", LineRole::MainVideo, Some(204)),
570 stream("4", LineRole::MainVideo, None),
571 stream("5", LineRole::MainVideo, Some(206)),
572 stream("11", LineRole::ScreenShare, Some(207)),
573 ];
574 let table = SlotTable::from_streams(&streams);
575 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
576 assert_eq!(mids, vec!["2", "3", "5"]);
577 assert_eq!(
578 table.screen,
579 Some(ReceiveSlot {
580 mid: "11".into(),
581 stream_id: 207
582 })
583 );
584 }
585
586 #[test]
587 fn nobody_is_dropped_while_they_are_still_wanted() {
588 let held = vec![
589 Some(assignment("a", 1)),
590 Some(assignment("b", 2)),
591 None,
592 None,
593 ];
594 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
595 let next = plan_receive(&held, &candidates);
596 assert_eq!(next[0], Some(assignment("a", 1)));
597 assert_eq!(next[1], Some(assignment("b", 2)));
598 assert_eq!(next[2], Some(assignment("c", 3)));
599 assert_eq!(next[3], None);
600 }
601
602 #[test]
603 fn a_new_speaker_replaces_the_least_recent_person() {
604 let held: Vec<Option<Assignment>> = (1..=4)
605 .map(|index| Some(assignment(&format!("p{index}"), index)))
606 .collect();
607 let history = vec![
608 "8:orgid:p5".to_owned(),
609 "8:orgid:p1".to_owned(),
610 "8:orgid:p2".to_owned(),
611 "8:orgid:p3".to_owned(),
612 ];
613 let roster = (1..=5)
614 .map(|index| (format!("8:orgid:p{index}"), index))
615 .collect();
616 let next = plan_receive(&held, &prioritize(roster, &history, None));
617 let names: Vec<&str> = next
618 .iter()
619 .flatten()
620 .map(|held| held.mri.as_str())
621 .collect();
622 assert_eq!(
623 names,
624 vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]
625 );
626 }
627
628 #[test]
629 fn people_who_left_free_their_slot() {
630 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))];
631 let next = plan_receive(&held, &[assignment("b", 2)]);
632 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
633 let slots = vec![
634 ReceiveSlot {
635 mid: "2".into(),
636 stream_id: 203,
637 },
638 ReceiveSlot {
639 mid: "3".into(),
640 stream_id: 204,
641 },
642 ];
643 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
644 assert_eq!(
645 requests,
646 vec![SourceRequest {
647 mid: "2".into(),
648 stream_id: 203,
649 source: None,
650 screen: false,
651 detail: TileDetail::Stage,
652 quality: VideoQuality::Auto,
653 }]
654 );
655 }
656
657 #[test]
658 fn a_source_request_wraps_the_control_message_like_the_web_client() {
659 let request = SourceRequest {
660 mid: "3".into(),
661 stream_id: 204,
662 source: Some(302),
663 screen: false,
664 detail: TileDetail::Stage,
665 quality: VideoQuality::Auto,
666 };
667 let body = request.body(7);
668 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
669 assert_eq!(channel["mids"], json!(["3"]));
670 let parameter: Value =
671 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
672 let info = &parameter["controlVideoStreaming"]["controlInfo"];
673 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
674 assert_eq!(info["sourceId"], 302);
675 assert_eq!(info["streamMsid"], 204);
676 assert_eq!(info["fmtParams"][0]["max-fs"], 8160);
677 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
678 assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800);
679 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
680 let cleared = SourceRequest {
681 source: None,
682 ..request.clone()
683 }
684 .body(8);
685 let parameter: Value = serde_json::from_str(
686 cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
687 .as_str()
688 .unwrap(),
689 )
690 .unwrap();
691 assert_eq!(
692 parameter["controlVideoStreaming"]["controlInfo"]["sourceId"],
693 -1
694 );
695 let screen = SourceRequest {
696 screen: true,
697 ..request
698 }
699 .body(9);
700 let parameter: Value = serde_json::from_str(
701 screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
702 .as_str()
703 .unwrap(),
704 )
705 .unwrap();
706 assert_eq!(
707 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
708 8160
709 );
710 }
711
712 fn want(name: &str, detail: TileDetail) -> VideoWant {
713 VideoWant {
714 mri: format!("8:orgid:{name}"),
715 detail,
716 }
717 }
718
719 fn roster_of(count: u32) -> Vec<(String, u32)> {
720 (1..=count)
721 .map(|index| (format!("8:orgid:p{index}"), index))
722 .collect()
723 }
724
725 #[test]
726 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
727 let wants: Vec<VideoWant> = (1..=10)
728 .map(|index| want(&format!("p{index}"), TileDetail::Small))
729 .collect();
730 let candidates = prioritize(roster_of(10), &[], Some(&wants));
731 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
732 assert_eq!(next.iter().flatten().count(), 9);
733 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
734 }
735
736 #[test]
737 fn people_outside_the_visible_tiles_get_no_slot() {
738 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
739 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
740 let mris: Vec<&str> = candidates
741 .iter()
742 .map(|assignment| assignment.mri.as_str())
743 .collect();
744 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
745 let held = vec![Some(assignment("p5", 5)), None, None];
746 let next = plan_receive(&held, &candidates);
747 assert_eq!(
748 next.iter()
749 .flatten()
750 .map(|held| held.mri.as_str())
751 .collect::<Vec<_>>(),
752 vec!["8:orgid:p2", "8:orgid:p4"]
753 );
754 }
755
756 #[test]
757 fn nobody_visible_means_no_subscription() {
758 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
759 }
760
761 #[test]
762 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
763 let small = Assignment {
764 detail: TileDetail::Small,
765 ..assignment("a", 1)
766 };
767 let held = vec![None, Some(small), None];
768 let wants = vec![want("a", TileDetail::Stage)];
769 let next = plan_receive(
770 &held,
771 &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)),
772 );
773 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
774 let slots: Vec<ReceiveSlot> = (0..3)
775 .map(|index| ReceiveSlot {
776 mid: format!("{}", index + 2),
777 stream_id: 203 + index,
778 })
779 .collect();
780 let requests = requests_for(&held, &next, &slots, VideoQuality::Auto);
781 assert_eq!(requests.len(), 1);
782 assert_eq!(requests[0].mid, "3");
783 assert_eq!(requests[0].detail, TileDetail::Stage);
784 }
785
786 #[test]
787 fn stage_and_small_tiles_ask_for_different_resolutions() {
788 let fmt_for = |detail| {
789 let request = SourceRequest {
790 mid: "2".into(),
791 stream_id: 203,
792 source: Some(1),
793 screen: false,
794 detail,
795 quality: VideoQuality::Auto,
796 };
797 let body = request.body(1);
798 let parameter: Value = serde_json::from_str(
799 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
800 .as_str()
801 .unwrap(),
802 )
803 .unwrap();
804 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
805 };
806 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160);
807 assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800);
808 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
809 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
810 let locked = SourceRequest {
811 mid: "2".into(),
812 stream_id: 203,
813 source: Some(1),
814 screen: false,
815 detail: TileDetail::Stage,
816 quality: VideoQuality::P720,
817 }
818 .body(1);
819 let parameter: Value = serde_json::from_str(
820 locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
821 .as_str()
822 .unwrap(),
823 )
824 .unwrap();
825 assert_eq!(
826 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"],
827 3600
828 );
829 }
830
831 #[test]
832 fn media_descriptions_tell_the_mixer_what_a_line_does() {
833 assert_eq!(
834 MediaDescription::camera(true).wire(),
835 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
836 );
837 assert_eq!(
838 MediaDescription::camera(false).wire(),
839 json!({"mid": "1", "direction": "recvonly"})
840 );
841 assert_eq!(
842 MediaDescription::share(true).wire(),
843 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
844 );
845 }
846
847 #[test]
848 fn the_router_follows_assignments() {
849 let router = VideoRouter::default();
850 assert_eq!(router.key_for("2"), None);
851 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
852 assert_eq!(
853 router.key_for("2"),
854 Some(VideoKey::Person("8:orgid:a".into()))
855 );
856 router.set("2", None);
857 assert_eq!(router.key_for("2"), None);
858 }
859
860 #[test]
861 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
862 let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto);
863 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
864 assert_eq!(channel["mids"], json!(["1"]));
865 let parameter: Value =
866 serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
867 assert_eq!(
868 parameter,
869 json!({"maxVideoSendCapabilities": {
870 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
871 }})
872 );
873 let small: Value = serde_json::from_str(
874 send_capabilities_body(480, 270, 1, VideoQuality::Auto)
875 ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
876 .as_str()
877 .unwrap(),
878 )
879 .unwrap();
880 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
881 let clamped: Value =
882 serde_json::from_str(
883 send_capabilities_body(3840, 2160, 1, VideoQuality::P720)["applyChannelParameters"]
884 ["multiChannelParameter"]["mediaParameter"]
885 .as_str()
886 .unwrap(),
887 )
888 .unwrap();
889 assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280);
890 assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280);
891 }
892
893 #[test]
894 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
895 let mut reporter = SendCapabilityReporter::default();
896 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some());
897 assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none());
898 let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap();
899 let parameter: Value = serde_json::from_str(
900 body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"]
901 .as_str()
902 .unwrap(),
903 )
904 .unwrap();
905 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
906 assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some());
907 }
908}