BlueGit

ict rusty-teams

Files

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

mod.rs

mod.rs 12.5 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 {
34 spec: MEDIAPIPE,
35 device: Device::Cpu { threads: 1 },
36 }];
37 if !onnx_runtime {
38 return rungs;
39 }
40 if gpu {
41 // DirectML iGPU runs MODNET_SMALL efficiently even on battery; only skip MODNET_LARGE on battery.
42 rungs.push(Rung {
43 spec: MODNET_SMALL,
44 device: Device::Gpu,
45 });
46 if !on_battery {
47 rungs.push(Rung {
48 spec: MODNET_LARGE,
49 device: Device::Gpu,
50 });
51 }
52 } else if !on_battery {
53 rungs.push(Rung {
54 spec: MODNET_SMALL,
55 device: Device::Cpu {
56 threads: MODNET_CPU_THREADS,
57 },
58 });
59 }
60 rungs
61}
62
63fn budget(device: Device) -> Duration {
64 match device {
65 Device::Gpu => GPU_BUDGET,
66 Device::Cpu { .. } => BUDGET,
67 }
68}
69
70fn median(timings: impl Iterator<Item = Duration>) -> Duration {
71 let mut sorted: Vec<Duration> = timings.collect();
72 sorted.sort();
73 sorted.get(sorted.len() / 2).copied().unwrap_or_default()
74}
75
76type Probe = JoinHandle<Option<(Box<dyn Runner>, Duration)>>;
77
78fn probe(rung: Rung, input: Vec<f32>) -> Probe {
79 std::thread::spawn(move || {
80 let mut runner = runtime::runner(&rung.spec, rung.device).ok()?;
81 runner.run(input.clone()).ok()?;
82 let mut timings = Vec::with_capacity(PROBE_RUNS);
83 for _ in 0..PROBE_RUNS {
84 let started = Instant::now();
85 runner.run(input.clone()).ok()?;
86 timings.push(started.elapsed());
87 }
88 Some((runner, median(timings.into_iter())))
89 })
90}
91
92pub struct FixedSegmenter {
93 spec: ModelSpec,
94 runner: Box<dyn Runner>,
95}
96
97impl FixedSegmenter {
98 pub fn new(spec: ModelSpec, device: Device) -> Result<Self> {
99 let runner = runtime::runner(&spec, device)
100 .map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;
101 Ok(FixedSegmenter { spec, runner })
102 }
103}
104
105impl MaskInference for FixedSegmenter {
106 fn infer(&mut self, mut frame: I420Buffer) -> Result<Mask> {
107 let output = self
108 .runner
109 .run(self.spec.input(&mut frame))
110 .map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;
111 self.spec.mask(&output).ok_or_else(|| {
112 Error::Webrtc(format!("segmentation output has {} values", output.len()))
113 })
114 }
115}
116
117pub struct LadderSegmenter {
118 rungs: Vec<Rung>,
119 runners: Vec<Option<Box<dyn Runner>>>,
120 active: usize,
121 next_probe: usize,
122 probe: Option<(usize, Probe)>,
123 served: u32,
124 timings: VecDeque<Duration>,
125}
126
127impl LadderSegmenter {
128 pub fn new() -> Result<Self> {
129 Self::with_rungs(rungs(
130 runtime::environment().is_some(),
131 runtime::gpu_available(),
132 on_battery(),
133 ))
134 }
135
136 pub fn with_rungs(rungs: Vec<Rung>) -> Result<Self> {
137 let first = rungs
138 .first()
139 .ok_or_else(|| Error::Webrtc("segmentation: no model".into()))?;
140 let runner = runtime::runner(&first.spec, first.device)
141 .map_err(|error| Error::Webrtc(format!("segmentation model: {error}")))?;
142 let mut runners: Vec<Option<Box<dyn Runner>>> = rungs.iter().map(|_| None).collect();
143 runners[0] = Some(runner);
144 Ok(LadderSegmenter {
145 next_probe: 1,
146 rungs,
147 runners,
148 active: 0,
149 probe: None,
150 served: 0,
151 timings: VecDeque::new(),
152 })
153 }
154
155 pub fn active(&self) -> ModelSpec {
156 self.rungs[self.active].spec
157 }
158
159 fn adopt_probe(&mut self) {
160 let Some((rung, handle)) = self.probe.take_if(|(_, handle)| handle.is_finished()) else {
161 return;
162 };
163 match handle.join().ok().flatten() {
164 Some((runner, typical)) if typical <= budget(self.rungs[rung].device) => {
165 self.runners[rung] = Some(runner);
166 self.active = rung;
167 self.timings.clear();
168 self.served = 0;
169 self.next_probe = rung + 1;
170 }
171 _ => self.next_probe = self.rungs.len(),
172 }
173 }
174
175 fn start_probe(&mut self, frame: &mut I420Buffer) {
176 if self.probe.is_some() || self.served < PROBE_AFTER || self.next_probe >= self.rungs.len()
177 {
178 return;
179 }
180 let rung = self.rungs[self.next_probe];
181 self.probe = Some((self.next_probe, probe(rung, rung.spec.input(frame))));
182 }
183
184 fn record(&mut self, elapsed: Duration) {
185 self.timings.push_back(elapsed);
186 if self.timings.len() > TIMING_WINDOW {
187 self.timings.pop_front();
188 }
189 let behind =
190 self.timings.len() == TIMING_WINDOW && median(self.timings.iter().copied()) > BEHIND;
191 if behind && self.active > 0 {
192 self.runners[self.active] = None;
193 self.active -= 1;
194 self.next_probe = self.rungs.len();
195 self.timings.clear();
196 }
197 }
198}
199
200impl MaskInference for LadderSegmenter {
201 fn accelerated(&self) -> bool {
202 self.rungs[self.active].device == Device::Gpu
203 }
204
205 fn model(&self) -> &'static str {
206 self.active().name
207 }
208
209 fn infer(&mut self, mut frame: I420Buffer) -> Result<Mask> {
210 self.adopt_probe();
211 self.start_probe(&mut frame);
212 let spec = self.rungs[self.active].spec;
213 let input = spec.input(&mut frame);
214 let runner = self.runners[self.active]
215 .as_mut()
216 .ok_or_else(|| Error::Webrtc("segmentation: runner missing".into()))?;
217 let started = Instant::now();
218 let output = runner
219 .run(input)
220 .map_err(|error| Error::Webrtc(format!("segmentation: {error}")))?;
221 let elapsed = started.elapsed();
222 self.served += 1;
223 if self.active > 0 {
224 self.record(elapsed);
225 }
226 spec.mask(&output).ok_or_else(|| {
227 Error::Webrtc(format!("segmentation output has {} values", output.len()))
228 })
229 }
230}
231
232#[cfg(windows)]
233fn on_battery() -> bool {
234 use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};
235 let mut status = SYSTEM_POWER_STATUS::default();
236 unsafe { GetSystemPowerStatus(&mut status) }.is_ok() && status.ACLineStatus == 0
237}
238
239#[cfg(not(windows))]
240fn on_battery() -> bool {
241 std::fs::read_dir("/sys/class/power_supply")
242 .into_iter()
243 .flatten()
244 .flatten()
245 .any(|supply| {
246 let read =
247 |name: &str| std::fs::read_to_string(supply.path().join(name)).unwrap_or_default();
248 read("type").trim() == "Battery" && read("status").trim() == "Discharging"
249 })
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use crate::camera::i420_from_rgba;
256
257 struct Fixed(Duration, usize);
258
259 impl Runner for Fixed {
260 fn run(&mut self, _input: Vec<f32>) -> std::result::Result<Vec<f32>, String> {
261 std::thread::sleep(self.0);
262 Ok(vec![0.5; self.1])
263 }
264 }
265
266 fn ladder(times: [Duration; 2]) -> LadderSegmenter {
267 let rungs = vec![
268 Rung {
269 spec: MEDIAPIPE,
270 device: Device::Cpu { threads: 1 },
271 },
272 Rung {
273 spec: MODNET_SMALL,
274 device: Device::Cpu { threads: 1 },
275 },
276 ];
277 let mut ladder = LadderSegmenter::with_rungs(rungs.clone()).expect("mediapipe loads");
278 ladder.runners[0] = Some(Box::new(Fixed(
279 times[0],
280 MEDIAPIPE.width * MEDIAPIPE.height,
281 )));
282 ladder.runners[1] = Some(Box::new(Fixed(
283 times[1],
284 MODNET_SMALL.width * MODNET_SMALL.height,
285 )));
286 ladder
287 }
288
289 fn frame() -> I420Buffer {
290 i420_from_rgba(&vec![128u8; 64 * 36 * 4], 64, 36)
291 }
292
293 #[test]
294 fn the_ladder_starts_small_and_steps_down_when_the_big_model_falls_behind() {
295 let mut ladder = ladder([Duration::ZERO, BEHIND + Duration::from_millis(5)]);
296 assert_eq!(ladder.infer(frame()).unwrap().width, MEDIAPIPE.width);
297 ladder.active = 1;
298 ladder.next_probe = 2;
299 assert_eq!(ladder.infer(frame()).unwrap().width, MODNET_SMALL.width);
300 for _ in 1..TIMING_WINDOW {
301 ladder.infer(frame()).unwrap();
302 }
303 assert_eq!(ladder.active(), MEDIAPIPE);
304 assert!(ladder.runners[1].is_none());
305 }
306
307 fn finished_probe(ladder: &mut LadderSegmenter, typical: Duration) {
308 ladder.runners[1] = None;
309 let handle = std::thread::spawn(move || {
310 Some((
311 Box::new(Fixed(
312 Duration::ZERO,
313 MODNET_SMALL.width * MODNET_SMALL.height,
314 )) as Box<dyn Runner>,
315 typical,
316 ))
317 });
318 while !handle.is_finished() {
319 std::thread::yield_now();
320 }
321 ladder.probe = Some((1, handle));
322 }
323
324 #[test]
325 fn a_probe_within_budget_takes_over_and_a_slow_one_ends_the_climb() {
326 for (typical, climbs) in [(BUDGET / 2, true), (BUDGET * 2, false)] {
327 let mut ladder = ladder([Duration::ZERO, Duration::ZERO]);
328 finished_probe(&mut ladder, typical);
329 let mask = ladder.infer(frame()).unwrap();
330 assert_eq!(mask.width == MODNET_SMALL.width, climbs);
331 assert_eq!(ladder.next_probe, 2);
332 }
333 }
334
335 #[test]
336 fn a_gpu_rung_gets_a_longer_budget_and_segments_every_frame() {
337 let typical = Duration::from_millis(45);
338 for (device, climbs) in [(Device::Gpu, true), (Device::Cpu { threads: 4 }, false)] {
339 let mut ladder = ladder([Duration::ZERO, Duration::ZERO]);
340 ladder.rungs[1].device = device;
341 finished_probe(&mut ladder, typical);
342 ladder.infer(frame()).unwrap();
343 assert_eq!(ladder.active() == MODNET_SMALL, climbs);
344 assert_eq!(ladder.accelerated(), climbs);
345 }
346 }
347
348 #[test]
349 fn battery_missing_gpu_and_missing_onnx_runtime_shorten_the_ladder() {
350 assert_eq!(
351 rungs(true, true, true),
352 vec![
353 Rung {
354 spec: MEDIAPIPE,
355 device: Device::Cpu { threads: 1 },
356 },
357 Rung {
358 spec: MODNET_SMALL,
359 device: Device::Gpu,
360 },
361 ]
362 );
363 assert_eq!(rungs(true, false, true).len(), 1);
364 assert_eq!(
365 rungs(false, false, false).len(),
366 1,
367 "no matting model on tract"
368 );
369 assert_eq!(
370 rungs(true, false, false)
371 .iter()
372 .map(|rung| rung.spec)
373 .collect::<Vec<_>>(),
374 vec![MEDIAPIPE, MODNET_SMALL]
375 );
376 assert_eq!(
377 rungs(true, true, false).last().unwrap(),
378 &Rung {
379 spec: MODNET_LARGE,
380 device: Device::Gpu
381 }
382 );
383 }
384
385 #[test]
386 fn every_ladder_model_runs_and_answers_one_value_per_cell() {
387 let onnx_specs = if runtime::environment().is_some() {
388 vec![MEDIAPIPE, MODNET_SMALL]
389 } else {
390 Vec::new()
391 };
392 for spec in onnx_specs {
393 let mut runner =
394 runtime::runner(&spec, Device::Cpu { threads: 2 }).expect("model loads");
395 let output = runner
396 .run(spec.input(&mut frame()))
397 .expect("inference runs");
398 assert!(spec.mask(&output).is_some(), "{}", spec.name);
399 }
400 let mut tract = runtime::tract_only(&MEDIAPIPE);
401 assert_eq!(
402 tract.run(MEDIAPIPE.input(&mut frame())).unwrap().len(),
403 MEDIAPIPE.width * MEDIAPIPE.height
404 );
405 }
406}