BlueGit

ict rusty-teams

Files

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

video_layout.rs

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