BlueGit

ict rusty-teams

Files

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

video_layout.rs

070d92b0 History
video_layout.rs 22.5 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use libwebrtc::peer_connection::PeerConnection;
5use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters};
7use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
8use libwebrtc::MediaType;
9use serde_json::{Value, json};
10
11use crate::error::{Error, Result};
12use crate::send_control::capture_macroblocks;
13use crate::sdp::{LineRole, OfferPlan, StreamLine};
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";
24const SCREEN_STREAM: &str = "screen";
25const H264: &str = "video/h264";
26const RTX: &str = "video/rtx";
27const NO_SOURCE: i64 = -1;
28const STAGE_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 3600, max_fps: 3000, max_mbps: 108_000 };
29const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 920, max_fps: 3000, max_mbps: 27_600 };
30const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { max_fs: 8160, max_fps: 1500, max_mbps: 135_000 };
31const SUBSCRIBE_PROFILE: &str = "64001f";
32const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"];
33const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0];
34const SIMULCAST_SCALABILITY: &str = "L1T1";
35const THREE_LAYER_MIN_FS: u32 = 2040;
36const SEND_CAPABILITY_FPS: u32 = 30;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum TileDetail {
40 #[default]
41 Stage,
42 Small,
43}
44
45impl TileDetail {
46 fn limits(self) -> ReceiveLimits {
47 match self {
48 TileDetail::Stage => STAGE_REQUEST,
49 TileDetail::Small => SMALL_REQUEST,
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct VideoWant {
56 pub mri: String,
57 pub detail: TileDetail,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61struct ReceiveLimits {
62 max_fs: u32,
63 max_fps: u32,
64 max_mbps: u32,
65}
66
67pub fn offer_plan() -> OfferPlan {
68 OfferPlan {
69 screen_share_mids: vec![SHARE_MID.to_owned()],
70 gallery_mids: Vec::new(),
71 }
72}
73
74pub fn one_to_one_plan() -> OfferPlan {
75 OfferPlan {
76 screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()],
77 gallery_mids: Vec::new(),
78 }
79}
80
81/// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11).
82#[derive(Clone)]
83pub struct VideoLines {
84 pub camera: RtpTransceiver,
85 pub share: Option<RtpTransceiver>,
86}
87
88fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> {
89 capabilities
90 .into_iter()
91 .filter(|codec| {
92 let mime = codec.mime_type.to_ascii_lowercase();
93 mime == H264 || mime == RTX
94 })
95 .collect()
96}
97
98fn add_line(
99 peer: &PeerConnection,
100 direction: RtpTransceiverDirection,
101 stream: Option<&str>,
102 codecs: Vec<RtpCodecCapability>,
103 send_encodings: Vec<RtpEncodingParameters>,
104) -> Result<RtpTransceiver> {
105 let init = RtpTransceiverInit {
106 direction,
107 stream_ids: stream.map(str::to_owned).into_iter().collect(),
108 send_encodings,
109 };
110 let transceiver = peer
111 .add_transceiver_for_media(MediaType::Video, init)
112 .map_err(|error| Error::Webrtc(error.to_string()))?;
113 transceiver
114 .set_codec_preferences(codecs)
115 .map_err(|error| Error::Webrtc(error.to_string()))?;
116 Ok(transceiver)
117}
118
119fn simulcast_encodings() -> Vec<RtpEncodingParameters> {
120 SIMULCAST_RIDS
121 .iter()
122 .zip(SIMULCAST_START_SCALES)
123 .map(|(rid, scale)| RtpEncodingParameters {
124 rid: (*rid).to_owned(),
125 scale_resolution_down_by: Some(scale),
126 scalability_mode: Some(SIMULCAST_SCALABILITY.to_owned()),
127 ..RtpEncodingParameters::default()
128 })
129 .collect()
130}
131
132pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
133 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
134 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
135 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), simulcast_encodings())?;
136 for _ in 0..RECEIVE_SLOTS {
137 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving.clone(), Vec::new())?;
138 }
139 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
140 Ok(VideoLines { camera, share: Some(share) })
141}
142
143pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
144 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
145 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
146 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending, Vec::new())?;
147 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving, Vec::new())?;
148 Ok(VideoLines { camera, share: None })
149}
150
151/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct MediaDescription {
154 pub mid: &'static str,
155 pub direction: &'static str,
156 pub label: Option<&'static str>,
157}
158
159impl MediaDescription {
160 pub fn camera(sending: bool) -> Self {
161 Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL)
162 }
163
164 pub fn share(sending: bool) -> Self {
165 Self::line(SHARE_MID, sending, SHARE_LINE_LABEL)
166 }
167
168 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
169 if sending {
170 MediaDescription { mid, direction: "sendrecv", label: Some(label) }
171 } else {
172 MediaDescription { mid, direction: "recvonly", label: None }
173 }
174 }
175
176 pub fn wire(&self) -> Value {
177 let mut description = json!({"mid": self.mid, "direction": self.direction});
178 if let Some(label) = self.label {
179 description["label"] = json!(label);
180 }
181 description
182 }
183}
184
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct ReceiveSlot {
187 pub mid: String,
188 pub stream_id: u32,
189}
190
191#[derive(Debug, Clone, Default, PartialEq, Eq)]
192pub struct SlotTable {
193 pub people: Vec<ReceiveSlot>,
194 pub screen: Option<ReceiveSlot>,
195}
196
197impl SlotTable {
198 pub fn from_streams(streams: &[StreamLine]) -> Self {
199 let slot = |stream: &StreamLine| {
200 Some(ReceiveSlot {
201 mid: stream.browser_mid.clone(),
202 stream_id: stream.source_stream_id?,
203 })
204 };
205 let people = streams
206 .iter()
207 .filter(|stream| stream.role == LineRole::MainVideo)
208 .skip(1)
209 .filter_map(slot)
210 .take(RECEIVE_SLOTS)
211 .collect();
212 let screen = streams.iter().find(|stream| stream.role == LineRole::ScreenShare).and_then(slot);
213 SlotTable { people, screen }
214 }
215
216 pub fn is_empty(&self) -> bool {
217 self.people.is_empty() && self.screen.is_none()
218 }
219}
220
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct Assignment {
223 pub mri: String,
224 pub source: u32,
225 pub detail: TileDetail,
226}
227
228impl Assignment {
229 fn same_source(&self, other: &Assignment) -> bool {
230 self.mri == other.mri && self.source == other.source
231 }
232}
233
234pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
235 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
236 let mut next: Vec<Option<Assignment>> = current
237 .iter()
238 .map(|slot| {
239 let held = slot.as_ref()?;
240 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
241 })
242 .collect();
243 for assignment in wanted {
244 if next.iter().flatten().any(|held| held.same_source(assignment)) {
245 continue;
246 }
247 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
248 *free = Some(assignment.clone());
249 }
250 }
251 next
252}
253
254pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
255 if let Some(wants) = wants {
256 return wants
257 .iter()
258 .filter_map(|want| {
259 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
260 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
261 })
262 .collect();
263 }
264 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
265 let mut ordered: Vec<Assignment> = candidates
266 .into_iter()
267 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
268 .collect();
269 ordered.sort_by_key(|assignment| rank(&assignment.mri));
270 ordered
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct SourceRequest {
275 pub mid: String,
276 pub stream_id: u32,
277 pub source: Option<u32>,
278 pub screen: bool,
279 pub detail: TileDetail,
280}
281
282pub fn requests_for(
283 current: &[Option<Assignment>],
284 next: &[Option<Assignment>],
285 slots: &[ReceiveSlot],
286) -> Vec<SourceRequest> {
287 slots
288 .iter()
289 .zip(current.iter().zip(next))
290 .filter(|(_, (before, after))| before != after)
291 .map(|(slot, (_, after))| SourceRequest {
292 mid: slot.mid.clone(),
293 stream_id: slot.stream_id,
294 source: after.as_ref().map(|assignment| assignment.source),
295 screen: false,
296 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
297 })
298 .collect()
299}
300
301impl SourceRequest {
302 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
303 pub fn body(&self, sequence_number: u64) -> Value {
304 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
305 let control = json!({
306 "controlVideoStreaming": {
307 "sequenceNumber": sequence_number,
308 "controlInfo": {
309 "sourceId": self.source.map_or(NO_SOURCE, i64::from),
310 "streamMsid": self.stream_id,
311 "fmtParams": [{
312 "max-fs": limits.max_fs,
313 "max-mbps": limits.max_mbps,
314 "max-fps": limits.max_fps,
315 "profile-level-id": SUBSCRIBE_PROFILE,
316 }],
317 },
318 },
319 });
320 json!({
321 "applyChannelParameters": {
322 "multiChannelParameter": {
323 "mids": [self.mid],
324 "mediaParameter": control.to_string(),
325 },
326 },
327 })
328 }
329}
330
331pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
332 let largest_side = width.max(height);
333 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS { 2 } else { SIMULCAST_RIDS.len() };
334 let capabilities = json!({
335 "maxVideoSendCapabilities": {
336 "max-width": largest_side,
337 "max-height": largest_side,
338 "max-fps": SEND_CAPABILITY_FPS,
339 "max-streams": SIMULCAST_RIDS.len(),
340 "max-layers": layers,
341 "sequence-number": sequence_number,
342 },
343 });
344 json!({
345 "applyChannelParameters": {
346 "multiChannelParameter": {
347 "mids": [CAMERA_MID],
348 "mediaParameter": capabilities.to_string(),
349 },
350 },
351 })
352}
353
354/// Builds a send-capability body only when the camera size differs from the last one reported.
355#[derive(Debug, Default)]
356pub struct SendCapabilityReporter {
357 last_size: Option<(u32, u32)>,
358 sequence_number: u64,
359}
360
361impl SendCapabilityReporter {
362 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
363 if self.last_size == Some(size) {
364 return None;
365 }
366 self.last_size = Some(size);
367 self.sequence_number += 1;
368 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
369 }
370}
371
372#[derive(Clone, Default)]
373pub struct VideoRouter {
374 keys: Arc<Mutex<HashMap<String, VideoKey>>>,
375}
376
377impl VideoRouter {
378 pub fn set(&self, mid: &str, key: Option<VideoKey>) {
379 let mut keys = self.keys.lock().expect("router lock");
380 match key {
381 Some(key) => keys.insert(mid.to_owned(), key),
382 None => keys.remove(mid),
383 };
384 }
385
386 pub fn key_for(&self, mid: &str) -> Option<VideoKey> {
387 self.keys.lock().expect("router lock").get(mid).cloned()
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 fn assignment(name: &str, source: u32) -> Assignment {
396 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
397 }
398
399 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
400 StreamLine { mid: mid.into(), browser_mid: mid.into(), role, source_stream_id: id }
401 }
402
403 #[test]
404 fn slots_are_the_main_video_lines_after_the_camera_line() {
405 let streams = vec![
406 stream("0", LineRole::MainAudio, Some(201)),
407 stream("1", LineRole::MainVideo, Some(202)),
408 stream("2", LineRole::MainVideo, Some(203)),
409 stream("3", LineRole::MainVideo, Some(204)),
410 stream("4", LineRole::MainVideo, None),
411 stream("5", LineRole::MainVideo, Some(206)),
412 stream("11", LineRole::ScreenShare, Some(207)),
413 ];
414 let table = SlotTable::from_streams(&streams);
415 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
416 assert_eq!(mids, vec!["2", "3", "5"]);
417 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
418 }
419
420 #[test]
421 fn nobody_is_dropped_while_they_are_still_wanted() {
422 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2)), None, None];
423 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
424 let next = plan_receive(&held, &candidates);
425 assert_eq!(next[0], Some(assignment("a", 1)));
426 assert_eq!(next[1], Some(assignment("b", 2)));
427 assert_eq!(next[2], Some(assignment("c", 3)));
428 assert_eq!(next[3], None);
429 }
430
431 #[test]
432 fn a_new_speaker_replaces_the_least_recent_person() {
433 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
434 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
435 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
436 let next = plan_receive(&held, &prioritize(roster, &history, None));
437 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
438 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
439 }
440
441 #[test]
442 fn people_who_left_free_their_slot() {
443 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))];
444 let next = plan_receive(&held, &[assignment("b", 2)]);
445 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
446 let slots = vec![
447 ReceiveSlot { mid: "2".into(), stream_id: 203 },
448 ReceiveSlot { mid: "3".into(), stream_id: 204 },
449 ];
450 let requests = requests_for(&held, &next, &slots);
451 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
452 }
453
454 #[test]
455 fn a_source_request_wraps_the_control_message_like_the_web_client() {
456 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
457 let body = request.body(7);
458 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
459 assert_eq!(channel["mids"], json!(["3"]));
460 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
461 let info = &parameter["controlVideoStreaming"]["controlInfo"];
462 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
463 assert_eq!(info["sourceId"], 302);
464 assert_eq!(info["streamMsid"], 204);
465 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
466 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
467 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
468 let cleared = SourceRequest { source: None, ..request.clone() }.body(8);
469 let parameter: Value =
470 serde_json::from_str(cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
471 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["sourceId"], -1);
472 let screen = SourceRequest { screen: true, ..request }.body(9);
473 let parameter: Value =
474 serde_json::from_str(screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
475 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
476 }
477
478 fn want(name: &str, detail: TileDetail) -> VideoWant {
479 VideoWant { mri: format!("8:orgid:{name}"), detail }
480 }
481
482 fn roster_of(count: u32) -> Vec<(String, u32)> {
483 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
484 }
485
486 #[test]
487 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
488 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
489 let candidates = prioritize(roster_of(10), &[], Some(&wants));
490 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
491 assert_eq!(next.iter().flatten().count(), 9);
492 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
493 }
494
495 #[test]
496 fn people_outside_the_visible_tiles_get_no_slot() {
497 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
498 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
499 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
500 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
501 let held = vec![Some(assignment("p5", 5)), None, None];
502 let next = plan_receive(&held, &candidates);
503 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
504 }
505
506 #[test]
507 fn nobody_visible_means_no_subscription() {
508 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
509 }
510
511 #[test]
512 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
513 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
514 let held = vec![None, Some(small), None];
515 let wants = vec![want("a", TileDetail::Stage)];
516 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
517 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
518 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
519 let requests = requests_for(&held, &next, &slots);
520 assert_eq!(requests.len(), 1);
521 assert_eq!(requests[0].mid, "3");
522 assert_eq!(requests[0].detail, TileDetail::Stage);
523 }
524
525 #[test]
526 fn stage_and_small_tiles_ask_for_different_resolutions() {
527 let fmt_for = |detail| {
528 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
529 let body = request.body(1);
530 let parameter: Value =
531 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
532 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
533 };
534 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
535 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
536 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
537 }
538
539 #[test]
540 fn media_descriptions_tell_the_mixer_what_a_line_does() {
541 assert_eq!(
542 MediaDescription::camera(true).wire(),
543 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
544 );
545 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
546 assert_eq!(
547 MediaDescription::share(true).wire(),
548 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
549 );
550 }
551
552 #[test]
553 fn the_router_follows_assignments() {
554 let router = VideoRouter::default();
555 assert_eq!(router.key_for("2"), None);
556 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
557 assert_eq!(router.key_for("2"), Some(VideoKey::Person("8:orgid:a".into())));
558 router.set("2", None);
559 assert_eq!(router.key_for("2"), None);
560 }
561
562 #[test]
563 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
564 let body = send_capabilities_body(1280, 720, 4);
565 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
566 assert_eq!(channel["mids"], json!(["1"]));
567 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
568 assert_eq!(
569 parameter,
570 json!({"maxVideoSendCapabilities": {
571 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
572 }})
573 );
574 let small: Value =
575 serde_json::from_str(send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap())
576 .unwrap();
577 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
578 }
579
580 #[test]
581 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
582 let mut reporter = SendCapabilityReporter::default();
583 assert!(reporter.body_for((1280, 720)).is_some());
584 assert!(reporter.body_for((1280, 720)).is_none());
585 let body = reporter.body_for((640, 480)).unwrap();
586 let parameter: Value =
587 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
588 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
589 }
590}