1use std::{
11 collections::{BTreeMap, VecDeque},
12 sync::atomic::{AtomicU64, Ordering},
13 time::{Duration, Instant},
14};
15
16use moq_ext_player::{FrameTiming, Player};
17use moq_ext_publisher::LocalBroadcast;
18
19use self::{
20 sections::{
21 Line, Section, audio_playback, capture_publish, net_playback, net_publish, render_playback,
22 time_playback,
23 },
24 timeline::TIMELINE_HEIGHT,
25};
26
27mod sections;
28mod timeline;
29
30const BAR_HEIGHT: f32 = 15.0;
32
33#[must_use]
37pub fn fit_to_aspect(available: egui::Vec2, aspect: f32) -> egui::Vec2 {
38 let h_by_width = available.x / aspect;
39 if h_by_width <= available.y {
40 egui::vec2(available.x, h_by_width)
41 } else {
42 let w_by_height = available.y * aspect;
43 egui::vec2(w_by_height, available.y)
44 }
45}
46
47const BG_ALPHA: u8 = 200;
49
50const SAMPLE_INTERVAL: Duration = Duration::from_millis(100);
52
53const HISTORY_LEN: usize = 120;
55
56const SPARK_WIDTH: f32 = 100.0;
58
59const COLOR_GOOD: egui::Color32 = egui::Color32::from_rgb(100, 220, 100);
61const COLOR_WARN: egui::Color32 = egui::Color32::from_rgb(220, 200, 80);
62const COLOR_BAD: egui::Color32 = egui::Color32::from_rgb(220, 80, 80);
63const COLOR_DIM: egui::Color32 = egui::Color32::from_rgb(160, 160, 160);
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum StatCategory {
68 Net,
70 Capture,
72 Render,
74 Audio,
79 Time,
84}
85
86impl StatCategory {
87 #[must_use]
89 pub fn label(self) -> &'static str {
90 match self {
91 Self::Net => "NET",
92 Self::Capture => "CAPTURE",
93 Self::Render => "RENDER",
94 Self::Audio => "AUDIO",
95 Self::Time => "TIME",
96 }
97 }
98}
99
100#[derive(Debug)]
106pub struct DebugOverlay {
107 categories: Vec<(StatCategory, bool)>,
109 history: History,
110 link: Vec<String>,
114 timeline_scroll: f32,
116 timeline_paused: Option<Instant>,
118 salt: egui::Id,
123}
124
125static OVERLAY_SALT: AtomicU64 = AtomicU64::new(0);
127
128impl DebugOverlay {
129 #[must_use]
131 pub fn new(categories: &[StatCategory]) -> Self {
132 Self {
133 categories: categories
134 .iter()
135 .map(|&category| (category, false))
136 .collect(),
137 history: History::default(),
138 link: Vec::new(),
139 timeline_scroll: 0.0,
140 timeline_paused: None,
141 salt: egui::Id::unique((
142 "moq-ext-egui overlay",
143 OVERLAY_SALT.fetch_add(1, Ordering::Relaxed),
144 )),
145 }
146 }
147
148 pub fn set_link(&mut self, lines: Vec<String>) {
155 self.link = lines;
156 }
157
158 #[must_use]
160 pub fn any_expanded(&self) -> bool {
161 self.categories.iter().any(|&(_, expanded)| expanded)
162 }
163
164 pub fn show_player(&mut self, ui: &mut egui::Ui, video_rect: egui::Rect, player: &Player) {
169 let stats = player.stats();
170 let status = player.status().borrow().clone();
171 let timeline = if self.is_expanded(StatCategory::Time) {
172 player.timeline()
173 } else {
174 Vec::new()
175 };
176 let sections: Vec<Section> = self
177 .categories
178 .iter()
179 .filter_map(|&(category, _)| match category {
180 StatCategory::Net => Some(net_playback(stats.network.as_ref(), &self.link)),
181 StatCategory::Render => Some(render_playback(&stats, &status)),
182 StatCategory::Audio => Some(audio_playback(&stats, &status)),
183 StatCategory::Time => Some(time_playback(&timeline)),
184 StatCategory::Capture => None,
185 })
186 .collect();
187 self.draw(ui, video_rect, §ions, &timeline);
188 }
189
190 pub fn show_broadcast(
196 &mut self,
197 ui: &mut egui::Ui,
198 video_rect: egui::Rect,
199 broadcast: &LocalBroadcast,
200 ) {
201 let stats = broadcast.stats();
202 let status = broadcast.status().borrow().clone();
203 let sections: Vec<Section> = self
204 .categories
205 .iter()
206 .filter_map(|&(category, _)| match category {
207 StatCategory::Capture => Some(capture_publish(&stats, &status)),
208 StatCategory::Net => Some(net_publish(&stats)),
209 StatCategory::Render | StatCategory::Audio | StatCategory::Time => None,
210 })
211 .collect();
212 self.draw(ui, video_rect, §ions, &[]);
213 }
214
215 fn is_expanded(&self, category: StatCategory) -> bool {
217 self.categories
218 .iter()
219 .any(|&(candidate, expanded)| candidate == category && expanded)
220 }
221
222 fn draw(
224 &mut self,
225 ui: &mut egui::Ui,
226 video_rect: egui::Rect,
227 sections: &[Section],
228 timeline: &[FrameTiming],
229 ) {
230 self.history.record(sections, Instant::now());
231 let font = egui::FontId::monospace(11.0);
232
233 let mut y_cursor = video_rect.max.y - BAR_HEIGHT;
236 for section in sections.iter().rev() {
237 if section.lines.is_empty() || !self.is_expanded(section.category) {
238 continue;
239 }
240 let height = BAR_HEIGHT * (section.lines.len() as f32 + 0.5);
241 y_cursor -= height;
242 let rect = egui::Rect::from_min_size(
243 egui::pos2(video_rect.min.x, y_cursor),
244 egui::vec2(video_rect.width(), height),
245 );
246 self.paint_panel(ui.painter(), rect, §ion.lines, &font);
247 if section.category == StatCategory::Time {
248 y_cursor -= TIMELINE_HEIGHT;
249 let rect = egui::Rect::from_min_size(
250 egui::pos2(video_rect.min.x, y_cursor),
251 egui::vec2(video_rect.width(), TIMELINE_HEIGHT),
252 );
253 self.paint_timeline(ui, rect, timeline);
254 }
255 }
256
257 let bar_rect = egui::Rect::from_min_size(
258 egui::pos2(video_rect.min.x, video_rect.max.y - BAR_HEIGHT),
259 egui::vec2(video_rect.width(), BAR_HEIGHT),
260 );
261 let painter = ui.painter();
262 painter.rect_filled(bar_rect, 0.0, egui::Color32::from_black_alpha(BG_ALPHA));
263
264 let mut clicks = Vec::new();
265 let mut x = bar_rect.min.x + 8.0;
266 for (i, section) in sections.iter().enumerate() {
267 let galley =
268 painter.layout_no_wrap(section.summary.clone(), font.clone(), egui::Color32::WHITE);
269 let section_width = galley.size().x + 8.0;
270 let section_rect = egui::Rect::from_min_size(
271 egui::pos2(x - 4.0, bar_rect.min.y),
272 egui::vec2(section_width, BAR_HEIGHT),
273 );
274
275 let id = self.salt.with(("dbg_section", section.category.label()));
276 let response = ui.interact(section_rect, id, egui::Sense::click());
277 if response.hovered() {
278 painter.rect_filled(section_rect, 2.0, egui::Color32::from_white_alpha(30));
279 painter.line_segment(
280 [section_rect.left_bottom(), section_rect.right_bottom()],
281 egui::Stroke::new(1.0_f32, egui::Color32::from_white_alpha(80)),
282 );
283 }
284 if response.clicked() {
285 clicks.push(section.category);
286 }
287
288 painter.galley(
289 egui::pos2(x, bar_rect.min.y + 1.0),
290 galley,
291 egui::Color32::WHITE,
292 );
293 x += section_width;
294
295 if i + 1 < sections.len() {
296 let sep_x = x + 2.0;
297 painter.line_segment(
298 [
299 egui::pos2(sep_x, bar_rect.min.y + 3.0),
300 egui::pos2(sep_x, bar_rect.max.y - 3.0),
301 ],
302 egui::Stroke::new(1.0_f32, egui::Color32::from_white_alpha(40)),
303 );
304 x += 12.0;
305 }
306 }
307
308 for clicked in clicks {
309 for (category, expanded) in &mut self.categories {
310 if *category == clicked {
311 *expanded = !*expanded;
312 }
313 }
314 }
315 }
316
317 fn paint_panel(
321 &self,
322 painter: &egui::Painter,
323 rect: egui::Rect,
324 lines: &[Line],
325 font: &egui::FontId,
326 ) {
327 painter.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(BG_ALPHA));
328 let mut y = rect.min.y + 2.0;
329 for line in lines {
330 let galley =
331 painter.layout_no_wrap(format!(" {}", line.text), font.clone(), line.color);
332 painter.galley(egui::pos2(rect.min.x + 6.0, y), galley, line.color);
333
334 let history = line
335 .plot
336 .as_ref()
337 .and_then(|(key, _)| self.history.get(key))
338 .filter(|values| values.len() >= 2);
339 if let Some(values) = history {
340 let spark_rect = egui::Rect::from_min_size(
341 egui::pos2(rect.max.x - SPARK_WIDTH - 6.0, y + 2.0),
342 egui::vec2(SPARK_WIDTH, BAR_HEIGHT - 4.0),
343 );
344 paint_sparkline(painter, spark_rect, values, line.color);
345 }
346 y += BAR_HEIGHT;
347 }
348 }
349}
350
351#[derive(Debug, Default)]
356struct History {
357 last_sample: Option<Instant>,
359 tick: u64,
361 series: BTreeMap<String, Series>,
363}
364
365#[derive(Debug, Default)]
367struct Series {
368 values: VecDeque<f64>,
369 times: VecDeque<Instant>,
371 last_tick: u64,
373}
374
375impl History {
376 fn record(&mut self, sections: &[Section], now: Instant) {
380 if self
381 .last_sample
382 .is_some_and(|last| now.duration_since(last) < SAMPLE_INTERVAL)
383 {
384 return;
385 }
386 self.last_sample = Some(now);
387 self.tick += 1;
388 let tick = self.tick;
389 let points = sections
390 .iter()
391 .flat_map(|section| §ion.lines)
392 .filter_map(|line| line.plot.as_ref());
393 for (key, value) in points {
394 let series = self.series.entry(key.clone()).or_default();
395 if series.values.len() >= HISTORY_LEN {
396 series.values.pop_front();
397 series.times.pop_front();
398 }
399 series.values.push_back(*value);
400 series.times.push_back(now);
401 series.last_tick = tick;
402 }
403 self.series
404 .retain(|_, series| tick - series.last_tick < HISTORY_LEN as u64);
405 }
406
407 fn get(&self, key: &str) -> Option<&VecDeque<f64>> {
409 self.series.get(key).map(|series| &series.values)
410 }
411
412 fn timed(&self, key: &str) -> Vec<(Instant, f64)> {
414 self.series
415 .get(key)
416 .map(|series| {
417 series
418 .times
419 .iter()
420 .copied()
421 .zip(series.values.iter().copied())
422 .collect()
423 })
424 .unwrap_or_default()
425 }
426}
427
428fn paint_sparkline(
430 painter: &egui::Painter,
431 rect: egui::Rect,
432 values: &VecDeque<f64>,
433 color: egui::Color32,
434) {
435 let min = values.iter().copied().fold(f64::INFINITY, f64::min);
436 let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
437 let range = (max - min).max(0.001);
438 let last = (values.len() - 1).max(1) as f32;
439 let points: Vec<egui::Pos2> = values
440 .iter()
441 .enumerate()
442 .map(|(i, v)| {
443 let x = rect.min.x + (i as f32 / last) * rect.width();
444 let y = rect.max.y - ((v - min) / range) as f32 * rect.height();
445 egui::pos2(x, y)
446 })
447 .collect();
448 painter.add(egui::Shape::line(
449 points,
450 egui::Stroke::new(1.0_f32, color.linear_multiply(0.7)),
451 ));
452}