BlueGit

ict rusty-teams

Files

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

video_layout.rs

video_layout.rs 22.4 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 camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
146 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
147 Ok(VideoLines { camera, share: Some(share) })
148}
149
150/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct MediaDescription {
153 pub mid: &'static str,
154 pub direction: &'static str,
155 pub label: Option<&'static str>,
156}
157
158impl MediaDescription {
159 pub fn camera(sending: bool) -> Self {
160 Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL)
161 }
162
163 pub fn share(sending: bool) -> Self {
164 Self::line(SHARE_MID, sending, SHARE_LINE_LABEL)
165 }
166
167 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
168 if sending {
169 MediaDescription { mid, direction: "sendrecv", label: Some(label) }
170 } else {
171 MediaDescription { mid, direction: "recvonly", label: None }
172 }
173 }
174
175 pub fn wire(&self) -> Value {
176 let mut description = json!({"mid": self.mid, "direction": self.direction});
177 if let Some(label) = self.label {
178 description["label"] = json!(label);
179 }
180 description
181 }
182}
183
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct ReceiveSlot {
186 pub mid: String,
187 pub stream_id: u32,
188}
189
190#[derive(Debug, Clone, Default, PartialEq, Eq)]
191pub struct SlotTable {
192 pub people: Vec<ReceiveSlot>,
193 pub screen: Option<ReceiveSlot>,
194}
195
196impl SlotTable {
197 pub fn from_streams(streams: &[StreamLine]) -> Self {
198 let slot = |stream: &StreamLine| {
199 Some(ReceiveSlot {
200 mid: stream.browser_mid.clone(),
201 stream_id: stream.source_stream_id?,
202 })
203 };
204 let people = streams
205 .iter()
206 .filter(|stream| stream.role == LineRole::MainVideo)
207 .skip(1)
208 .filter_map(slot)
209 .take(RECEIVE_SLOTS)
210 .collect();
211 let screen = streams.iter().find(|stream| stream.role == LineRole::ScreenShare).and_then(slot);
212 SlotTable { people, screen }
213 }
214
215 pub fn is_empty(&self) -> bool {
216 self.people.is_empty() && self.screen.is_none()
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Assignment {
222 pub mri: String,
223 pub source: u32,
224 pub detail: TileDetail,
225}
226
227impl Assignment {
228 fn same_source(&self, other: &Assignment) -> bool {
229 self.mri == other.mri && self.source == other.source
230 }
231}
232
233pub fn plan_receive(current: &[Option<Assignment>], candidates: &[Assignment]) -> Vec<Option<Assignment>> {
234 let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect();
235 let mut next: Vec<Option<Assignment>> = current
236 .iter()
237 .map(|slot| {
238 let held = slot.as_ref()?;
239 wanted.iter().find(|assignment| assignment.same_source(held)).map(|assignment| (*assignment).clone())
240 })
241 .collect();
242 for assignment in wanted {
243 if next.iter().flatten().any(|held| held.same_source(assignment)) {
244 continue;
245 }
246 if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) {
247 *free = Some(assignment.clone());
248 }
249 }
250 next
251}
252
253pub fn prioritize(candidates: Vec<(String, u32)>, speaker_history: &[String], wants: Option<&[VideoWant]>) -> Vec<Assignment> {
254 if let Some(wants) = wants {
255 return wants
256 .iter()
257 .filter_map(|want| {
258 let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?;
259 Some(Assignment { mri: mri.clone(), source: *source, detail: want.detail })
260 })
261 .collect();
262 }
263 let rank = |mri: &str| speaker_history.iter().position(|speaker| speaker == mri).unwrap_or(usize::MAX);
264 let mut ordered: Vec<Assignment> = candidates
265 .into_iter()
266 .map(|(mri, source)| Assignment { mri, source, detail: TileDetail::Stage })
267 .collect();
268 ordered.sort_by_key(|assignment| rank(&assignment.mri));
269 ordered
270}
271
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct SourceRequest {
274 pub mid: String,
275 pub stream_id: u32,
276 pub source: Option<u32>,
277 pub screen: bool,
278 pub detail: TileDetail,
279}
280
281pub fn requests_for(
282 current: &[Option<Assignment>],
283 next: &[Option<Assignment>],
284 slots: &[ReceiveSlot],
285) -> Vec<SourceRequest> {
286 slots
287 .iter()
288 .zip(current.iter().zip(next))
289 .filter(|(_, (before, after))| before != after)
290 .map(|(slot, (_, after))| SourceRequest {
291 mid: slot.mid.clone(),
292 stream_id: slot.stream_id,
293 source: after.as_ref().map(|assignment| assignment.source),
294 screen: false,
295 detail: after.as_ref().map(|assignment| assignment.detail).unwrap_or_default(),
296 })
297 .collect()
298}
299
300impl SourceRequest {
301 /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message.
302 pub fn body(&self, sequence_number: u64) -> Value {
303 let limits = if self.screen { SCREEN_REQUEST } else { self.detail.limits() };
304 let control = json!({
305 "controlVideoStreaming": {
306 "sequenceNumber": sequence_number,
307 "controlInfo": {
308 "sourceId": self.source.map_or(NO_SOURCE, i64::from),
309 "streamMsid": self.stream_id,
310 "fmtParams": [{
311 "max-fs": limits.max_fs,
312 "max-mbps": limits.max_mbps,
313 "max-fps": limits.max_fps,
314 "profile-level-id": SUBSCRIBE_PROFILE,
315 }],
316 },
317 },
318 });
319 json!({
320 "applyChannelParameters": {
321 "multiChannelParameter": {
322 "mids": [self.mid],
323 "mediaParameter": control.to_string(),
324 },
325 },
326 })
327 }
328}
329
330pub fn send_capabilities_body(width: u32, height: u32, sequence_number: u64) -> Value {
331 let largest_side = width.max(height);
332 let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS { 2 } else { SIMULCAST_RIDS.len() };
333 let capabilities = json!({
334 "maxVideoSendCapabilities": {
335 "max-width": largest_side,
336 "max-height": largest_side,
337 "max-fps": SEND_CAPABILITY_FPS,
338 "max-streams": SIMULCAST_RIDS.len(),
339 "max-layers": layers,
340 "sequence-number": sequence_number,
341 },
342 });
343 json!({
344 "applyChannelParameters": {
345 "multiChannelParameter": {
346 "mids": [CAMERA_MID],
347 "mediaParameter": capabilities.to_string(),
348 },
349 },
350 })
351}
352
353/// Builds a send-capability body only when the camera size differs from the last one reported.
354#[derive(Debug, Default)]
355pub struct SendCapabilityReporter {
356 last_size: Option<(u32, u32)>,
357 sequence_number: u64,
358}
359
360impl SendCapabilityReporter {
361 pub fn body_for(&mut self, size: (u32, u32)) -> Option<Value> {
362 if self.last_size == Some(size) {
363 return None;
364 }
365 self.last_size = Some(size);
366 self.sequence_number += 1;
367 Some(send_capabilities_body(size.0, size.1, self.sequence_number))
368 }
369}
370
371#[derive(Clone, Default)]
372pub struct VideoRouter {
373 keys: Arc<Mutex<HashMap<String, VideoKey>>>,
374}
375
376impl VideoRouter {
377 pub fn set(&self, mid: &str, key: Option<VideoKey>) {
378 let mut keys = self.keys.lock().expect("router lock");
379 match key {
380 Some(key) => keys.insert(mid.to_owned(), key),
381 None => keys.remove(mid),
382 };
383 }
384
385 pub fn key_for(&self, mid: &str) -> Option<VideoKey> {
386 self.keys.lock().expect("router lock").get(mid).cloned()
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 fn assignment(name: &str, source: u32) -> Assignment {
395 Assignment { mri: format!("8:orgid:{name}"), source, detail: TileDetail::Stage }
396 }
397
398 fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine {
399 StreamLine { mid: mid.into(), browser_mid: mid.into(), role, source_stream_id: id }
400 }
401
402 #[test]
403 fn slots_are_the_main_video_lines_after_the_camera_line() {
404 let streams = vec![
405 stream("0", LineRole::MainAudio, Some(201)),
406 stream("1", LineRole::MainVideo, Some(202)),
407 stream("2", LineRole::MainVideo, Some(203)),
408 stream("3", LineRole::MainVideo, Some(204)),
409 stream("4", LineRole::MainVideo, None),
410 stream("5", LineRole::MainVideo, Some(206)),
411 stream("11", LineRole::ScreenShare, Some(207)),
412 ];
413 let table = SlotTable::from_streams(&streams);
414 let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect();
415 assert_eq!(mids, vec!["2", "3", "5"]);
416 assert_eq!(table.screen, Some(ReceiveSlot { mid: "11".into(), stream_id: 207 }));
417 }
418
419 #[test]
420 fn nobody_is_dropped_while_they_are_still_wanted() {
421 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2)), None, None];
422 let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)];
423 let next = plan_receive(&held, &candidates);
424 assert_eq!(next[0], Some(assignment("a", 1)));
425 assert_eq!(next[1], Some(assignment("b", 2)));
426 assert_eq!(next[2], Some(assignment("c", 3)));
427 assert_eq!(next[3], None);
428 }
429
430 #[test]
431 fn a_new_speaker_replaces_the_least_recent_person() {
432 let held: Vec<Option<Assignment>> = (1..=4).map(|index| Some(assignment(&format!("p{index}"), index))).collect();
433 let history = vec!["8:orgid:p5".to_owned(), "8:orgid:p1".to_owned(), "8:orgid:p2".to_owned(), "8:orgid:p3".to_owned()];
434 let roster = (1..=5).map(|index| (format!("8:orgid:p{index}"), index)).collect();
435 let next = plan_receive(&held, &prioritize(roster, &history, None));
436 let names: Vec<&str> = next.iter().flatten().map(|held| held.mri.as_str()).collect();
437 assert_eq!(names, vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"]);
438 }
439
440 #[test]
441 fn people_who_left_free_their_slot() {
442 let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))];
443 let next = plan_receive(&held, &[assignment("b", 2)]);
444 assert_eq!(next, vec![None, Some(assignment("b", 2))]);
445 let slots = vec![
446 ReceiveSlot { mid: "2".into(), stream_id: 203 },
447 ReceiveSlot { mid: "3".into(), stream_id: 204 },
448 ];
449 let requests = requests_for(&held, &next, &slots);
450 assert_eq!(requests, vec![SourceRequest { mid: "2".into(), stream_id: 203, source: None, screen: false, detail: TileDetail::Stage }]);
451 }
452
453 #[test]
454 fn a_source_request_wraps_the_control_message_like_the_web_client() {
455 let request = SourceRequest { mid: "3".into(), stream_id: 204, source: Some(302), screen: false, detail: TileDetail::Stage };
456 let body = request.body(7);
457 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
458 assert_eq!(channel["mids"], json!(["3"]));
459 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
460 let info = &parameter["controlVideoStreaming"]["controlInfo"];
461 assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7);
462 assert_eq!(info["sourceId"], 302);
463 assert_eq!(info["streamMsid"], 204);
464 assert_eq!(info["fmtParams"][0]["max-fs"], 3600);
465 assert_eq!(info["fmtParams"][0]["max-fps"], 3000);
466 assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f");
467 let cleared = SourceRequest { source: None, ..request.clone() }.body(8);
468 let parameter: Value =
469 serde_json::from_str(cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
470 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["sourceId"], -1);
471 let screen = SourceRequest { screen: true, ..request }.body(9);
472 let parameter: Value =
473 serde_json::from_str(screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
474 assert_eq!(parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], 8160);
475 }
476
477 fn want(name: &str, detail: TileDetail) -> VideoWant {
478 VideoWant { mri: format!("8:orgid:{name}"), detail }
479 }
480
481 fn roster_of(count: u32) -> Vec<(String, u32)> {
482 (1..=count).map(|index| (format!("8:orgid:p{index}"), index)).collect()
483 }
484
485 #[test]
486 fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() {
487 let wants: Vec<VideoWant> = (1..=10).map(|index| want(&format!("p{index}"), TileDetail::Small)).collect();
488 let candidates = prioritize(roster_of(10), &[], Some(&wants));
489 let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates);
490 assert_eq!(next.iter().flatten().count(), 9);
491 assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10"));
492 }
493
494 #[test]
495 fn people_outside_the_visible_tiles_get_no_slot() {
496 let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)];
497 let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants));
498 let mris: Vec<&str> = candidates.iter().map(|assignment| assignment.mri.as_str()).collect();
499 assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]);
500 let held = vec![Some(assignment("p5", 5)), None, None];
501 let next = plan_receive(&held, &candidates);
502 assert_eq!(next.iter().flatten().map(|held| held.mri.as_str()).collect::<Vec<_>>(), vec!["8:orgid:p2", "8:orgid:p4"]);
503 }
504
505 #[test]
506 fn nobody_visible_means_no_subscription() {
507 assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty());
508 }
509
510 #[test]
511 fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() {
512 let small = Assignment { detail: TileDetail::Small, ..assignment("a", 1) };
513 let held = vec![None, Some(small), None];
514 let wants = vec![want("a", TileDetail::Stage)];
515 let next = plan_receive(&held, &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)));
516 assert_eq!(next, vec![None, Some(assignment("a", 1)), None]);
517 let slots: Vec<ReceiveSlot> = (0..3).map(|index| ReceiveSlot { mid: format!("{}", index + 2), stream_id: 203 + index }).collect();
518 let requests = requests_for(&held, &next, &slots);
519 assert_eq!(requests.len(), 1);
520 assert_eq!(requests[0].mid, "3");
521 assert_eq!(requests[0].detail, TileDetail::Stage);
522 }
523
524 #[test]
525 fn stage_and_small_tiles_ask_for_different_resolutions() {
526 let fmt_for = |detail| {
527 let request = SourceRequest { mid: "2".into(), stream_id: 203, source: Some(1), screen: false, detail };
528 let body = request.body(1);
529 let parameter: Value =
530 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
531 parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone()
532 };
533 assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 3600);
534 assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920);
535 assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600);
536 }
537
538 #[test]
539 fn media_descriptions_tell_the_mixer_what_a_line_does() {
540 assert_eq!(
541 MediaDescription::camera(true).wire(),
542 json!({"mid": "1", "direction": "sendrecv", "label": "main-video"})
543 );
544 assert_eq!(MediaDescription::camera(false).wire(), json!({"mid": "1", "direction": "recvonly"}));
545 assert_eq!(
546 MediaDescription::share(true).wire(),
547 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
548 );
549 }
550
551 #[test]
552 fn the_router_follows_assignments() {
553 let router = VideoRouter::default();
554 assert_eq!(router.key_for("2"), None);
555 router.set("2", Some(VideoKey::Person("8:orgid:a".into())));
556 assert_eq!(router.key_for("2"), Some(VideoKey::Person("8:orgid:a".into())));
557 router.set("2", None);
558 assert_eq!(router.key_for("2"), None);
559 }
560
561 #[test]
562 fn send_capabilities_name_the_camera_mid_and_the_largest_side() {
563 let body = send_capabilities_body(1280, 720, 4);
564 let channel = &body["applyChannelParameters"]["multiChannelParameter"];
565 assert_eq!(channel["mids"], json!(["1"]));
566 let parameter: Value = serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap();
567 assert_eq!(
568 parameter,
569 json!({"maxVideoSendCapabilities": {
570 "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4
571 }})
572 );
573 let small: Value =
574 serde_json::from_str(send_capabilities_body(480, 270, 1)["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap())
575 .unwrap();
576 assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2);
577 }
578
579 #[test]
580 fn the_reporter_skips_a_repeated_size_and_counts_sequences() {
581 let mut reporter = SendCapabilityReporter::default();
582 assert!(reporter.body_for((1280, 720)).is_some());
583 assert!(reporter.body_for((1280, 720)).is_none());
584 let body = reporter.body_for((640, 480)).unwrap();
585 let parameter: Value =
586 serde_json::from_str(body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"].as_str().unwrap()).unwrap();
587 assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2);
588 }
589}