Skip to main content

egui_pop_views/video/
session.rs

1//! A video's state from one pass to the next (its player, position, volume,
2//! texture), the context's registry of them, and the sweep stopping the
3//! players of videos no longer drawn.
4
5use std::collections::HashMap;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8use std::time::Duration;
9
10use egui::{Context, Id, TextureHandle, TextureOptions, ViewportId};
11use egui_pop_core::lock;
12use egui_pop_core::state::Slot;
13use serde_json::{Value as Json, json};
14
15use super::{
16    Controls, DEFAULT_ASPECT, VideoBackend, VideoPlayer, VideoRequest, VideoState, VideoStatus,
17};
18
19/// The passes a video may go undrawn before its player stops: a pass may run
20/// before the part holding it is drawn in it.
21const HIDDEN_PASSES: u64 = 3;
22/// The texture's name, for egui's debugging.
23const TEXTURE: &str = "egui_pop.video";
24
25/// What the user asked of a video while it was drawn.
26#[derive(Clone, Copy, Debug)]
27pub(super) enum Act {
28    Toggle,
29    SeekTo(f64),
30    SeekBy(f64),
31    Volume(f32),
32    VolumeBy(f32),
33}
34
35/// One video's state.
36pub(super) struct Session {
37    pub(super) source: PathBuf,
38    /// Its id, for agents.
39    pub(super) name: Option<String>,
40    /// None: the placeholder.
41    backend: Option<Arc<dyn VideoBackend>>,
42    /// None before it opens, while out of view, and after a failure.
43    player: Option<Box<dyn VideoPlayer>>,
44    pub(super) status: VideoStatus,
45    /// The last position known, kept when the player stops.
46    pub(super) position: Duration,
47    pub(super) volume: f32,
48    pub(super) muted: bool,
49    pub(super) autoplay: bool,
50    pub(super) controls: Controls,
51    looping: bool,
52    /// What the player was told of looping, and whether it loops by itself.
53    looping_told: Option<bool>,
54    native_loop: bool,
55    /// The times the widget sought back to the start itself.
56    loops: u64,
57    pub(super) texture: Option<TextureHandle>,
58    pub(super) aspect: f32,
59    /// The position while the slider is dragged.
60    pub(super) scrub: Option<f64>,
61    /// When it was last drawn, and in which window.
62    pass: u64,
63    viewport: ViewportId,
64    pub(super) error: Option<String>,
65    /// It played or moved once: the poster gives way to the frames.
66    pub(super) started: bool,
67    /// Its player was stopped while it was out of view.
68    pub(super) stopped: bool,
69}
70
71impl Session {
72    pub(super) fn new(
73        source: PathBuf,
74        backend: Option<Arc<dyn VideoBackend>>,
75        volume: f32,
76        muted: bool,
77    ) -> Self {
78        Self {
79            source,
80            name: None,
81            backend,
82            player: None,
83            status: VideoStatus::default(),
84            position: Duration::ZERO,
85            volume: volume.clamp(0.0, 1.0),
86            muted,
87            autoplay: false,
88            controls: Controls::Full,
89            looping: false,
90            looping_told: None,
91            native_loop: false,
92            loops: 0,
93            texture: None,
94            aspect: DEFAULT_ASPECT,
95            scrub: None,
96            pass: 0,
97            viewport: ViewportId::ROOT,
98            error: None,
99            started: false,
100            stopped: false,
101        }
102    }
103
104    /// No player for it: the placeholder is drawn.
105    pub(super) fn unavailable(&self) -> bool {
106        self.backend.is_none()
107    }
108
109    /// Its shape: the frame's, else the poster's, else 16:9.
110    pub(super) fn aspect_or(&self, poster: Option<f32>) -> f32 {
111        let aspect = if self.texture.is_some() {
112            self.aspect
113        } else {
114            poster.unwrap_or(DEFAULT_ASPECT)
115        };
116        if aspect.is_finite() && aspect > 0.0 {
117            aspect
118        } else {
119            DEFAULT_ASPECT
120        }
121    }
122
123    /// The volume heard: none while muted.
124    pub(super) fn audible_volume(&self) -> f32 {
125        if self.muted { 0.0 } else { self.volume }
126    }
127
128    pub(super) fn seen(&mut self, pass: u64, viewport: ViewportId) {
129        self.pass = pass;
130        self.viewport = viewport;
131    }
132
133    /// Each pass it is drawn: opens the player (again, after being out of
134    /// view), takes what it says and its last frame, loops.
135    pub(super) fn update(&mut self, ctx: &Context, looping: bool) {
136        self.looping = looping;
137        if self.error.is_some() {
138            return;
139        }
140        let Some(backend) = self.backend.clone() else {
141            return;
142        };
143        if self.player.is_none() {
144            let opened = backend.open(&VideoRequest {
145                path: self.source.clone(),
146                egui: ctx.clone(),
147                volume: self.audible_volume(),
148            });
149            let mut player = match opened {
150                Ok(p) => p,
151                Err(e) => return self.fail(e),
152            };
153            if !self.position.is_zero()
154                && let Err(e) = player.seek(self.position)
155            {
156                return self.fail(e);
157            }
158            self.player = Some(player);
159            self.looping_told = None;
160            self.stopped = false;
161            if self.autoplay
162                && let Err(e) = self.play()
163            {
164                return self.fail(e);
165            }
166        }
167        let Some(player) = self.player.as_mut() else {
168            return;
169        };
170        if self.looping_told != Some(self.looping) {
171            self.native_loop = player.set_looping(self.looping) && self.looping;
172            self.looping_told = Some(self.looping);
173        }
174        let status = match player.poll() {
175            Ok(s) => s,
176            Err(e) => return self.fail(e),
177        };
178        if let Some(p) = status.position {
179            self.position = p;
180        }
181        self.status = status;
182        if let Some(frame) = player.frame() {
183            self.aspect = frame.aspect;
184            match self.texture.as_mut() {
185                Some(t) => t.set(frame.image, TextureOptions::LINEAR),
186                None => {
187                    self.texture =
188                        Some(ctx.load_texture(TEXTURE, frame.image, TextureOptions::LINEAR));
189                }
190            }
191        }
192        if self.status.state == VideoState::Ended && self.looping && !self.native_loop {
193            // The player cannot loop: back to the start, with the gap a
194            // flushing seek makes.
195            self.loops += 1;
196            if let Err(e) = self.seek_to(0.0).and_then(|()| self.play()) {
197                self.fail(e);
198            }
199        }
200    }
201
202    /// The player failed: it stops, the picture says why.
203    fn fail(&mut self, error: String) {
204        self.player = None;
205        self.texture = None;
206        self.error = Some(error);
207    }
208
209    /// Runs `f` on the player; a failure ends it.
210    fn with_player(
211        &mut self,
212        f: impl FnOnce(&mut Self, &mut dyn VideoPlayer) -> Result<(), String>,
213    ) -> Result<(), String> {
214        if let Some(e) = &self.error {
215            return Err(format!("the video failed: {e}"));
216        }
217        if self.unavailable() {
218            return Err("this application has no video player".into());
219        }
220        let Some(mut player) = self.player.take() else {
221            return Err(if self.stopped {
222                "the video is stopped while out of view".into()
223            } else {
224                "the video has not been drawn yet".into()
225            });
226        };
227        let done = f(self, player.as_mut());
228        self.player = Some(player);
229        if let Err(e) = &done {
230            self.fail(e.clone());
231        }
232        done
233    }
234
235    /// What the user asked while it was drawn; a failure is shown in place.
236    pub(super) fn act(&mut self, ctx: &Context, act: Act) {
237        let _ = match act {
238            Act::Toggle => self.toggle(),
239            Act::SeekTo(s) => self.seek_to(s),
240            Act::SeekBy(by) => self.seek_to(self.position.as_secs_f64() + by),
241            Act::Volume(v) => self.set_volume(v),
242            Act::VolumeBy(by) => self.set_volume(self.audible_volume() + by),
243        };
244        ctx.request_repaint();
245    }
246
247    /// Plays or pauses; from the end, plays from the start.
248    pub(super) fn toggle(&mut self) -> Result<(), String> {
249        if self.status.state == VideoState::Playing {
250            self.pause()
251        } else {
252            self.play()
253        }
254    }
255
256    pub(super) fn play(&mut self) -> Result<(), String> {
257        self.with_player(|s, player| {
258            player.play()?;
259            if s.status.state == VideoState::Ended {
260                s.position = Duration::ZERO;
261            }
262            s.status.state = VideoState::Playing;
263            s.started = true;
264            Ok(())
265        })
266    }
267
268    pub(super) fn pause(&mut self) -> Result<(), String> {
269        self.with_player(|s, player| {
270            player.pause()?;
271            if s.status.state != VideoState::Ended {
272                s.status.state = VideoState::Paused;
273            }
274            Ok(())
275        })
276    }
277
278    /// Moves to a position, kept within the video.
279    pub(super) fn seek_to(&mut self, seconds: f64) -> Result<(), String> {
280        self.with_player(|s, player| {
281            let to = Duration::try_from_secs_f64(seconds.max(0.0)).unwrap_or(Duration::ZERO);
282            let to = s.status.duration.map_or(to, |d| to.min(d));
283            player.seek(to)?;
284            s.position = to;
285            s.started = true;
286            if s.status.state == VideoState::Ended {
287                s.status.state = VideoState::Paused;
288            }
289            Ok(())
290        })
291    }
292
293    /// Sets the volume, from 0 to 1, and gives the sound back.
294    pub(super) fn set_volume(&mut self, volume: f32) -> Result<(), String> {
295        self.volume = volume.clamp(0.0, 1.0);
296        self.muted = false;
297        let volume = self.volume;
298        self.with_player(|_, player| {
299            player.set_volume(volume);
300            Ok(())
301        })
302    }
303
304    pub(super) fn set_muted(&mut self, muted: bool) -> Result<(), String> {
305        self.muted = muted;
306        let volume = self.audible_volume();
307        self.with_player(|_, player| {
308            player.set_volume(volume);
309            Ok(())
310        })
311    }
312
313    /// What it holds, for the `videos` collector and the commands.
314    pub(super) fn json(&self) -> Json {
315        let ms = |d: Duration| u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
316        let loops = self.loops + self.player.as_ref().map_or(0, |p| p.loops());
317        json!({
318            "video": self.name,
319            "source": self.source.display().to_string(),
320            "backend": self.backend.as_ref().map(|b| b.name().to_string()),
321            "controls": self.controls,
322            "state": self.status.state,
323            "playing": self.status.state == VideoState::Playing,
324            "stopped": self.stopped,
325            "position_ms": ms(self.position),
326            "duration_ms": self.status.duration.map(ms),
327            // In hundredths, not the float's long tail.
328            "volume": f64::from((self.volume * 100.0).round()) / 100.0,
329            "muted": self.muted,
330            "looping": self.looping,
331            "loops": loops,
332            "size": self.texture.as_ref().map(TextureHandle::size),
333            "note": self.status.note,
334            "error": self.error,
335        })
336    }
337}
338
339/// The videos of a context.
340#[derive(Default)]
341pub(super) struct Registry {
342    sessions: HashMap<Id, Session>,
343    /// The named video whose picture last had the focus.
344    pub(super) focused: Option<String>,
345    swept: bool,
346}
347
348impl std::fmt::Debug for Registry {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        f.debug_struct("Registry")
351            .field("videos", &self.sessions.len())
352            .field("focused", &self.focused)
353            .finish()
354    }
355}
356
357impl Registry {
358    pub(super) fn session(&mut self, key: Id, fresh: impl FnOnce() -> Session) -> &mut Session {
359        self.sessions.entry(key).or_insert_with(fresh)
360    }
361
362    fn named(&mut self, name: &str) -> Option<&mut Session> {
363        self.sessions
364            .values_mut()
365            .find(|s| s.name.as_deref() == Some(name))
366    }
367
368    /// The video a command acts on: `video`, else the one that last had the
369    /// focus, else the only one with an id.
370    fn target(&mut self, video: Option<&str>) -> Result<&mut Session, String> {
371        let name = match video {
372            Some(v) => v.to_string(),
373            None => match self.focused.clone() {
374                Some(f) => f,
375                None => {
376                    let mut names = self.sessions.values().filter_map(|s| s.name.clone());
377                    match (names.next(), names.next()) {
378                        (Some(only), None) => only,
379                        (None, _) => return Err("no video with an id is drawn".into()),
380                        _ => {
381                            return Err(
382                                "several videos have an id and none had the focus; name one with `video`"
383                                    .into(),
384                            );
385                        }
386                    }
387                }
388            },
389        };
390        self.named(&name)
391            .ok_or_else(|| format!("no video `{name}`"))
392    }
393}
394
395/// The registry in the context's memory.
396#[derive(Clone, Default)]
397struct Shared(Arc<Mutex<Registry>>);
398
399impl std::fmt::Debug for Shared {
400    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
401        lock(&self.0).fmt(f)
402    }
403}
404
405const SLOT: Slot<Shared> = Slot::new("views.video");
406
407/// The videos drawn in a context, by id: what the `video.*` commands and the
408/// `videos` collector reach, and the viewer's video page.
409#[derive(Clone)]
410pub struct Videos {
411    ctx: Context,
412    registry: Arc<Mutex<Registry>>,
413}
414
415impl std::fmt::Debug for Videos {
416    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
417        lock(&self.registry).fmt(f)
418    }
419}
420
421impl Videos {
422    /// The context's videos.
423    pub fn of(ctx: &Context) -> Self {
424        Self {
425            ctx: ctx.clone(),
426            registry: SLOT.get_or_insert_with(ctx, Shared::default).0,
427        }
428    }
429
430    pub(super) fn registry(&self) -> Arc<Mutex<Registry>> {
431        self.registry.clone()
432    }
433
434    /// Stops the players of videos no longer drawn, once per pass.
435    pub(super) fn install_sweep(&self) {
436        let mut reg = lock(&self.registry);
437        if !reg.swept {
438            reg.swept = true;
439            drop(reg);
440            self.ctx.add_plugin(Sweep);
441        }
442    }
443
444    /// The ids of the videos drawn with one.
445    pub fn ids(&self) -> Vec<String> {
446        let mut ids: Vec<String> = lock(&self.registry)
447            .sessions
448            .values()
449            .filter_map(|s| s.name.clone())
450            .collect();
451        ids.sort();
452        ids
453    }
454
455    /// What a video holds: its state, position (`position_ms`), length
456    /// (`duration_ms`), volume, whether it plays, loops or is muted, its
457    /// picture's size, a note or an error.
458    pub fn state(&self, video: &str) -> Option<Json> {
459        lock(&self.registry).named(video).map(|s| s.json())
460    }
461
462    /// What the `videos` collector shows: every video with an id, the one
463    /// that last had the focus, and how many have none.
464    pub fn describe(&self) -> Json {
465        let reg = lock(&self.registry);
466        let mut named = serde_json::Map::new();
467        let mut unnamed = 0;
468        for s in reg.sessions.values() {
469            match &s.name {
470                Some(n) => {
471                    named.insert(n.clone(), s.json());
472                }
473                None => unnamed += 1,
474            }
475        }
476        json!({ "videos": named, "focused": reg.focused, "without_id": unnamed })
477    }
478
479    /// Runs `f` on a video (see [`Self::toggle`] for which), then says what it
480    /// holds.
481    fn run(
482        &self,
483        video: Option<&str>,
484        f: impl FnOnce(&mut Session) -> Result<(), String>,
485    ) -> Result<Json, String> {
486        let done = {
487            let mut reg = lock(&self.registry);
488            let s = reg.target(video)?;
489            f(s).map(|()| s.json())
490        };
491        self.ctx.request_repaint();
492        done
493    }
494
495    /// Plays or pauses a video: `video` by its id, else the one whose picture
496    /// last had the focus, else the only one with an id. From its end, it
497    /// plays from the start.
498    pub fn toggle(&self, video: Option<&str>) -> Result<Json, String> {
499        self.run(video, Session::toggle)
500    }
501
502    pub fn play(&self, video: Option<&str>) -> Result<Json, String> {
503        self.run(video, Session::play)
504    }
505
506    pub fn pause(&self, video: Option<&str>) -> Result<Json, String> {
507        self.run(video, Session::pause)
508    }
509
510    /// Moves to a position in seconds, kept within the video.
511    pub fn seek_to(&self, video: Option<&str>, seconds: f64) -> Result<Json, String> {
512        self.run(video, |s| s.seek_to(seconds))
513    }
514
515    /// Moves forward, or back with a negative number.
516    pub fn seek_by(&self, video: Option<&str>, seconds: f64) -> Result<Json, String> {
517        self.run(video, |s| s.seek_to(s.position.as_secs_f64() + seconds))
518    }
519
520    /// Sets the volume, from 0 to 1, and gives the sound back.
521    pub fn set_volume(&self, video: Option<&str>, volume: f32) -> Result<Json, String> {
522        self.run(video, |s| s.set_volume(volume))
523    }
524
525    /// Changes the volume heard by an amount.
526    pub fn volume_by(&self, video: Option<&str>, by: f32) -> Result<Json, String> {
527        self.run(video, |s| s.set_volume(s.audible_volume() + by))
528    }
529
530    /// Mutes or gives the sound back; `None` switches.
531    pub fn set_muted(&self, video: Option<&str>, muted: Option<bool>) -> Result<Json, String> {
532        self.run(video, |s| {
533            let muted = muted.unwrap_or(!s.muted);
534            s.set_muted(muted)
535        })
536    }
537
538    /// Forgets a video: its player stops, and drawn again it starts afresh.
539    /// Whether there was one.
540    pub fn forget(&self, video: &str) -> bool {
541        let gone = {
542            let mut reg = lock(&self.registry);
543            let before = reg.sessions.len();
544            let mut gone = Vec::new();
545            reg.sessions.retain(|_, s| {
546                if s.name.as_deref() == Some(video) {
547                    gone.push(s.player.take());
548                    false
549                } else {
550                    true
551                }
552            });
553            if reg.focused.as_deref() == Some(video) {
554                reg.focused = None;
555            }
556            let found = reg.sessions.len() != before;
557            drop(reg);
558            drop(gone);
559            found
560        };
561        self.ctx.request_repaint();
562        gone
563    }
564
565    /// Once per pass of a window: stops the players of its videos not drawn
566    /// for a few passes, and keeps passes coming until they are stopped.
567    fn sweep(&self) {
568        let now = self.ctx.cumulative_pass_nr();
569        let viewport = self.ctx.viewport_id();
570        let mut stopped = Vec::new();
571        let mut waiting = false;
572        {
573            let mut reg = lock(&self.registry);
574            for s in reg.sessions.values_mut() {
575                if s.viewport != viewport || s.player.is_none() {
576                    continue;
577                }
578                let unseen = now.saturating_sub(s.pass);
579                if unseen >= HIDDEN_PASSES {
580                    stopped.push(s.player.take());
581                    s.texture = None;
582                    s.stopped = true;
583                    if s.status.state != VideoState::Ended {
584                        s.status.state = VideoState::Paused;
585                    }
586                } else if unseen > 0 {
587                    waiting = true;
588                }
589            }
590        }
591        drop(stopped);
592        if waiting {
593            self.ctx.request_repaint();
594        }
595    }
596}
597
598/// egui's hook running the sweep at the end of each pass.
599struct Sweep;
600
601impl egui::Plugin for Sweep {
602    fn debug_name(&self) -> &'static str {
603        "egui_pop.video.sweep"
604    }
605
606    fn on_end_pass(&mut self, ui: &mut egui::Ui) {
607        Videos::of(ui.ctx()).sweep();
608    }
609}