BlueGit

ict rusty-teams

Files

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

video_layout.rs

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