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