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