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