BlueGit

ict rusty-teams

Files

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

mod.rs

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