BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / segmentation / mod.rs

mod.rs

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