BlueGit

ict rusty-teams

Files

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

video_layout.rs

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