| 1 | #[cfg(windows)] |
| 2 | mod embedded; |
| 3 | pub mod model; |
| 4 | pub mod runtime; |
| 5 | |
| 6 | use std::collections::VecDeque; |
| 7 | use std::thread::JoinHandle; |
| 8 | use std::time::{Duration, Instant}; |
| 9 | |
| 10 | use libwebrtc::video_frame::I420Buffer; |
| 11 | |
| 12 | use crate::blur::MaskInference; |
| 13 | use crate::error::{Error, Result}; |
| 14 | use crate::mask::Mask; |
| 15 | use model::{MEDIAPIPE, MODNET_LARGE, MODNET_SMALL, ModelSpec}; |
| 16 | use runtime::{Device, Runner}; |
| 17 | |
| 18 | const BUDGET: Duration = Duration::from_millis(35); |
| 19 | const BEHIND: Duration = Duration::from_millis(45); |
| 20 | const PROBE_AFTER: u32 = 15; |
| 21 | const PROBE_RUNS: usize = 5; |
| 22 | const TIMING_WINDOW: usize = 20; |
| 23 | const MODNET_CPU_THREADS: usize = 4; |
| 24 | |
| 25 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 26 | pub struct Rung { |
| 27 | pub spec: ModelSpec, |
| 28 | pub device: Device, |
| 29 | } |
| 30 | |
| 31 | pub fn rungs(onnx_runtime: bool, gpu: bool, on_battery: bool) -> Vec<Rung> { |
| 32 | let mut rungs = vec![Rung { spec: MEDIAPIPE, device: Device::Cpu { threads: 1 } }]; |
| 33 | if on_battery || !onnx_runtime { |
| 34 | return rungs; |
| 35 | } |
| 36 | if gpu { |
| 37 | rungs.push(Rung { spec: MODNET_SMALL, device: Device::Gpu }); |
| 38 | rungs.push(Rung { spec: MODNET_LARGE, device: Device::Gpu }); |
| 39 | } else { |
| 40 | rungs.push(Rung { spec: MODNET_SMALL, device: Device::Cpu { threads: MODNET_CPU_THREADS } }); |
| 41 | } |
| 42 | rungs |
| 43 | } |
| 44 | |
| 45 | fn median(timings: impl Iterator<Item = Duration>) -> Duration { |
| 46 | let mut sorted: Vec<Duration> = timings.collect(); |
| 47 | sorted.sort(); |
| 48 | sorted.get(sorted.len() / 2).copied().unwrap_or_default() |
| 49 | } |
| 50 | |
| 51 | type Probe = JoinHandle<Option<(Box<dyn Runner>, Duration)>>; |
| 52 | |
| 53 | fn probe(rung: Rung, input: Vec<f32>) -> Probe { |
| 54 | std::thread::spawn(move || { |
| 55 | let mut runner = runtime::runner(&rung.spec, rung.device).ok()?; |
| 56 | runner.run(input.clone()).ok()?; |
| 57 | let mut timings = Vec::with_capacity(PROBE_RUNS); |
| 58 | for _ in 0..PROBE_RUNS { |
| 59 | let started = Instant::now(); |
| 60 | runner.run(input.clone()).ok()?; |
| 61 | timings.push(started.elapsed()); |
| 62 | } |
| 63 | Some((runner, median(timings.into_iter()))) |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | pub struct FixedSegmenter { |
| 68 | spec: ModelSpec, |
| 69 | runner: Box<dyn Runner>, |
| 70 | } |
| 71 | |
| 72 | impl FixedSegmenter { |
| 73 | pub fn new(spec: ModelSpec, device: Device) -> Result<Self> { |
| 74 | let runner = runtime::runner(&spec, device).map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?; |
| 75 | Ok(FixedSegmenter { spec, runner }) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | impl MaskInference for FixedSegmenter { |
| 80 | fn infer(&mut self, mut frame: I420Buffer) -> Result<Mask> { |
| 81 | let output = self.runner.run(self.spec.input(&mut frame)).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?; |
| 82 | self.spec.mask(&output).ok_or_else(|| Error::Webrtc(format!("segmentation output has {} values", output.len()))) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | pub struct LadderSegmenter { |
| 87 | rungs: Vec<Rung>, |
| 88 | runners: Vec<Option<Box<dyn Runner>>>, |
| 89 | active: usize, |
| 90 | next_probe: usize, |
| 91 | probe: Option<(usize, Probe)>, |
| 92 | served: u32, |
| 93 | timings: VecDeque<Duration>, |
| 94 | } |
| 95 | |
| 96 | impl LadderSegmenter { |
| 97 | pub fn new() -> Result<Self> { |
| 98 | Self::with_rungs(rungs(runtime::environment().is_some(), runtime::gpu_available(), on_battery())) |
| 99 | } |
| 100 | |
| 101 | pub fn with_rungs(rungs: Vec<Rung>) -> Result<Self> { |
| 102 | let first = rungs.first().ok_or_else(|| Error::Webrtc("segmentation: no model".into()))?; |
| 103 | let runner = runtime::runner(&first.spec, first.device).map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?; |
| 104 | let mut runners: Vec<Option<Box<dyn Runner>>> = rungs.iter().map(|_| None).collect(); |
| 105 | runners[0] = Some(runner); |
| 106 | Ok(LadderSegmenter { next_probe: 1, rungs, runners, active: 0, probe: None, served: 0, timings: VecDeque::new() }) |
| 107 | } |
| 108 | |
| 109 | pub fn active(&self) -> ModelSpec { |
| 110 | self.rungs[self.active].spec |
| 111 | } |
| 112 | |
| 113 | fn adopt_probe(&mut self) { |
| 114 | let Some((rung, handle)) = self.probe.take_if(|(_, handle)| handle.is_finished()) else { return }; |
| 115 | match handle.join().ok().flatten() { |
| 116 | Some((runner, typical)) if typical <= BUDGET => { |
| 117 | self.runners[rung] = Some(runner); |
| 118 | self.active = rung; |
| 119 | self.timings.clear(); |
| 120 | self.served = 0; |
| 121 | self.next_probe = rung + 1; |
| 122 | } |
| 123 | _ => self.next_probe = self.rungs.len(), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | fn start_probe(&mut self, frame: &mut I420Buffer) { |
| 128 | if self.probe.is_some() || self.served < PROBE_AFTER || self.next_probe >= self.rungs.len() { |
| 129 | return; |
| 130 | } |
| 131 | let rung = self.rungs[self.next_probe]; |
| 132 | self.probe = Some((self.next_probe, probe(rung, rung.spec.input(frame)))); |
| 133 | } |
| 134 | |
| 135 | fn record(&mut self, elapsed: Duration) { |
| 136 | self.timings.push_back(elapsed); |
| 137 | if self.timings.len() > TIMING_WINDOW { |
| 138 | self.timings.pop_front(); |
| 139 | } |
| 140 | let behind = self.timings.len() == TIMING_WINDOW && median(self.timings.iter().copied()) > BEHIND; |
| 141 | if behind && self.active > 0 { |
| 142 | self.runners[self.active] = None; |
| 143 | self.active -= 1; |
| 144 | self.next_probe = self.rungs.len(); |
| 145 | self.timings.clear(); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | impl MaskInference for LadderSegmenter { |
| 151 | fn infer(&mut self, mut frame: I420Buffer) -> Result<Mask> { |
| 152 | self.adopt_probe(); |
| 153 | self.start_probe(&mut frame); |
| 154 | let spec = self.rungs[self.active].spec; |
| 155 | let input = spec.input(&mut frame); |
| 156 | let runner = self.runners[self.active].as_mut().ok_or_else(|| Error::Webrtc("segmentation: runner missing".into()))?; |
| 157 | let started = Instant::now(); |
| 158 | let output = runner.run(input).map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?; |
| 159 | let elapsed = started.elapsed(); |
| 160 | self.served += 1; |
| 161 | if self.active > 0 { |
| 162 | self.record(elapsed); |
| 163 | } |
| 164 | spec.mask(&output).ok_or_else(|| Error::Webrtc(format!("segmentation output has {} values", output.len()))) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | #[cfg(windows)] |
| 169 | fn on_battery() -> bool { |
| 170 | use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS}; |
| 171 | let mut status = SYSTEM_POWER_STATUS::default(); |
| 172 | unsafe { GetSystemPowerStatus(&mut status) }.is_ok() && status.ACLineStatus == 0 |
| 173 | } |
| 174 | |
| 175 | #[cfg(not(windows))] |
| 176 | fn on_battery() -> bool { |
| 177 | std::fs::read_dir("/sys/class/power_supply").into_iter().flatten().flatten().any(|supply| { |
| 178 | let read = |name: &str| std::fs::read_to_string(supply.path().join(name)).unwrap_or_default(); |
| 179 | read("type").trim() == "Battery" && read("status").trim() == "Discharging" |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | #[cfg(test)] |
| 184 | mod tests { |
| 185 | use super::*; |
| 186 | use crate::camera::i420_from_rgba; |
| 187 | |
| 188 | struct Fixed(Duration, usize); |
| 189 | |
| 190 | impl Runner for Fixed { |
| 191 | fn run(&mut self, _input: Vec<f32>) -> std::result::Result<Vec<f32>, String> { |
| 192 | std::thread::sleep(self.0); |
| 193 | Ok(vec![0.5; self.1]) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn ladder(times: [Duration; 2]) -> LadderSegmenter { |
| 198 | let rungs = vec![Rung { spec: MEDIAPIPE, device: Device::Cpu { threads: 1 } }, Rung { spec: MODNET_SMALL, device: Device::Cpu { threads: 1 } }]; |
| 199 | let mut ladder = LadderSegmenter::with_rungs(rungs.clone()).expect("mediapipe loads"); |
| 200 | ladder.runners[0] = Some(Box::new(Fixed(times[0], MEDIAPIPE.width * MEDIAPIPE.height))); |
| 201 | ladder.runners[1] = Some(Box::new(Fixed(times[1], MODNET_SMALL.width * MODNET_SMALL.height))); |
| 202 | ladder |
| 203 | } |
| 204 | |
| 205 | fn frame() -> I420Buffer { |
| 206 | i420_from_rgba(&vec![128u8; 64 * 36 * 4], 64, 36) |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn the_ladder_starts_small_and_steps_down_when_the_big_model_falls_behind() { |
| 211 | let mut ladder = ladder([Duration::ZERO, BEHIND + Duration::from_millis(5)]); |
| 212 | assert_eq!(ladder.infer(frame()).unwrap().width, MEDIAPIPE.width); |
| 213 | ladder.active = 1; |
| 214 | ladder.next_probe = 2; |
| 215 | assert_eq!(ladder.infer(frame()).unwrap().width, MODNET_SMALL.width); |
| 216 | for _ in 1..TIMING_WINDOW { |
| 217 | ladder.infer(frame()).unwrap(); |
| 218 | } |
| 219 | assert_eq!(ladder.active(), MEDIAPIPE); |
| 220 | assert!(ladder.runners[1].is_none()); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn a_probe_within_budget_takes_over_and_a_slow_one_ends_the_climb() { |
| 225 | for (typical, climbs) in [(BUDGET / 2, true), (BUDGET * 2, false)] { |
| 226 | let mut ladder = ladder([Duration::ZERO, Duration::ZERO]); |
| 227 | ladder.runners[1] = None; |
| 228 | let handle = std::thread::spawn(move || Some((Box::new(Fixed(Duration::ZERO, MODNET_SMALL.width * MODNET_SMALL.height)) as Box<dyn Runner>, typical))); |
| 229 | while !handle.is_finished() { |
| 230 | std::thread::yield_now(); |
| 231 | } |
| 232 | ladder.probe = Some((1, handle)); |
| 233 | let mask = ladder.infer(frame()).unwrap(); |
| 234 | assert_eq!(mask.width == MODNET_SMALL.width, climbs); |
| 235 | assert_eq!(ladder.next_probe, 2); |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn battery_missing_gpu_and_missing_onnx_runtime_shorten_the_ladder() { |
| 241 | assert_eq!(rungs(true, true, true).len(), 1); |
| 242 | assert_eq!(rungs(false, false, false).len(), 1, "no matting model on tract"); |
| 243 | assert_eq!(rungs(true, false, false).iter().map(|rung| rung.spec).collect::<Vec<_>>(), vec![MEDIAPIPE, MODNET_SMALL]); |
| 244 | assert_eq!(rungs(true, true, false).last().unwrap(), &Rung { spec: MODNET_LARGE, device: Device::Gpu }); |
| 245 | } |
| 246 | |
| 247 | #[test] |
| 248 | fn every_ladder_model_runs_and_answers_one_value_per_cell() { |
| 249 | let onnx_specs = if runtime::environment().is_some() { vec![MEDIAPIPE, MODNET_SMALL] } else { Vec::new() }; |
| 250 | for spec in onnx_specs { |
| 251 | let mut runner = runtime::runner(&spec, Device::Cpu { threads: 2 }).expect("model loads"); |
| 252 | let output = runner.run(spec.input(&mut frame())).expect("inference runs"); |
| 253 | assert!(spec.mask(&output).is_some(), "{}", spec.name); |
| 254 | } |
| 255 | let mut tract = runtime::tract_only(&MEDIAPIPE); |
| 256 | assert_eq!(tract.run(MEDIAPIPE.input(&mut frame())).unwrap().len(), MEDIAPIPE.width * MEDIAPIPE.height); |
| 257 | } |
| 258 | } |