| 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 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, Default, PartialEq)] |
| 25 | pub struct SendRequest { |
| 26 | pub source_id: Option<i64>, |
| 27 | pub sequence: Option<i64>, |
| 28 | pub limits: Vec<SendLimit>, |
| 29 | pub shape: String, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 33 | pub struct EncoderLimits { |
| 34 | pub scale_down_by: f64, |
| 35 | pub max_framerate: Option<f64>, |
| 36 | pub max_bitrate: Option<u64>, |
| 37 | } |
| 38 | |
| 39 | fn text_of(value: &Value) -> Option<String> { |
| 40 | match value { |
| 41 | Value::String(text) => Some(text.clone()), |
| 42 | Value::Number(number) => Some(number.to_string()), |
| 43 | Value::Bool(flag) => Some(u8::from(*flag).to_string()), |
| 44 | _ => None, |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | fn pairs(value: &Value) -> BTreeMap<String, String> { |
| 49 | match value { |
| 50 | Value::String(text) => text |
| 51 | .split(';') |
| 52 | .filter_map(|pair| pair.split_once('=')) |
| 53 | .map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned())) |
| 54 | .collect(), |
| 55 | Value::Object(map) => map.iter().filter_map(|(key, value)| Some((key.clone(), text_of(value)?))).collect(), |
| 56 | _ => BTreeMap::new(), |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | fn limit_from(parameters: &BTreeMap<String, String>) -> SendLimit { |
| 61 | let number = |key: &str| parameters.get(key).and_then(|value| value.parse::<f64>().ok()); |
| 62 | SendLimit { |
| 63 | max_fs: number("max-fs").map(|value| value as u32), |
| 64 | max_mbps: number("max-mbps").map(|value| value as u32), |
| 65 | max_fps: number("max-fps").map(|value| value / FPS_UNIT), |
| 66 | max_bitrate: number("max-br").map(|value| value as u64 * BITRATE_UNIT), |
| 67 | keyframe: number("KeyFrame").is_some_and(|value| value != 0.0), |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn describe(parameters: &BTreeMap<String, String>) -> String { |
| 72 | parameters |
| 73 | .iter() |
| 74 | .map(|(key, value)| if KNOWN_KEYS.contains(&key.as_str()) { format!("{key}={value}") } else { key.clone() }) |
| 75 | .collect::<Vec<_>>() |
| 76 | .join(";") |
| 77 | } |
| 78 | |
| 79 | pub fn parse_request(body: &Value) -> Option<SendRequest> { |
| 80 | let control = body.get("controlVideoStreaming").unwrap_or(body); |
| 81 | let info = match &control["controlInfo"] { |
| 82 | Value::Array(items) => items.first()?, |
| 83 | Value::Object(_) => &control["controlInfo"], |
| 84 | _ => return None, |
| 85 | }; |
| 86 | let layers: Vec<BTreeMap<String, String>> = match (&info["fmtParamsList"], &info["fmtParams"]) { |
| 87 | (Value::Array(list), _) => list.iter().map(pairs).collect(), |
| 88 | (_, Value::Array(list)) => list.iter().map(pairs).collect(), |
| 89 | (_, single) if !single.is_null() => vec![pairs(single)], |
| 90 | _ => Vec::new(), |
| 91 | }; |
| 92 | let mut fields: Vec<&str> = info.as_object().map(|map| map.keys().map(String::as_str).collect()).unwrap_or_default(); |
| 93 | fields.sort_unstable(); |
| 94 | let shape = format!( |
| 95 | "seq {} source {} control {} fields [{}] layers [{}]", |
| 96 | control["sequenceNumber"], |
| 97 | info["sourceId"], |
| 98 | info["control"].as_str().unwrap_or("-"), |
| 99 | fields.join(","), |
| 100 | layers.iter().map(describe).collect::<Vec<_>>().join(" | ") |
| 101 | ); |
| 102 | let layer_sequence = layers.iter().find_map(|layer| layer.get("sequence-number")?.parse().ok()); |
| 103 | Some(SendRequest { |
| 104 | source_id: info["sourceId"].as_i64(), |
| 105 | sequence: layer_sequence.or_else(|| control["sequenceNumber"].as_i64()), |
| 106 | limits: layers.iter().map(limit_from).collect(), |
| 107 | shape, |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | /// Drops requests older than the last one per source and repeats that change nothing and ask for no keyframe. |
| 112 | #[derive(Debug, Default)] |
| 113 | pub struct RequestFilter { |
| 114 | last_sequence: HashMap<Option<i64>, i64>, |
| 115 | last_limit: HashMap<Option<i64>, SendLimit>, |
| 116 | } |
| 117 | |
| 118 | impl RequestFilter { |
| 119 | pub fn admit(&mut self, request: &SendRequest) -> Option<SendLimit> { |
| 120 | let limit = request.limits.first()?.clone(); |
| 121 | if let Some(sequence) = request.sequence { |
| 122 | let last = self.last_sequence.entry(request.source_id).or_insert(i64::MIN); |
| 123 | if sequence < *last { |
| 124 | return None; |
| 125 | } |
| 126 | *last = sequence; |
| 127 | } |
| 128 | let unchanged = self.last_limit.get(&request.source_id) == Some(&limit); |
| 129 | self.last_limit.insert(request.source_id, limit.clone()); |
| 130 | (!unchanged || limit.keyframe).then_some(limit) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn macroblocks(width: f64, height: f64) -> u32 { |
| 135 | ((width / f64::from(MACROBLOCK)).ceil() * (height / f64::from(MACROBLOCK)).ceil()) as u32 |
| 136 | } |
| 137 | |
| 138 | pub fn scale_for(width: u32, height: u32, max_fs: u32) -> f64 { |
| 139 | let (width, height) = (f64::from(width), f64::from(height)); |
| 140 | if max_fs == 0 || macroblocks(width, height) <= max_fs { |
| 141 | return 1.0; |
| 142 | } |
| 143 | let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt(); |
| 144 | while macroblocks(width / scale, height / scale) > max_fs && scale < MAX_SCALE { |
| 145 | scale *= SCALE_STEP; |
| 146 | } |
| 147 | scale |
| 148 | } |
| 149 | |
| 150 | pub fn encoder_limits(limit: &SendLimit, frame: Option<(u32, u32)>) -> EncoderLimits { |
| 151 | let scale_down_by = match (limit.max_fs, frame) { |
| 152 | (Some(max_fs), Some((width, height))) => scale_for(width, height, max_fs), |
| 153 | _ => 1.0, |
| 154 | }; |
| 155 | let rate_by_mbps = match (limit.max_mbps, frame) { |
| 156 | (Some(max_mbps), Some((width, height))) if max_mbps > 0 => { |
| 157 | let blocks = macroblocks(f64::from(width) / scale_down_by, f64::from(height) / scale_down_by).max(1); |
| 158 | Some(f64::from(max_mbps) / f64::from(blocks)) |
| 159 | } |
| 160 | _ => None, |
| 161 | }; |
| 162 | let max_framerate = match (limit.max_fps, rate_by_mbps) { |
| 163 | (Some(fps), Some(by_mbps)) => Some(fps.min(by_mbps)), |
| 164 | (fps, by_mbps) => fps.or(by_mbps), |
| 165 | } |
| 166 | .filter(|fps| *fps > 0.0) |
| 167 | .map(|fps| fps.max(1.0)); |
| 168 | EncoderLimits { scale_down_by, max_framerate, max_bitrate: limit.max_bitrate.filter(|bitrate| *bitrate > 0) } |
| 169 | } |
| 170 | |
| 171 | #[cfg(test)] |
| 172 | mod tests { |
| 173 | use serde_json::json; |
| 174 | |
| 175 | use super::*; |
| 176 | |
| 177 | #[test] |
| 178 | fn a_signaling_request_with_a_string_fmtp_is_read() { |
| 179 | let body = json!({"controlVideoStreaming": {"sequenceNumber": 12, "controlInfo": [ |
| 180 | {"control": "start", "sourceId": 405, "streamMsid": 3, "fmtParams": "max-fs=920;max-mbps=27600;max-fps=3000;KeyFrame=1;x-secret=abc"} |
| 181 | ]}}); |
| 182 | let request = parse_request(&body).unwrap(); |
| 183 | assert_eq!(request.source_id, Some(405)); |
| 184 | assert_eq!(request.sequence, Some(12)); |
| 185 | assert_eq!(request.limits, vec![SendLimit { max_fs: Some(920), max_mbps: Some(27600), max_fps: Some(30.0), max_bitrate: None, keyframe: true }]); |
| 186 | assert_eq!( |
| 187 | request.shape, |
| 188 | "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]" |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn lists_objects_and_a_bare_control_info_are_read_too() { |
| 194 | let listed = json!({"controlVideoStreaming": {"sequenceNumber": 1, "controlInfo": [ |
| 195 | {"sourceId": 405, "fmtParamsList": ["max-fs=3600;max-br=1500", "max-fs=920"]} |
| 196 | ]}}); |
| 197 | let request = parse_request(&listed).unwrap(); |
| 198 | assert_eq!(request.limits.len(), 2); |
| 199 | assert_eq!(request.limits[0].max_bitrate, Some(1_800_000)); |
| 200 | let objects = json!({"sequenceNumber": 2, "controlInfo": {"sourceId": 415, "fmtParams": [{"max-fs": 8160, "max-fps": 1500}]}}); |
| 201 | let request = parse_request(&objects).unwrap(); |
| 202 | assert_eq!(request.source_id, Some(415)); |
| 203 | assert_eq!(request.limits[0].max_fs, Some(8160)); |
| 204 | assert_eq!(request.limits[0].max_fps, Some(15.0)); |
| 205 | assert!(parse_request(&json!({"other": 1})).is_none()); |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn stale_and_repeated_requests_are_dropped_unless_a_keyframe_is_asked() { |
| 210 | let request = |sequence: i64, fmtp: &str| { |
| 211 | parse_request(&json!({"sequenceNumber": sequence, "controlInfo": [{"sourceId": 405, "fmtParams": fmtp}]})).unwrap() |
| 212 | }; |
| 213 | let mut filter = RequestFilter::default(); |
| 214 | assert!(filter.admit(&request(5, "max-fs=920")).is_some()); |
| 215 | assert!(filter.admit(&request(6, "max-fs=920")).is_none()); |
| 216 | assert!(filter.admit(&request(4, "max-fs=3600")).is_none()); |
| 217 | assert!(filter.admit(&request(7, "max-fs=920;KeyFrame=1")).is_some()); |
| 218 | assert_eq!(filter.admit(&request(8, "max-fs=3600")).unwrap().max_fs, Some(3600)); |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn the_scale_fits_the_frame_into_max_fs() { |
| 223 | assert_eq!(scale_for(1280, 720, 3600), 1.0); |
| 224 | let scale = scale_for(1280, 720, 920); |
| 225 | assert!(macroblocks(1280.0 / scale, 720.0 / scale) <= 920); |
| 226 | assert!(scale < 2.2, "{scale}"); |
| 227 | let scale = scale_for(960, 720, 920); |
| 228 | assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920); |
| 229 | assert_eq!(scale_for(1280, 720, 0), 1.0); |
| 230 | } |
| 231 | |
| 232 | #[test] |
| 233 | fn frame_rate_follows_max_fps_and_max_mbps() { |
| 234 | let limit = SendLimit { max_fs: Some(920), max_mbps: Some(13_800), max_fps: Some(30.0), max_bitrate: Some(600_000), keyframe: false }; |
| 235 | let limits = encoder_limits(&limit, Some((1280, 720))); |
| 236 | assert!(limits.scale_down_by > 1.0); |
| 237 | assert!(limits.max_framerate.unwrap() <= 30.0 && limits.max_framerate.unwrap() >= 14.0); |
| 238 | assert_eq!(limits.max_bitrate, Some(600_000)); |
| 239 | let unknown_frame = encoder_limits(&limit, None); |
| 240 | assert_eq!(unknown_frame.scale_down_by, 1.0); |
| 241 | assert_eq!(unknown_frame.max_framerate, Some(30.0)); |
| 242 | } |
| 243 | } |