BlueGit

ict rusty-teams

Files

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

video_layout.rs

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