Skip to main content

moq_ext_egui/
overlay.rs

1//! Translucent stats bars painted over video.
2//!
3//! [`DebugOverlay`] draws a bar of clickable sections along the bottom of a
4//! video. It shows the stats of a [`Player`] or a [`LocalBroadcast`]. The
5//! stats carry only current values, so the overlay keeps its own short history
6//! for the sparklines.
7//!
8//! [`fit_to_aspect`] sizes a video to the space it has.
9
10use 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
30/// Height of the overlay bar, text and padding included.
31const BAR_HEIGHT: f32 = 15.0;
32
33/// Returns the largest size that fits `available` and keeps `aspect`.
34///
35/// The aspect is width over height.
36#[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
47/// The alpha of the translucent black behind bars and panels.
48const BG_ALPHA: u8 = 200;
49
50/// How often the overlay records history, so its length does not depend on the repaint rate.
51const SAMPLE_INTERVAL: Duration = Duration::from_millis(100);
52
53/// The points kept per series, twelve seconds at [`SAMPLE_INTERVAL`].
54const HISTORY_LEN: usize = 120;
55
56/// The width of a sparkline, in points.
57const SPARK_WIDTH: f32 = 100.0;
58
59// Colors that grade a figure, and the one for plain information.
60const 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/// A section of the overlay's bottom bar.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum StatCategory {
68    /// The player's link figures, or the outgoing video of a broadcast.
69    Net,
70    /// The publisher's source, encoders, and slot states.
71    Capture,
72    /// The player's video decoding and rendition switching.
73    Render,
74    /// The player's audio and the playout latency.
75    ///
76    /// The latency is here because it includes the audio queued at the
77    /// speaker, so it moves with the audio buffer.
78    Audio,
79    /// The player's timeline of presented frames over the last ten seconds.
80    ///
81    /// Scrolling over the panel pauses it and moves back in time. A double
82    /// click returns to the live edge.
83    Time,
84}
85
86impl StatCategory {
87    /// Returns the short label shown in the bottom bar.
88    #[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/// A debug overlay with a bottom bar and detail panels.
101///
102/// The bar shows a short summary for each enabled category. Clicking a section
103/// toggles a panel above the bar with all figures and their sparklines.
104/// Several panels can be open at once.
105#[derive(Debug)]
106pub struct DebugOverlay {
107    /// Enabled categories in bar order, each with whether its panel is open.
108    categories: Vec<(StatCategory, bool)>,
109    history: History,
110    /// Transport details such as path kind and address.
111    ///
112    /// The first line joins the NET summary.
113    link: Vec<String>,
114    /// Seconds the paused timeline is scrolled back from `timeline_paused`.
115    timeline_scroll: f32,
116    /// When the timeline was paused, or `None` while it follows the live edge.
117    timeline_paused: Option<Instant>,
118    /// Salt for this overlay's interaction ids.
119    ///
120    /// Without it, overlays on several tiles would share ids and highlight
121    /// together on hover.
122    salt: egui::Id,
123}
124
125/// Counter that gives each [`DebugOverlay`] its own id salt.
126static OVERLAY_SALT: AtomicU64 = AtomicU64::new(0);
127
128impl DebugOverlay {
129    /// Creates an overlay with the given categories enabled, all collapsed.
130    #[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    /// Sets the link details shown in a player's NET section.
149    ///
150    /// The section already shows whether the path goes through an iroh relay and the rate
151    /// media arrives at, from the player's network sample. These lines add
152    /// what the player does not know, such as addresses. The first line also
153    /// joins the section summary.
154    pub fn set_link(&mut self, lines: Vec<String>) {
155        self.link = lines;
156    }
157
158    /// Returns whether any detail panel is open.
159    #[must_use]
160    pub fn any_expanded(&self) -> bool {
161        self.categories.iter().any(|&(_, expanded)| expanded)
162    }
163
164    /// Draws the overlay for `player` at the bottom of `video_rect`.
165    ///
166    /// Shows the enabled NET, RENDER, AUDIO, and TIME categories. Reads the
167    /// player's timeline only while the TIME panel is open.
168    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, &sections, &timeline);
188    }
189
190    /// Draws the overlay for a local broadcast at the bottom of `video_rect`.
191    ///
192    /// Shows the enabled CAPTURE and NET categories. The publish side has no
193    /// link figures, so NET shows the encoded video bitrate summed over all
194    /// renditions.
195    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, &sections, &[]);
213    }
214
215    /// Returns whether the panel of `category` is open.
216    fn is_expanded(&self, category: StatCategory) -> bool {
217        self.categories
218            .iter()
219            .any(|&(candidate, expanded)| candidate == category && expanded)
220    }
221
222    /// Records the history, then paints the open panels and the bottom bar.
223    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        // Open panels stack upward from the bar. Walking the sections in
234        // reverse puts the first category's panel on top.
235        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, &section.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    /// Paints one detail panel.
318    ///
319    /// Each line with at least two points of history gets a sparkline.
320    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/// The overlay's own history of the figures it plots.
352///
353/// Each series keeps at most [`HISTORY_LEN`] points. A series that gets no
354/// point for that many samples is dropped, so the history stays bounded.
355#[derive(Debug, Default)]
356struct History {
357    /// When the history last took a sample.
358    last_sample: Option<Instant>,
359    /// How many samples the history has taken.
360    tick: u64,
361    /// The plotted figures, by key.
362    series: BTreeMap<String, Series>,
363}
364
365/// The recorded points of one plotted figure.
366#[derive(Debug, Default)]
367struct Series {
368    values: VecDeque<f64>,
369    /// When each value was recorded, for the timeline.
370    times: VecDeque<Instant>,
371    /// The history tick of the latest point, for dropping idle series.
372    last_tick: u64,
373}
374
375impl History {
376    /// Appends the current value of every plotted line.
377    ///
378    /// Records at most once per [`SAMPLE_INTERVAL`].
379    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| &section.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    /// Returns the recorded points of `key`, oldest first.
408    fn get(&self, key: &str) -> Option<&VecDeque<f64>> {
409        self.series.get(key).map(|series| &series.values)
410    }
411
412    /// Returns the recorded points of `key` with their times, oldest first.
413    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
428/// Draws a small line graph of `values`, scaled to their own range.
429fn 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}