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