| 1 | use std::collections::{BTreeMap, HashMap}; |
| 2 | |
| 3 | use serde_json::Value; |
| 4 | |
| 5 | const MACROBLOCK: u32 = 16; |
| 6 | const FPS_UNIT: f64 = 100.0; |
| 7 | const BITRATE_UNIT: u64 = 1200; |
| 8 | const SCALE_STEP: f64 = 1.01; |
| 9 | const MAX_SCALE: f64 = 16.0; |
| 10 | pub const KEYFRAME_NUDGE: f64 = 1.1; |
| 11 | const KNOWN_KEYS: [&str; 10] = |
| 12 | ["max-fs", "max-fps", "max-mbps", "max-br", "KeyFrame", "profile-level-id", "rid", "ssrc", "sequence-number", "packetization-mode"]; |
| 13 | |
| 14 | /// One layer of a mixer `controlVideoStreaming` request (VDCLC) for what we send. |
| 15 | #[derive(Debug, Clone, Default, PartialEq)] |
| 16 | pub struct SendLimit { |
| 17 | pub max_fs: Option<u32>, |
| 18 | pub max_mbps: Option<u32>, |
| 19 | pub max_fps: Option<f64>, |
| 20 | pub max_bitrate: Option<u64>, |
| 21 | pub keyframe: bool, |
| 22 | pub rid: Option<String>, |
| 23 | pub ssrc: Option<u32>, |
| 24 | } |
| 25 | |
| 26 | #[derive(Debug, Clone, Default, PartialEq)] |
| 27 | pub struct SendRequest { |
| 28 | pub source_id: Option<i64>, |
| 29 | pub sequence: Option<i64>, |
| 30 | pub limits: Vec<SendLimit>, |
| 31 | pub shape: String, |
| 32 | } |
| 33 | |
| 34 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 35 | pub struct EncoderLimits { |
| 36 | pub scale_down_by: f64, |
| 37 | pub max_framerate: Option<f64>, |
| 38 | pub max_bitrate: Option<u64>, |
| 39 | } |
| 40 | |
| 41 | fn text_of(value: &Value) -> Option<String> { |
| 42 | match value { |
| 43 | Value::String(text) => Some(text.clone()), |
| 44 | Value::Number(number) => Some(number.to_string()), |
| 45 | Value::Bool(flag) => Some(u8::from(*flag).to_string()), |
| 46 | _ => None, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn pairs(value: &Value) -> BTreeMap<String, String> { |
| 51 | match value { |
| 52 | Value::String(text) => text |
| 53 | .split(';') |
| 54 | .filter_map(|pair| pair.split_once('=')) |
| 55 | .map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned())) |
| 56 | .collect(), |
| 57 | Value::Object(map) => map.iter().filter_map(|(key, value)| Some((key.clone(), text_of(value)?))).collect(), |
| 58 | _ => BTreeMap::new(), |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn limit_from(parameters: &BTreeMap<String, String>) -> SendLimit { |
| 63 | let number = |key: &str| parameters.get(key).and_then(|value| value.parse::<f64>().ok()); |
| 64 | SendLimit { |
| 65 | max_fs: number("max-fs").map(|value| value as u32), |
| 66 | max_mbps: number("max-mbps").map(|value| value as u32), |
| 67 | max_fps: number("max-fps").map(|value| value / FPS_UNIT), |
| 68 | max_bitrate: number("max-br").map(|value| value as u64 * BITRATE_UNIT), |
| 69 | keyframe: number("KeyFrame").is_some_and(|value| value != 0.0), |
| 70 | rid: parameters.get("rid").cloned(), |
| 71 | ssrc: parameters.get("ssrc").and_then(|value| value.parse().ok()), |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn describe(parameters: &BTreeMap<String, String>) -> String { |
| 76 | parameters |
| 77 | .iter() |
| 78 | .map(|(key, value)| if KNOWN_KEYS.contains(&key.as_str()) { format!("{key}={value}") } else { key.clone() }) |
| 79 | .collect::<Vec<_>>() |
| 80 | .join(";") |
| 81 | } |
| 82 | |
| 83 | pub fn parse_request(body: &Value) -> Option<SendRequest> { |
| 84 | let control = body.get("controlVideoStreaming").unwrap_or(body); |
| 85 | let info = match &control["controlInfo"] { |
| 86 | Value::Array(items) => items.first()?, |
| 87 | Value::Object(_) => &control["controlInfo"], |
| 88 | _ => return None, |
| 89 | }; |
| 90 | let layers: Vec<BTreeMap<String, String>> = match (&info["fmtParamsList"], &info["fmtParams"]) { |
| 91 | (Value::Array(list), _) => list.iter().map(pairs).collect(), |
| 92 | (_, Value::Array(list)) => list.iter().map(pairs).collect(), |
| 93 | (_, single) if !single.is_null() => vec![pairs(single)], |
| 94 | _ => Vec::new(), |
| 95 | }; |
| 96 | let mut fields: Vec<&str> = info.as_object().map(|map| map.keys().map(String::as_str).collect()).unwrap_or_default(); |
| 97 | fields.sort_unstable(); |
| 98 | let shape = format!( |
| 99 | "seq {} source {} control {} fields [{}] layers [{}]", |
| 100 | control["sequenceNumber"], |
| 101 | info["sourceId"], |
| 102 | info["control"].as_str().unwrap_or("-"), |
| 103 | fields.join(","), |
| 104 | layers.iter().map(describe).collect::<Vec<_>>().join(" | ") |
| 105 | ); |
| 106 | let layer_sequence = layers.iter().find_map(|layer| layer.get("sequence-number")?.parse().ok()); |
| 107 | Some(SendRequest { |
| 108 | source_id: info["sourceId"].as_i64(), |
| 109 | sequence: layer_sequence.or_else(|| control["sequenceNumber"].as_i64()), |
| 110 | limits: layers.iter().map(limit_from).collect(), |
| 111 | shape, |
| 112 | }) |
| 113 | } |
| 114 | |
| 115 | /// Drops requests older than the last one per source and repeats that change nothing and ask for no keyframe. |
| 116 | #[derive(Debug, Default)] |
| 117 | pub struct RequestFilter { |
| 118 | last_sequence: HashMap<Option<i64>, i64>, |
| 119 | last_limits: HashMap<Option<i64>, Vec<SendLimit>>, |
| 120 | } |
| 121 | |
| 122 | impl RequestFilter { |
| 123 | pub fn admit(&mut self, request: &SendRequest) -> Option<Vec<SendLimit>> { |
| 124 | if request.limits.is_empty() { |
| 125 | return None; |
| 126 | } |
| 127 | if let Some(sequence) = request.sequence { |
| 128 | let last = self.last_sequence.entry(request.source_id).or_insert(i64::MIN); |
| 129 | if sequence < *last { |
| 130 | return None; |
| 131 | } |
| 132 | *last = sequence; |
| 133 | } |
| 134 | let unchanged = self.last_limits.get(&request.source_id) == Some(&request.limits); |
| 135 | self.last_limits.insert(request.source_id, request.limits.clone()); |
| 136 | let keyframe = request.limits.iter().any(|limit| limit.keyframe); |
| 137 | (!unchanged || keyframe).then(|| request.limits.clone()) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | fn macroblocks(width: f64, height: f64) -> u32 { |
| 142 | ((width / f64::from(MACROBLOCK)).ceil() * (height / f64::from(MACROBLOCK)).ceil()) as u32 |
| 143 | } |
| 144 | |
| 145 | pub fn scale_for(width: u32, height: u32, max_fs: u32) -> f64 { |
| 146 | let (width, height) = (f64::from(width), f64::from(height)); |
| 147 | if max_fs == 0 || macroblocks(width, height) <= max_fs { |
| 148 | return 1.0; |
| 149 | } |
| 150 | let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt(); |
| 151 | while macroblocks(width / scale, height / scale) > max_fs && scale < MAX_SCALE { |
| 152 | scale *= SCALE_STEP; |
| 153 | } |
| 154 | scale |
| 155 | } |
| 156 | |
| 157 | pub fn encoder_limits(limit: &SendLimit, frame: Option<(u32, u32)>) -> EncoderLimits { |
| 158 | let scale_down_by = match (limit.max_fs, frame) { |
| 159 | (Some(max_fs), Some((width, height))) => scale_for(width, height, max_fs), |
| 160 | _ => 1.0, |
| 161 | }; |
| 162 | let rate_by_mbps = match (limit.max_mbps, frame) { |
| 163 | (Some(max_mbps), Some((width, height))) if max_mbps > 0 => { |
| 164 | let blocks = macroblocks(f64::from(width) / scale_down_by, f64::from(height) / scale_down_by).max(1); |
| 165 | Some(f64::from(max_mbps) / f64::from(blocks)) |
| 166 | } |
| 167 | _ => None, |
| 168 | }; |
| 169 | let max_framerate = match (limit.max_fps, rate_by_mbps) { |
| 170 | (Some(fps), Some(by_mbps)) => Some(fps.min(by_mbps)), |
| 171 | (fps, by_mbps) => fps.or(by_mbps), |
| 172 | } |
| 173 | .filter(|fps| *fps > 0.0) |
| 174 | .map(|fps| fps.max(1.0)); |
| 175 | EncoderLimits { scale_down_by, max_framerate, max_bitrate: limit.max_bitrate.filter(|bitrate| *bitrate > 0) } |
| 176 | } |
| 177 | |
| 178 | #[derive(Debug, Clone, PartialEq)] |
| 179 | pub struct LayerPlan { |
| 180 | pub rid: String, |
| 181 | pub active: bool, |
| 182 | pub limits: Option<EncoderLimits>, |
| 183 | pub keyframe: bool, |
| 184 | } |
| 185 | |
| 186 | pub fn plan_layers(limits: &[SendLimit], frame: Option<(u32, u32)>, rids: &[String]) -> Vec<LayerPlan> { |
| 187 | let encoding_of = |limit: &SendLimit| { |
| 188 | limit.rid.as_ref().and_then(|rid| rids.iter().position(|candidate| candidate == rid)).unwrap_or(0) |
| 189 | }; |
| 190 | rids.iter() |
| 191 | .enumerate() |
| 192 | .map(|(index, rid)| { |
| 193 | let requested = limits.iter().find(|limit| encoding_of(limit) == index); |
| 194 | LayerPlan { |
| 195 | rid: rid.clone(), |
| 196 | active: requested.is_some(), |
| 197 | limits: requested.map(|limit| encoder_limits(limit, frame)), |
| 198 | keyframe: requested.is_some_and(|limit| limit.keyframe), |
| 199 | } |
| 200 | }) |
| 201 | .collect() |
| 202 | } |
| 203 | |
| 204 | pub fn capture_macroblocks(width: u32, height: u32) -> u32 { |
| 205 | macroblocks(f64::from(width), f64::from(height)) |
| 206 | } |
| 207 | |
| 208 | #[cfg(test)] |
| 209 | mod tests { |
| 210 | use serde_json::json; |
| 211 | |
| 212 | use super::*; |
| 213 | |
| 214 | #[test] |
| 215 | fn a_signaling_request_with_a_string_fmtp_is_read() { |
| 216 | let body = json!({"controlVideoStreaming": {"sequenceNumber": 12, "controlInfo": [ |
| 217 | {"control": "start", "sourceId": 405, "streamMsid": 3, "fmtParams": "max-fs=920;max-mbps=27600;max-fps=3000;KeyFrame=1;x-secret=abc"} |
| 218 | ]}}); |
| 219 | let request = parse_request(&body).unwrap(); |
| 220 | assert_eq!(request.source_id, Some(405)); |
| 221 | assert_eq!(request.sequence, Some(12)); |
| 222 | assert_eq!(request.limits, vec![SendLimit { max_fs: Some(920), max_mbps: Some(27600), max_fps: Some(30.0), max_bitrate: None, keyframe: true, rid: None, ssrc: None }]); |
| 223 | assert_eq!( |
| 224 | request.shape, |
| 225 | "seq 12 source 405 control start fields [control,fmtParams,sourceId,streamMsid] layers [KeyFrame=1;max-fps=3000;max-fs=920;max-mbps=27600;x-secret]" |
| 226 | ); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn lists_objects_and_a_bare_control_info_are_read_too() { |
| 231 | let listed = json!({"controlVideoStreaming": {"sequenceNumber": 1, "controlInfo": [ |
| 232 | {"sourceId": 405, "fmtParamsList": ["max-fs=3600;max-br=1500", "max-fs=920"]} |
| 233 | ]}}); |
| 234 | let request = parse_request(&listed).unwrap(); |
| 235 | assert_eq!(request.limits.len(), 2); |
| 236 | assert_eq!(request.limits[0].max_bitrate, Some(1_800_000)); |
| 237 | let objects = json!({"sequenceNumber": 2, "controlInfo": {"sourceId": 415, "fmtParams": [{"max-fs": 8160, "max-fps": 1500}]}}); |
| 238 | let request = parse_request(&objects).unwrap(); |
| 239 | assert_eq!(request.source_id, Some(415)); |
| 240 | assert_eq!(request.limits[0].max_fs, Some(8160)); |
| 241 | assert_eq!(request.limits[0].max_fps, Some(15.0)); |
| 242 | assert!(parse_request(&json!({"other": 1})).is_none()); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn stale_and_repeated_requests_are_dropped_unless_a_keyframe_is_asked() { |
| 247 | let request = |sequence: i64, fmtp: &str| { |
| 248 | parse_request(&json!({"sequenceNumber": sequence, "controlInfo": [{"sourceId": 405, "fmtParams": fmtp}]})).unwrap() |
| 249 | }; |
| 250 | let mut filter = RequestFilter::default(); |
| 251 | assert!(filter.admit(&request(5, "max-fs=920")).is_some()); |
| 252 | assert!(filter.admit(&request(6, "max-fs=920")).is_none()); |
| 253 | assert!(filter.admit(&request(4, "max-fs=3600")).is_none()); |
| 254 | assert!(filter.admit(&request(7, "max-fs=920;KeyFrame=1")).is_some()); |
| 255 | assert_eq!(filter.admit(&request(8, "max-fs=3600")).unwrap()[0].max_fs, Some(3600)); |
| 256 | } |
| 257 | |
| 258 | #[test] |
| 259 | fn the_scale_fits_the_frame_into_max_fs() { |
| 260 | assert_eq!(scale_for(1280, 720, 3600), 1.0); |
| 261 | let scale = scale_for(1280, 720, 920); |
| 262 | assert!(macroblocks(1280.0 / scale, 720.0 / scale) <= 920); |
| 263 | assert!(scale < 2.2, "{scale}"); |
| 264 | let scale = scale_for(960, 720, 920); |
| 265 | assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920); |
| 266 | assert_eq!(scale_for(1280, 720, 0), 1.0); |
| 267 | let screen = scale_for(1920, 1200, 8160); |
| 268 | assert!(screen > 1.0 && macroblocks(1920.0 / screen, 1200.0 / screen) <= 8160, "{screen}"); |
| 269 | } |
| 270 | |
| 271 | #[test] |
| 272 | fn frame_rate_follows_max_fps_and_max_mbps() { |
| 273 | let limit = SendLimit { max_fs: Some(920), max_mbps: Some(13_800), max_fps: Some(30.0), max_bitrate: Some(600_000), keyframe: false, ..SendLimit::default() }; |
| 274 | let limits = encoder_limits(&limit, Some((1280, 720))); |
| 275 | assert!(limits.scale_down_by > 1.0); |
| 276 | assert!(limits.max_framerate.unwrap() <= 30.0 && limits.max_framerate.unwrap() >= 14.0); |
| 277 | assert_eq!(limits.max_bitrate, Some(600_000)); |
| 278 | let unknown_frame = encoder_limits(&limit, None); |
| 279 | assert_eq!(unknown_frame.scale_down_by, 1.0); |
| 280 | assert_eq!(unknown_frame.max_framerate, Some(30.0)); |
| 281 | } |
| 282 | |
| 283 | fn simulcast_request(sequence: i64, fmtp: [&str; 3]) -> SendRequest { |
| 284 | parse_request(&json!({"sequenceNumber": sequence, "controlInfo": [{"sourceId": 405, "fmtParamsList": fmtp}]})).unwrap() |
| 285 | } |
| 286 | |
| 287 | const THREE_LAYERS: [&str; 3] = [ |
| 288 | "max-fs=405;max-fps=3000;max-br=250;rid=1;ssrc=1111", |
| 289 | "max-fs=920;max-fps=3000;max-br=500;rid=2;ssrc=1112", |
| 290 | "max-fs=3600;max-fps=3000;max-br=1500;rid=3;ssrc=1113;KeyFrame=0", |
| 291 | ]; |
| 292 | |
| 293 | fn rids() -> Vec<String> { |
| 294 | ["1", "2", "3"].map(String::from).to_vec() |
| 295 | } |
| 296 | |
| 297 | #[test] |
| 298 | fn three_layers_keep_their_rid_ssrc_and_limits() { |
| 299 | let request = simulcast_request(1, THREE_LAYERS); |
| 300 | let seen: Vec<(Option<&str>, Option<u32>, Option<u32>)> = |
| 301 | request.limits.iter().map(|limit| (limit.rid.as_deref(), limit.ssrc, limit.max_fs)).collect(); |
| 302 | assert_eq!(seen, vec![(Some("1"), Some(1111), Some(405)), (Some("2"), Some(1112), Some(920)), (Some("3"), Some(1113), Some(3600))]); |
| 303 | assert_eq!(request.limits[2].max_bitrate, Some(1_800_000)); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn a_missing_rid_switches_that_layer_off() { |
| 308 | let request = simulcast_request(1, THREE_LAYERS); |
| 309 | let limits: Vec<SendLimit> = request.limits.into_iter().filter(|limit| limit.rid.as_deref() != Some("2")).collect(); |
| 310 | let plans = plan_layers(&limits, Some((1280, 720)), &rids()); |
| 311 | assert_eq!(plans.iter().map(|plan| plan.active).collect::<Vec<_>>(), vec![true, false, true]); |
| 312 | assert!(plans[1].limits.is_none()); |
| 313 | assert!(plans[0].limits.unwrap().scale_down_by > plans[2].limits.unwrap().scale_down_by); |
| 314 | assert_eq!(plans[2].limits.unwrap().scale_down_by, 1.0); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn an_entry_without_rid_drives_the_first_encoding() { |
| 319 | let limits = [SendLimit { max_fs: Some(920), ..SendLimit::default() }]; |
| 320 | let plans = plan_layers(&limits, Some((1280, 720)), &rids()); |
| 321 | assert_eq!(plans.iter().map(|plan| plan.active).collect::<Vec<_>>(), vec![true, false, false]); |
| 322 | assert!(plans[0].limits.unwrap().scale_down_by > 1.0); |
| 323 | } |
| 324 | |
| 325 | #[test] |
| 326 | fn the_keyframe_flag_stays_on_its_rid() { |
| 327 | let mut limits = simulcast_request(1, THREE_LAYERS).limits; |
| 328 | limits[1].keyframe = true; |
| 329 | let plans = plan_layers(&limits, Some((1280, 720)), &rids()); |
| 330 | assert_eq!(plans.iter().map(|plan| plan.keyframe).collect::<Vec<_>>(), vec![false, true, false]); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn the_filter_compares_the_whole_layer_set() { |
| 335 | let mut filter = RequestFilter::default(); |
| 336 | assert_eq!(filter.admit(&simulcast_request(1, THREE_LAYERS)).unwrap().len(), 3); |
| 337 | assert!(filter.admit(&simulcast_request(2, THREE_LAYERS)).is_none()); |
| 338 | let mut changed = THREE_LAYERS; |
| 339 | changed[1] = "max-fs=405;max-fps=3000;max-br=250;rid=2;ssrc=1112"; |
| 340 | assert!(filter.admit(&simulcast_request(3, changed)).is_some()); |
| 341 | assert!(filter.admit(&simulcast_request(4, changed)).is_none()); |
| 342 | let mut keyframe = changed; |
| 343 | keyframe[2] = "max-fs=3600;max-fps=3000;max-br=1500;rid=3;ssrc=1113;KeyFrame=1"; |
| 344 | assert!(filter.admit(&simulcast_request(5, keyframe)).is_some()); |
| 345 | } |
| 346 | } |