| 1 | use std::collections::HashMap; |
| 2 | use std::sync::{Arc, Mutex}; |
| 3 | |
| 4 | use libwebrtc::MediaType; |
| 5 | use libwebrtc::peer_connection::PeerConnection; |
| 6 | use libwebrtc::peer_connection_factory::PeerConnectionFactory; |
| 7 | use libwebrtc::rtp_parameters::{RtpCodecCapability, RtpEncodingParameters}; |
| 8 | use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit}; |
| 9 | use serde_json::{Value, json}; |
| 10 | |
| 11 | use crate::error::{Error, Result}; |
| 12 | use crate::sdp::{LineRole, OfferPlan, StreamLine}; |
| 13 | use crate::send_control::capture_macroblocks; |
| 14 | use crate::video_frame::VideoKey; |
| 15 | use crate::video_quality::VideoQuality; |
| 16 | |
| 17 | pub const RECEIVE_SLOTS: usize = 9; |
| 18 | pub const CAMERA_MID: &str = "1"; |
| 19 | pub const SHARE_MID: &str = "11"; |
| 20 | pub const ONE_TO_ONE_SHARE_MID: &str = "2"; |
| 21 | |
| 22 | const CAMERA_LINE_LABEL: &str = "main-video"; |
| 23 | const SHARE_LINE_LABEL: &str = "applicationsharing-video"; |
| 24 | const CAMERA_STREAM: &str = "camera"; |
| 25 | pub const SCREEN_STREAM: &str = "screen"; |
| 26 | const H264: &str = "video/h264"; |
| 27 | const RTX: &str = "video/rtx"; |
| 28 | const NO_SOURCE: i64 = -1; |
| 29 | const STAGE_720_REQUEST: ReceiveLimits = ReceiveLimits { |
| 30 | max_fs: 3600, |
| 31 | max_fps: 3000, |
| 32 | max_mbps: 108_000, |
| 33 | }; |
| 34 | /// 1080p @ 30: max-fs 8160 macroblocks, mbps ≈ 8160 * 30. |
| 35 | const STAGE_1080_REQUEST: ReceiveLimits = ReceiveLimits { |
| 36 | max_fs: 8160, |
| 37 | max_fps: 3000, |
| 38 | max_mbps: 244_800, |
| 39 | }; |
| 40 | const SMALL_REQUEST: ReceiveLimits = ReceiveLimits { |
| 41 | max_fs: 920, |
| 42 | max_fps: 3000, |
| 43 | max_mbps: 27_600, |
| 44 | }; |
| 45 | const SCREEN_REQUEST: ReceiveLimits = ReceiveLimits { |
| 46 | max_fs: 8160, |
| 47 | max_fps: 1500, |
| 48 | max_mbps: 135_000, |
| 49 | }; |
| 50 | const SUBSCRIBE_PROFILE: &str = "64001f"; |
| 51 | const SIMULCAST_RIDS: [&str; 3] = ["1", "2", "3"]; |
| 52 | const SIMULCAST_START_SCALES: [f64; 3] = [4.0, 2.0, 1.0]; |
| 53 | const SIMULCAST_SCALABILITY: &str = "L1T1"; |
| 54 | const THREE_LAYER_MIN_FS: u32 = 2040; |
| 55 | const SEND_CAPABILITY_FPS: u32 = 30; |
| 56 | |
| 57 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 58 | pub enum TileDetail { |
| 59 | #[default] |
| 60 | Stage, |
| 61 | Small, |
| 62 | } |
| 63 | |
| 64 | impl TileDetail { |
| 65 | fn limits(self, quality: VideoQuality) -> ReceiveLimits { |
| 66 | match self { |
| 67 | TileDetail::Stage => match quality { |
| 68 | VideoQuality::P720 => STAGE_720_REQUEST, |
| 69 | VideoQuality::Auto | VideoQuality::P1080 => STAGE_1080_REQUEST, |
| 70 | }, |
| 71 | TileDetail::Small => SMALL_REQUEST, |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 77 | pub struct VideoWant { |
| 78 | pub mri: String, |
| 79 | pub detail: TileDetail, |
| 80 | } |
| 81 | |
| 82 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 83 | struct ReceiveLimits { |
| 84 | max_fs: u32, |
| 85 | max_fps: u32, |
| 86 | max_mbps: u32, |
| 87 | } |
| 88 | |
| 89 | pub fn offer_plan() -> OfferPlan { |
| 90 | OfferPlan { |
| 91 | screen_share_mids: vec![SHARE_MID.to_owned()], |
| 92 | gallery_mids: Vec::new(), |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn one_to_one_plan() -> OfferPlan { |
| 97 | OfferPlan { |
| 98 | screen_share_mids: vec![ONE_TO_ONE_SHARE_MID.to_owned()], |
| 99 | gallery_mids: Vec::new(), |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Offered after the audio line: camera, `RECEIVE_SLOTS` receive-only slots, screen share (mids 1, 2-10, 11). |
| 104 | #[derive(Clone)] |
| 105 | pub struct VideoLines { |
| 106 | pub camera: RtpTransceiver, |
| 107 | pub share: Option<RtpTransceiver>, |
| 108 | } |
| 109 | |
| 110 | fn h264_only(capabilities: Vec<RtpCodecCapability>) -> Vec<RtpCodecCapability> { |
| 111 | capabilities |
| 112 | .into_iter() |
| 113 | .filter(|codec| { |
| 114 | let mime = codec.mime_type.to_ascii_lowercase(); |
| 115 | mime == H264 || mime == RTX |
| 116 | }) |
| 117 | .collect() |
| 118 | } |
| 119 | |
| 120 | fn add_line( |
| 121 | peer: &PeerConnection, |
| 122 | direction: RtpTransceiverDirection, |
| 123 | stream: Option<&str>, |
| 124 | codecs: Vec<RtpCodecCapability>, |
| 125 | send_encodings: Vec<RtpEncodingParameters>, |
| 126 | ) -> Result<RtpTransceiver> { |
| 127 | let init = RtpTransceiverInit { |
| 128 | direction, |
| 129 | stream_ids: stream.map(str::to_owned).into_iter().collect(), |
| 130 | send_encodings, |
| 131 | }; |
| 132 | let transceiver = peer |
| 133 | .add_transceiver_for_media(MediaType::Video, init) |
| 134 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 135 | transceiver |
| 136 | .set_codec_preferences(codecs) |
| 137 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 138 | Ok(transceiver) |
| 139 | } |
| 140 | |
| 141 | fn simulcast_encodings() -> Vec<RtpEncodingParameters> { |
| 142 | SIMULCAST_RIDS |
| 143 | .iter() |
| 144 | .zip(SIMULCAST_START_SCALES) |
| 145 | .map(|(rid, scale)| RtpEncodingParameters { |
| 146 | rid: (*rid).to_owned(), |
| 147 | scale_resolution_down_by: Some(scale), |
| 148 | scalability_mode: Some(SIMULCAST_SCALABILITY.to_owned()), |
| 149 | ..RtpEncodingParameters::default() |
| 150 | }) |
| 151 | .collect() |
| 152 | } |
| 153 | |
| 154 | pub fn add_video_lines( |
| 155 | peer: &PeerConnection, |
| 156 | factory: &PeerConnectionFactory, |
| 157 | ) -> Result<VideoLines> { |
| 158 | let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs); |
| 159 | let receiving = h264_only( |
| 160 | factory |
| 161 | .get_rtp_receiver_capabilities(MediaType::Video) |
| 162 | .codecs, |
| 163 | ); |
| 164 | let camera = add_line( |
| 165 | peer, |
| 166 | RtpTransceiverDirection::SendRecv, |
| 167 | Some(CAMERA_STREAM), |
| 168 | sending.clone(), |
| 169 | simulcast_encodings(), |
| 170 | )?; |
| 171 | for _ in 0..RECEIVE_SLOTS { |
| 172 | add_line( |
| 173 | peer, |
| 174 | RtpTransceiverDirection::RecvOnly, |
| 175 | None, |
| 176 | receiving.clone(), |
| 177 | Vec::new(), |
| 178 | )?; |
| 179 | } |
| 180 | let share = add_line( |
| 181 | peer, |
| 182 | RtpTransceiverDirection::SendRecv, |
| 183 | Some(SCREEN_STREAM), |
| 184 | sending, |
| 185 | Vec::new(), |
| 186 | )?; |
| 187 | Ok(VideoLines { |
| 188 | camera, |
| 189 | share: Some(share), |
| 190 | }) |
| 191 | } |
| 192 | |
| 193 | /// A sharing line added to a running direct call, the way Teams adds it before its share offer. |
| 194 | pub fn add_share_line( |
| 195 | peer: &PeerConnection, |
| 196 | factory: &PeerConnectionFactory, |
| 197 | ) -> Result<RtpTransceiver> { |
| 198 | let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs); |
| 199 | add_line( |
| 200 | peer, |
| 201 | RtpTransceiverDirection::SendRecv, |
| 202 | Some(SCREEN_STREAM), |
| 203 | sending, |
| 204 | Vec::new(), |
| 205 | ) |
| 206 | } |
| 207 | |
| 208 | pub fn add_one_to_one_lines( |
| 209 | peer: &PeerConnection, |
| 210 | factory: &PeerConnectionFactory, |
| 211 | ) -> Result<VideoLines> { |
| 212 | let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs); |
| 213 | let camera = add_line( |
| 214 | peer, |
| 215 | RtpTransceiverDirection::SendRecv, |
| 216 | Some(CAMERA_STREAM), |
| 217 | sending.clone(), |
| 218 | Vec::new(), |
| 219 | )?; |
| 220 | let share = add_line( |
| 221 | peer, |
| 222 | RtpTransceiverDirection::SendRecv, |
| 223 | Some(SCREEN_STREAM), |
| 224 | sending, |
| 225 | Vec::new(), |
| 226 | )?; |
| 227 | Ok(VideoLines { |
| 228 | camera, |
| 229 | share: Some(share), |
| 230 | }) |
| 231 | } |
| 232 | |
| 233 | /// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation. |
| 234 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 235 | pub struct MediaDescription { |
| 236 | pub mid: &'static str, |
| 237 | pub direction: &'static str, |
| 238 | pub label: Option<&'static str>, |
| 239 | } |
| 240 | |
| 241 | impl MediaDescription { |
| 242 | pub fn camera(sending: bool) -> Self { |
| 243 | Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL) |
| 244 | } |
| 245 | |
| 246 | pub fn share(sending: bool) -> Self { |
| 247 | Self::line(SHARE_MID, sending, SHARE_LINE_LABEL) |
| 248 | } |
| 249 | |
| 250 | fn line(mid: &'static str, sending: bool, label: &'static str) -> Self { |
| 251 | if sending { |
| 252 | MediaDescription { |
| 253 | mid, |
| 254 | direction: "sendrecv", |
| 255 | label: Some(label), |
| 256 | } |
| 257 | } else { |
| 258 | MediaDescription { |
| 259 | mid, |
| 260 | direction: "recvonly", |
| 261 | label: None, |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | pub fn wire(&self) -> Value { |
| 267 | let mut description = json!({"mid": self.mid, "direction": self.direction}); |
| 268 | if let Some(label) = self.label { |
| 269 | description["label"] = json!(label); |
| 270 | } |
| 271 | description |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 276 | pub struct ReceiveSlot { |
| 277 | pub mid: String, |
| 278 | pub stream_id: u32, |
| 279 | } |
| 280 | |
| 281 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 282 | pub struct SlotTable { |
| 283 | pub people: Vec<ReceiveSlot>, |
| 284 | pub screen: Option<ReceiveSlot>, |
| 285 | } |
| 286 | |
| 287 | impl SlotTable { |
| 288 | pub fn from_streams(streams: &[StreamLine]) -> Self { |
| 289 | let slot = |stream: &StreamLine| { |
| 290 | Some(ReceiveSlot { |
| 291 | mid: stream.browser_mid.clone(), |
| 292 | stream_id: stream.source_stream_id?, |
| 293 | }) |
| 294 | }; |
| 295 | let people = streams |
| 296 | .iter() |
| 297 | .filter(|stream| stream.role == LineRole::MainVideo) |
| 298 | .skip(1) |
| 299 | .filter_map(slot) |
| 300 | .take(RECEIVE_SLOTS) |
| 301 | .collect(); |
| 302 | let screen = streams |
| 303 | .iter() |
| 304 | .find(|stream| stream.role == LineRole::ScreenShare) |
| 305 | .and_then(slot); |
| 306 | SlotTable { people, screen } |
| 307 | } |
| 308 | |
| 309 | pub fn is_empty(&self) -> bool { |
| 310 | self.people.is_empty() && self.screen.is_none() |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 315 | pub struct Assignment { |
| 316 | pub mri: String, |
| 317 | pub source: u32, |
| 318 | pub detail: TileDetail, |
| 319 | } |
| 320 | |
| 321 | impl Assignment { |
| 322 | fn same_source(&self, other: &Assignment) -> bool { |
| 323 | self.mri == other.mri && self.source == other.source |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | pub fn plan_receive( |
| 328 | current: &[Option<Assignment>], |
| 329 | candidates: &[Assignment], |
| 330 | ) -> Vec<Option<Assignment>> { |
| 331 | let wanted: Vec<&Assignment> = candidates.iter().take(current.len()).collect(); |
| 332 | let mut next: Vec<Option<Assignment>> = current |
| 333 | .iter() |
| 334 | .map(|slot| { |
| 335 | let held = slot.as_ref()?; |
| 336 | wanted |
| 337 | .iter() |
| 338 | .find(|assignment| assignment.same_source(held)) |
| 339 | .map(|assignment| (*assignment).clone()) |
| 340 | }) |
| 341 | .collect(); |
| 342 | for assignment in wanted { |
| 343 | if next |
| 344 | .iter() |
| 345 | .flatten() |
| 346 | .any(|held| held.same_source(assignment)) |
| 347 | { |
| 348 | continue; |
| 349 | } |
| 350 | if let Some(free) = next.iter_mut().find(|slot| slot.is_none()) { |
| 351 | *free = Some(assignment.clone()); |
| 352 | } |
| 353 | } |
| 354 | next |
| 355 | } |
| 356 | |
| 357 | pub fn prioritize( |
| 358 | candidates: Vec<(String, u32)>, |
| 359 | speaker_history: &[String], |
| 360 | wants: Option<&[VideoWant]>, |
| 361 | ) -> Vec<Assignment> { |
| 362 | if let Some(wants) = wants { |
| 363 | return wants |
| 364 | .iter() |
| 365 | .filter_map(|want| { |
| 366 | let (mri, source) = candidates.iter().find(|(mri, _)| *mri == want.mri)?; |
| 367 | Some(Assignment { |
| 368 | mri: mri.clone(), |
| 369 | source: *source, |
| 370 | detail: want.detail, |
| 371 | }) |
| 372 | }) |
| 373 | .collect(); |
| 374 | } |
| 375 | let rank = |mri: &str| { |
| 376 | speaker_history |
| 377 | .iter() |
| 378 | .position(|speaker| speaker == mri) |
| 379 | .unwrap_or(usize::MAX) |
| 380 | }; |
| 381 | let mut ordered: Vec<Assignment> = candidates |
| 382 | .into_iter() |
| 383 | .map(|(mri, source)| Assignment { |
| 384 | mri, |
| 385 | source, |
| 386 | detail: TileDetail::Stage, |
| 387 | }) |
| 388 | .collect(); |
| 389 | ordered.sort_by_key(|assignment| rank(&assignment.mri)); |
| 390 | ordered |
| 391 | } |
| 392 | |
| 393 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 394 | pub struct SourceRequest { |
| 395 | pub mid: String, |
| 396 | pub stream_id: u32, |
| 397 | pub source: Option<u32>, |
| 398 | pub screen: bool, |
| 399 | pub detail: TileDetail, |
| 400 | pub quality: VideoQuality, |
| 401 | } |
| 402 | |
| 403 | pub fn requests_for( |
| 404 | current: &[Option<Assignment>], |
| 405 | next: &[Option<Assignment>], |
| 406 | slots: &[ReceiveSlot], |
| 407 | quality: VideoQuality, |
| 408 | ) -> Vec<SourceRequest> { |
| 409 | slots |
| 410 | .iter() |
| 411 | .zip(current.iter().zip(next)) |
| 412 | .filter(|(_, (before, after))| before != after) |
| 413 | .map(|(slot, (_, after))| SourceRequest { |
| 414 | mid: slot.mid.clone(), |
| 415 | stream_id: slot.stream_id, |
| 416 | source: after.as_ref().map(|assignment| assignment.source), |
| 417 | screen: false, |
| 418 | detail: after |
| 419 | .as_ref() |
| 420 | .map(|assignment| assignment.detail) |
| 421 | .unwrap_or_default(), |
| 422 | quality, |
| 423 | }) |
| 424 | .collect() |
| 425 | } |
| 426 | |
| 427 | impl SourceRequest { |
| 428 | /// Body of the `applyChannelParameters` link, the signaling twin of the data-channel `sr` message. |
| 429 | pub fn body(&self, sequence_number: u64) -> Value { |
| 430 | let limits = if self.screen { |
| 431 | SCREEN_REQUEST |
| 432 | } else { |
| 433 | self.detail.limits(self.quality) |
| 434 | }; |
| 435 | let control = json!({ |
| 436 | "controlVideoStreaming": { |
| 437 | "sequenceNumber": sequence_number, |
| 438 | "controlInfo": { |
| 439 | "sourceId": self.source.map_or(NO_SOURCE, i64::from), |
| 440 | "streamMsid": self.stream_id, |
| 441 | "fmtParams": [{ |
| 442 | "max-fs": limits.max_fs, |
| 443 | "max-mbps": limits.max_mbps, |
| 444 | "max-fps": limits.max_fps, |
| 445 | "profile-level-id": SUBSCRIBE_PROFILE, |
| 446 | }], |
| 447 | }, |
| 448 | }, |
| 449 | }); |
| 450 | json!({ |
| 451 | "applyChannelParameters": { |
| 452 | "multiChannelParameter": { |
| 453 | "mids": [self.mid], |
| 454 | "mediaParameter": control.to_string(), |
| 455 | }, |
| 456 | }, |
| 457 | }) |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | pub fn send_capabilities_body( |
| 462 | width: u32, |
| 463 | height: u32, |
| 464 | sequence_number: u64, |
| 465 | quality: VideoQuality, |
| 466 | ) -> Value { |
| 467 | let ceiling = quality.capture_height().max(quality.capture_width()); |
| 468 | let width = width.min(ceiling); |
| 469 | let height = height.min(ceiling); |
| 470 | let largest_side = width.max(height); |
| 471 | let layers = if capture_macroblocks(width, height) < THREE_LAYER_MIN_FS { |
| 472 | 2 |
| 473 | } else { |
| 474 | SIMULCAST_RIDS.len() |
| 475 | }; |
| 476 | let capabilities = json!({ |
| 477 | "maxVideoSendCapabilities": { |
| 478 | "max-width": largest_side, |
| 479 | "max-height": largest_side, |
| 480 | "max-fps": SEND_CAPABILITY_FPS, |
| 481 | "max-streams": SIMULCAST_RIDS.len(), |
| 482 | "max-layers": layers, |
| 483 | "sequence-number": sequence_number, |
| 484 | }, |
| 485 | }); |
| 486 | json!({ |
| 487 | "applyChannelParameters": { |
| 488 | "multiChannelParameter": { |
| 489 | "mids": [CAMERA_MID], |
| 490 | "mediaParameter": capabilities.to_string(), |
| 491 | }, |
| 492 | }, |
| 493 | }) |
| 494 | } |
| 495 | |
| 496 | /// Builds a send-capability body only when the camera size differs from the last one reported. |
| 497 | #[derive(Debug, Default)] |
| 498 | pub struct SendCapabilityReporter { |
| 499 | last_size: Option<(u32, u32)>, |
| 500 | last_quality: Option<VideoQuality>, |
| 501 | sequence_number: u64, |
| 502 | } |
| 503 | |
| 504 | impl SendCapabilityReporter { |
| 505 | pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> { |
| 506 | if self.last_size == Some(size) && self.last_quality == Some(quality) { |
| 507 | return None; |
| 508 | } |
| 509 | self.last_size.replace(size); |
| 510 | self.last_quality.replace(quality); |
| 511 | self.sequence_number += 1; |
| 512 | Some(send_capabilities_body( |
| 513 | size.0, |
| 514 | size.1, |
| 515 | self.sequence_number, |
| 516 | quality, |
| 517 | )) |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | #[derive(Clone, Default)] |
| 522 | pub struct VideoRouter { |
| 523 | keys: Arc<Mutex<HashMap<String, VideoKey>>>, |
| 524 | } |
| 525 | |
| 526 | impl VideoRouter { |
| 527 | pub fn set(&self, mid: &str, key: Option<VideoKey>) { |
| 528 | let mut keys = self.keys.lock().expect("router lock"); |
| 529 | match key { |
| 530 | Some(key) => keys.insert(mid.to_owned(), key), |
| 531 | None => keys.remove(mid), |
| 532 | }; |
| 533 | } |
| 534 | |
| 535 | pub fn key_for(&self, mid: &str) -> Option<VideoKey> { |
| 536 | self.keys.lock().expect("router lock").get(mid).cloned() |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | #[cfg(test)] |
| 541 | mod tests { |
| 542 | use super::*; |
| 543 | |
| 544 | fn assignment(name: &str, source: u32) -> Assignment { |
| 545 | Assignment { |
| 546 | mri: format!("8:orgid:{name}"), |
| 547 | source, |
| 548 | detail: TileDetail::Stage, |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | fn stream(mid: &str, role: LineRole, id: Option<u32>) -> StreamLine { |
| 553 | StreamLine { |
| 554 | mid: mid.into(), |
| 555 | browser_mid: mid.into(), |
| 556 | role, |
| 557 | source_stream_id: id, |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn slots_are_the_main_video_lines_after_the_camera_line() { |
| 563 | let streams = vec![ |
| 564 | stream("0", LineRole::MainAudio, Some(201)), |
| 565 | stream("1", LineRole::MainVideo, Some(202)), |
| 566 | stream("2", LineRole::MainVideo, Some(203)), |
| 567 | stream("3", LineRole::MainVideo, Some(204)), |
| 568 | stream("4", LineRole::MainVideo, None), |
| 569 | stream("5", LineRole::MainVideo, Some(206)), |
| 570 | stream("11", LineRole::ScreenShare, Some(207)), |
| 571 | ]; |
| 572 | let table = SlotTable::from_streams(&streams); |
| 573 | let mids: Vec<&str> = table.people.iter().map(|slot| slot.mid.as_str()).collect(); |
| 574 | assert_eq!(mids, vec!["2", "3", "5"]); |
| 575 | assert_eq!( |
| 576 | table.screen, |
| 577 | Some(ReceiveSlot { |
| 578 | mid: "11".into(), |
| 579 | stream_id: 207 |
| 580 | }) |
| 581 | ); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn nobody_is_dropped_while_they_are_still_wanted() { |
| 586 | let held = vec![ |
| 587 | Some(assignment("a", 1)), |
| 588 | Some(assignment("b", 2)), |
| 589 | None, |
| 590 | None, |
| 591 | ]; |
| 592 | let candidates = vec![assignment("c", 3), assignment("a", 1), assignment("b", 2)]; |
| 593 | let next = plan_receive(&held, &candidates); |
| 594 | assert_eq!(next[0], Some(assignment("a", 1))); |
| 595 | assert_eq!(next[1], Some(assignment("b", 2))); |
| 596 | assert_eq!(next[2], Some(assignment("c", 3))); |
| 597 | assert_eq!(next[3], None); |
| 598 | } |
| 599 | |
| 600 | #[test] |
| 601 | fn a_new_speaker_replaces_the_least_recent_person() { |
| 602 | let held: Vec<Option<Assignment>> = (1..=4) |
| 603 | .map(|index| Some(assignment(&format!("p{index}"), index))) |
| 604 | .collect(); |
| 605 | let history = vec![ |
| 606 | "8:orgid:p5".to_owned(), |
| 607 | "8:orgid:p1".to_owned(), |
| 608 | "8:orgid:p2".to_owned(), |
| 609 | "8:orgid:p3".to_owned(), |
| 610 | ]; |
| 611 | let roster = (1..=5) |
| 612 | .map(|index| (format!("8:orgid:p{index}"), index)) |
| 613 | .collect(); |
| 614 | let next = plan_receive(&held, &prioritize(roster, &history, None)); |
| 615 | let names: Vec<&str> = next |
| 616 | .iter() |
| 617 | .flatten() |
| 618 | .map(|held| held.mri.as_str()) |
| 619 | .collect(); |
| 620 | assert_eq!( |
| 621 | names, |
| 622 | vec!["8:orgid:p1", "8:orgid:p2", "8:orgid:p3", "8:orgid:p5"] |
| 623 | ); |
| 624 | } |
| 625 | |
| 626 | #[test] |
| 627 | fn people_who_left_free_their_slot() { |
| 628 | let held = vec![Some(assignment("a", 1)), Some(assignment("b", 2))]; |
| 629 | let next = plan_receive(&held, &[assignment("b", 2)]); |
| 630 | assert_eq!(next, vec![None, Some(assignment("b", 2))]); |
| 631 | let slots = vec![ |
| 632 | ReceiveSlot { |
| 633 | mid: "2".into(), |
| 634 | stream_id: 203, |
| 635 | }, |
| 636 | ReceiveSlot { |
| 637 | mid: "3".into(), |
| 638 | stream_id: 204, |
| 639 | }, |
| 640 | ]; |
| 641 | let requests = requests_for(&held, &next, &slots, VideoQuality::Auto); |
| 642 | assert_eq!( |
| 643 | requests, |
| 644 | vec![SourceRequest { |
| 645 | mid: "2".into(), |
| 646 | stream_id: 203, |
| 647 | source: None, |
| 648 | screen: false, |
| 649 | detail: TileDetail::Stage, |
| 650 | quality: VideoQuality::Auto, |
| 651 | }] |
| 652 | ); |
| 653 | } |
| 654 | |
| 655 | #[test] |
| 656 | fn a_source_request_wraps_the_control_message_like_the_web_client() { |
| 657 | let request = SourceRequest { |
| 658 | mid: "3".into(), |
| 659 | stream_id: 204, |
| 660 | source: Some(302), |
| 661 | screen: false, |
| 662 | detail: TileDetail::Stage, |
| 663 | quality: VideoQuality::Auto, |
| 664 | }; |
| 665 | let body = request.body(7); |
| 666 | let channel = &body["applyChannelParameters"]["multiChannelParameter"]; |
| 667 | assert_eq!(channel["mids"], json!(["3"])); |
| 668 | let parameter: Value = |
| 669 | serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap(); |
| 670 | let info = ¶meter["controlVideoStreaming"]["controlInfo"]; |
| 671 | assert_eq!(parameter["controlVideoStreaming"]["sequenceNumber"], 7); |
| 672 | assert_eq!(info["sourceId"], 302); |
| 673 | assert_eq!(info["streamMsid"], 204); |
| 674 | assert_eq!(info["fmtParams"][0]["max-fs"], 8160); |
| 675 | assert_eq!(info["fmtParams"][0]["max-fps"], 3000); |
| 676 | assert_eq!(info["fmtParams"][0]["max-mbps"], 244_800); |
| 677 | assert_eq!(info["fmtParams"][0]["profile-level-id"], "64001f"); |
| 678 | let cleared = SourceRequest { |
| 679 | source: None, |
| 680 | ..request.clone() |
| 681 | } |
| 682 | .body(8); |
| 683 | let parameter: Value = serde_json::from_str( |
| 684 | cleared["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 685 | .as_str() |
| 686 | .unwrap(), |
| 687 | ) |
| 688 | .unwrap(); |
| 689 | assert_eq!( |
| 690 | parameter["controlVideoStreaming"]["controlInfo"]["sourceId"], |
| 691 | -1 |
| 692 | ); |
| 693 | let screen = SourceRequest { |
| 694 | screen: true, |
| 695 | ..request |
| 696 | } |
| 697 | .body(9); |
| 698 | let parameter: Value = serde_json::from_str( |
| 699 | screen["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 700 | .as_str() |
| 701 | .unwrap(), |
| 702 | ) |
| 703 | .unwrap(); |
| 704 | assert_eq!( |
| 705 | parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], |
| 706 | 8160 |
| 707 | ); |
| 708 | } |
| 709 | |
| 710 | fn want(name: &str, detail: TileDetail) -> VideoWant { |
| 711 | VideoWant { |
| 712 | mri: format!("8:orgid:{name}"), |
| 713 | detail, |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | fn roster_of(count: u32) -> Vec<(String, u32)> { |
| 718 | (1..=count) |
| 719 | .map(|index| (format!("8:orgid:p{index}"), index)) |
| 720 | .collect() |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn nine_slots_hold_nine_visible_people_and_the_tenth_waits() { |
| 725 | let wants: Vec<VideoWant> = (1..=10) |
| 726 | .map(|index| want(&format!("p{index}"), TileDetail::Small)) |
| 727 | .collect(); |
| 728 | let candidates = prioritize(roster_of(10), &[], Some(&wants)); |
| 729 | let next = plan_receive(&vec![None; RECEIVE_SLOTS], &candidates); |
| 730 | assert_eq!(next.iter().flatten().count(), 9); |
| 731 | assert!(next.iter().flatten().all(|held| held.mri != "8:orgid:p10")); |
| 732 | } |
| 733 | |
| 734 | #[test] |
| 735 | fn people_outside_the_visible_tiles_get_no_slot() { |
| 736 | let wants = vec![want("p2", TileDetail::Small), want("p4", TileDetail::Small)]; |
| 737 | let candidates = prioritize(roster_of(5), &["8:orgid:p5".to_owned()], Some(&wants)); |
| 738 | let mris: Vec<&str> = candidates |
| 739 | .iter() |
| 740 | .map(|assignment| assignment.mri.as_str()) |
| 741 | .collect(); |
| 742 | assert_eq!(mris, vec!["8:orgid:p2", "8:orgid:p4"]); |
| 743 | let held = vec![Some(assignment("p5", 5)), None, None]; |
| 744 | let next = plan_receive(&held, &candidates); |
| 745 | assert_eq!( |
| 746 | next.iter() |
| 747 | .flatten() |
| 748 | .map(|held| held.mri.as_str()) |
| 749 | .collect::<Vec<_>>(), |
| 750 | vec!["8:orgid:p2", "8:orgid:p4"] |
| 751 | ); |
| 752 | } |
| 753 | |
| 754 | #[test] |
| 755 | fn nobody_visible_means_no_subscription() { |
| 756 | assert!(prioritize(roster_of(3), &[], Some(&[])).is_empty()); |
| 757 | } |
| 758 | |
| 759 | #[test] |
| 760 | fn a_person_who_moves_to_the_stage_keeps_the_slot_and_gets_the_large_request() { |
| 761 | let small = Assignment { |
| 762 | detail: TileDetail::Small, |
| 763 | ..assignment("a", 1) |
| 764 | }; |
| 765 | let held = vec![None, Some(small), None]; |
| 766 | let wants = vec![want("a", TileDetail::Stage)]; |
| 767 | let next = plan_receive( |
| 768 | &held, |
| 769 | &prioritize(vec![("8:orgid:a".to_owned(), 1)], &[], Some(&wants)), |
| 770 | ); |
| 771 | assert_eq!(next, vec![None, Some(assignment("a", 1)), None]); |
| 772 | let slots: Vec<ReceiveSlot> = (0..3) |
| 773 | .map(|index| ReceiveSlot { |
| 774 | mid: format!("{}", index + 2), |
| 775 | stream_id: 203 + index, |
| 776 | }) |
| 777 | .collect(); |
| 778 | let requests = requests_for(&held, &next, &slots, VideoQuality::Auto); |
| 779 | assert_eq!(requests.len(), 1); |
| 780 | assert_eq!(requests[0].mid, "3"); |
| 781 | assert_eq!(requests[0].detail, TileDetail::Stage); |
| 782 | } |
| 783 | |
| 784 | #[test] |
| 785 | fn stage_and_small_tiles_ask_for_different_resolutions() { |
| 786 | let fmt_for = |detail| { |
| 787 | let request = SourceRequest { |
| 788 | mid: "2".into(), |
| 789 | stream_id: 203, |
| 790 | source: Some(1), |
| 791 | screen: false, |
| 792 | detail, |
| 793 | quality: VideoQuality::Auto, |
| 794 | }; |
| 795 | let body = request.body(1); |
| 796 | let parameter: Value = serde_json::from_str( |
| 797 | body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 798 | .as_str() |
| 799 | .unwrap(), |
| 800 | ) |
| 801 | .unwrap(); |
| 802 | parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0].clone() |
| 803 | }; |
| 804 | assert_eq!(fmt_for(TileDetail::Stage)["max-fs"], 8160); |
| 805 | assert_eq!(fmt_for(TileDetail::Stage)["max-mbps"], 244_800); |
| 806 | assert_eq!(fmt_for(TileDetail::Small)["max-fs"], 920); |
| 807 | assert_eq!(fmt_for(TileDetail::Small)["max-mbps"], 27_600); |
| 808 | let locked = SourceRequest { |
| 809 | mid: "2".into(), |
| 810 | stream_id: 203, |
| 811 | source: Some(1), |
| 812 | screen: false, |
| 813 | detail: TileDetail::Stage, |
| 814 | quality: VideoQuality::P720, |
| 815 | } |
| 816 | .body(1); |
| 817 | let parameter: Value = serde_json::from_str( |
| 818 | locked["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 819 | .as_str() |
| 820 | .unwrap(), |
| 821 | ) |
| 822 | .unwrap(); |
| 823 | assert_eq!( |
| 824 | parameter["controlVideoStreaming"]["controlInfo"]["fmtParams"][0]["max-fs"], |
| 825 | 3600 |
| 826 | ); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn media_descriptions_tell_the_mixer_what_a_line_does() { |
| 831 | assert_eq!( |
| 832 | MediaDescription::camera(true).wire(), |
| 833 | json!({"mid": "1", "direction": "sendrecv", "label": "main-video"}) |
| 834 | ); |
| 835 | assert_eq!( |
| 836 | MediaDescription::camera(false).wire(), |
| 837 | json!({"mid": "1", "direction": "recvonly"}) |
| 838 | ); |
| 839 | assert_eq!( |
| 840 | MediaDescription::share(true).wire(), |
| 841 | json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"}) |
| 842 | ); |
| 843 | } |
| 844 | |
| 845 | #[test] |
| 846 | fn the_router_follows_assignments() { |
| 847 | let router = VideoRouter::default(); |
| 848 | assert_eq!(router.key_for("2"), None); |
| 849 | router.set("2", Some(VideoKey::Person("8:orgid:a".into()))); |
| 850 | assert_eq!( |
| 851 | router.key_for("2"), |
| 852 | Some(VideoKey::Person("8:orgid:a".into())) |
| 853 | ); |
| 854 | router.set("2", None); |
| 855 | assert_eq!(router.key_for("2"), None); |
| 856 | } |
| 857 | |
| 858 | #[test] |
| 859 | fn send_capabilities_name_the_camera_mid_and_the_largest_side() { |
| 860 | let body = send_capabilities_body(1280, 720, 4, VideoQuality::Auto); |
| 861 | let channel = &body["applyChannelParameters"]["multiChannelParameter"]; |
| 862 | assert_eq!(channel["mids"], json!(["1"])); |
| 863 | let parameter: Value = |
| 864 | serde_json::from_str(channel["mediaParameter"].as_str().unwrap()).unwrap(); |
| 865 | assert_eq!( |
| 866 | parameter, |
| 867 | json!({"maxVideoSendCapabilities": { |
| 868 | "max-width": 1280, "max-height": 1280, "max-fps": 30, "max-streams": 3, "max-layers": 3, "sequence-number": 4 |
| 869 | }}) |
| 870 | ); |
| 871 | let small: Value = serde_json::from_str( |
| 872 | send_capabilities_body(480, 270, 1, VideoQuality::Auto) |
| 873 | ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 874 | .as_str() |
| 875 | .unwrap(), |
| 876 | ) |
| 877 | .unwrap(); |
| 878 | assert_eq!(small["maxVideoSendCapabilities"]["max-layers"], 2); |
| 879 | let clamped: Value = serde_json::from_str( |
| 880 | send_capabilities_body(3840, 2160, 1, VideoQuality::P720) |
| 881 | ["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 882 | .as_str() |
| 883 | .unwrap(), |
| 884 | ) |
| 885 | .unwrap(); |
| 886 | assert_eq!(clamped["maxVideoSendCapabilities"]["max-width"], 1280); |
| 887 | assert_eq!(clamped["maxVideoSendCapabilities"]["max-height"], 1280); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn the_reporter_skips_a_repeated_size_and_counts_sequences() { |
| 892 | let mut reporter = SendCapabilityReporter::default(); |
| 893 | assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_some()); |
| 894 | assert!(reporter.body_for((1280, 720), VideoQuality::Auto).is_none()); |
| 895 | let body = reporter.body_for((640, 480), VideoQuality::Auto).unwrap(); |
| 896 | let parameter: Value = serde_json::from_str( |
| 897 | body["applyChannelParameters"]["multiChannelParameter"]["mediaParameter"] |
| 898 | .as_str() |
| 899 | .unwrap(), |
| 900 | ) |
| 901 | .unwrap(); |
| 902 | assert_eq!(parameter["maxVideoSendCapabilities"]["sequence-number"], 2); |
| 903 | assert!(reporter.body_for((640, 480), VideoQuality::P720).is_some()); |
| 904 | } |
| 905 | } |