Skip to main content

cosmic_applet_avestruz/
video.rs

1// SPDX-License-Identifier: MIT
2
3//! Videos notes link to, played where the link was: in the note's row.
4//!
5//! Nothing of a video is fetched until its reader presses play: the server
6//! it is on sees that request, a video is large, and it has sound. Then
7//! GStreamer does the work. A `playbin` fetches the address and decodes
8//! what it finds, the sound goes to the system's output, and the pictures
9//! come here, each scaled to what a row can show and converted to RGBA,
10//! through an `appsink`. The app looks for a new one thirty times a second
11//! while a video plays (see [`TICK_PLAYING`]) and shows the latest.
12//!
13//! ```mermaid
14//! flowchart LR
15//!     url["An https address"] --> playbin["playbin: fetches, demuxes, decodes"]
16//!     playbin -->|"sound"| audio["The system's audio output"]
17//!     playbin -->|"pictures"| convert["videoconvert, videoscale: RGBA, no side over the limit"]
18//!     convert --> sink["appsink: keeps the latest frame, drops the rest"]
19//!     sink -->|"taken at each tick"| playback["Playback: the frame as an image, where it is, how long it is"]
20//!     playback --> row["The row's video box"]
21//! ```
22//!
23//! One video plays at a time, and it plays while it is on screen. The
24//! rows of a list are built anew each time the popup is, and only those in
25//! view: so [`Videos`] counts the times the popup is built, a row that
26//! shows the video says so as it is built, and a video no row has shown
27//! through a few builds of the popup, and for a moment, is held. That is
28//! one rule for a row scrolled out of view and for another view shown in
29//! the list's place. A closed popup is not built at all, and holds its
30//! video as it closes.
31//!
32//! Whether a video's sound is off, and how loud it is, is asked of what
33//! plays it, not kept here (see [`SOUND_EVERY`]): where the system
34//! remembers how an app's sound was left, as PipeWire and PulseAudio do, a
35//! video starts as the last one ended, muted if that was and as loud as
36//! that was, and the mute button and its slider say so.
37//!
38//! A video plays at the speed its reader chose (see [`Speed`]), which
39//! holds for the next one too until the applet is started again. A speed
40//! is a seek: to where the video is, to play on from there at another
41//! rate. Its sound keeps its pitch, where GStreamer has the element for
42//! that (`scaletempo`).
43//!
44//! The room a video takes in its row is settled before anything of it is
45//! known ([`box_size`]): as wide as the row, in the proportions the note
46//! says it has, or those of most videos if it doesn't say. What plays is
47//! fitted inside, so a row is the same height before, while and after.
48//!
49//! A link to YouTube is to a page, and what there is to play of it has to
50//! be found first (see [`crate::youtube`]). Its [`Playback`] is there from
51//! the press, saying it is on its way, and gets its player when the
52//! stream is found.
53//!
54//! The address comes from whoever wrote the note. Only `https` is played,
55//! and it is GStreamer that fetches it: its decoders read what a stranger
56//! sent, which is one more reason nothing plays unasked.
57
58use std::cell::Cell;
59use std::collections::HashSet;
60use std::sync::{Arc, Mutex, OnceLock, PoisonError};
61use std::time::{Duration, Instant};
62
63use cosmic::iced::Size;
64use cosmic::widget::image::Handle;
65use gstreamer as gst;
66use gstreamer::prelude::*;
67use gstreamer_app as gst_app;
68use gstreamer_video as gst_video;
69use gstreamer_video::prelude::*;
70
71use crate::youtube;
72
73/// How often a video that plays is looked at for a new frame, and how
74/// often one that doesn't, while the popup is open: it may still have a
75/// frame to show after a seek, or something to say.
76pub const TICK_PLAYING: Duration = Duration::from_millis(33);
77pub const TICK_PAUSED: Duration = Duration::from_millis(250);
78
79/// How long a video plays on with no row showing it, and through how
80/// many builds of the popup, before it is held. Both, because neither
81/// says it alone: a popup that took its time to draw has let a moment go
82/// by without being built again, and one that is built several times
83/// before it is drawn once has not been long about it.
84const UNSEEN: Duration = Duration::from_millis(700);
85const UNSEEN_VIEWS: u64 = 3;
86
87/// How often a video is asked whether its sound is off, and how loud it
88/// is. That is not the mute button's alone to say: the system may start a
89/// video's sound as it left this app's last, off included, and a mixer
90/// can turn it off, on, up or down at any time. The button and its slider
91/// show what is so, a moment later at most.
92const SOUND_EVERY: Duration = Duration::from_millis(250);
93
94/// How loud a video is, as its reader is shown it and sets it: from `0.0`
95/// to `1.0`, on the scale a system's mixer shows, where half way sounds
96/// about half as loud. What plays it counts in amplitude, which is that
97/// cubed: half way there is an eighth.
98fn shown_volume(amplitude: f64) -> f64 {
99    amplitude.clamp(0.0, 1.0).cbrt()
100}
101
102/// The amplitude that is shown as `shown` (see [`shown_volume`]).
103fn amplitude(shown: f64) -> f64 {
104    shown.clamp(0.0, 1.0).powi(3)
105}
106
107/// How fast a video plays: `1` is as it was made. One of [`Speed::ALL`].
108#[derive(Debug, Clone, Copy, PartialEq)]
109pub struct Speed(f64);
110
111impl Default for Speed {
112    fn default() -> Self {
113        Self(1.0)
114    }
115}
116
117impl Speed {
118    /// The speeds there are to choose from, the slowest first.
119    pub const ALL: [Self; 6] = [Self(0.5), Self(0.75), Self(1.0), Self(1.25), Self(1.5), Self(2.0)];
120
121    /// As a player says it: `1×`, `1.25×`.
122    pub fn label(self) -> String {
123        format!("{}\u{d7}", self.0)
124    }
125
126    /// Whether this is the speed a video was made to play at.
127    pub fn is_usual(self) -> bool {
128        self == Self::default()
129    }
130}
131
132/// How loud a video is, as its button says it at a glance.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Loudness {
135    /// Its sound is off, or turned all the way down.
136    Off,
137    Low,
138    Medium,
139    High,
140}
141
142/// The most pixels a frame has on either side when it is handed over:
143/// more than the popup shows at any scale, and far fewer than a video may
144/// have. Frames are copied thirty times a second.
145const FRAME_MAX_SIDE: i32 = 960;
146
147/// The most bits a second taken of a video that comes in several sizes
148/// to choose from, as the playlist of a live one lists them: about what
149/// one 720 lines tall takes. Its pictures are shown no larger than
150/// [`FRAME_MAX_SIDE`], so the sizes over that would be fetched and
151/// decoded to be scaled down.
152const STREAM_BITRATE_MAX: u32 = 3_500_000;
153
154/// The proportions a video is given room for when its note doesn't say
155/// its own: what most videos have.
156const USUAL_ASPECT: (u32, u32) = (16, 9);
157
158/// The room a video takes in a row `width` wide, when its note says it is
159/// `size` pixels, or doesn't say: the whole width, as tall as its
160/// proportions make that, and never taller than it is wide. A video taller
161/// than that plays between bars, with its controls still in view.
162pub fn box_size(size: Option<(u32, u32)>, width: f32) -> Size {
163    let (across, down) = size.filter(|(across, down)| *across > 0 && *down > 0).unwrap_or(USUAL_ASPECT);
164    let height = width * down as f32 / across as f32;
165    Size::new(width, height.min(width))
166}
167
168/// `seconds` as a player says it: `0:07`, `12:34`, `1:02:03`.
169pub fn clock(seconds: f64) -> String {
170    let seconds = if seconds.is_finite() && seconds > 0.0 { seconds as u64 } else { 0 };
171    let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
172    if hours > 0 { format!("{hours}:{minutes:02}:{seconds:02}") } else { format!("{minutes}:{seconds:02}") }
173}
174
175/// One picture of a video: RGBA, row after row, with nothing between the
176/// rows.
177struct Frame {
178    width: u32,
179    height: u32,
180    rgba: Vec<u8>,
181}
182
183/// The picture `sample` carries, copied out row by row: a row may be
184/// longer in the buffer than the pixels it holds.
185fn frame_of(sample: &gst::Sample) -> Option<Frame> {
186    let info = gst_video::VideoInfo::from_caps(sample.caps()?).ok()?;
187    let frame = gst_video::VideoFrameRef::from_buffer_ref_readable(sample.buffer()?, &info).ok()?;
188    let (width, height) = (frame.width() as usize, frame.height() as usize);
189    let stride = usize::try_from(*frame.plane_stride().first()?).ok()?;
190    let row = width * 4;
191    if row == 0 || stride < row {
192        return None;
193    }
194    let mut rgba = Vec::with_capacity(row * height);
195    for line in frame.plane_data(0).ok()?.chunks(stride).take(height) {
196        rgba.extend_from_slice(line.get(..row)?);
197    }
198    (rgba.len() == row * height).then_some(Frame { width: frame.width(), height: frame.height(), rgba })
199}
200
201/// GStreamer, started once. What it said if it could not be: there is no
202/// second try in one run.
203fn ready() -> Result<(), String> {
204    static READY: OnceLock<Result<(), String>> = OnceLock::new();
205    READY.get_or_init(|| gst::init().map_err(|e| e.to_string())).clone()
206}
207
208/// Where a video's pictures go: converted to RGBA with square pixels,
209/// scaled down until neither side is over [`FRAME_MAX_SIDE`], and the
210/// latest kept in `latest` for whoever takes it. A frame nobody took is
211/// dropped for the next: what is shown is what is current.
212fn picture_sink(latest: Arc<Mutex<Option<Frame>>>) -> Result<gst::Element, String> {
213    let caps = gst_video::VideoCapsBuilder::new()
214        .format(gst_video::VideoFormat::Rgba)
215        .pixel_aspect_ratio(gst::Fraction::new(1, 1))
216        .width_range(1..=FRAME_MAX_SIDE)
217        .height_range(1..=FRAME_MAX_SIDE)
218        .build();
219    let sink = gst_app::AppSink::builder().caps(&caps).max_buffers(1).drop(true).build();
220    sink.set_callbacks(
221        gst_app::AppSinkCallbacks::builder()
222            .new_sample(move |sink| {
223                let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
224                if let Some(frame) = frame_of(&sample) {
225                    *latest.lock().unwrap_or_else(PoisonError::into_inner) = Some(frame);
226                }
227                Ok(gst::FlowSuccess::Ok)
228            })
229            .build(),
230    );
231
232    let said = |e: &dyn std::fmt::Display| format!("the video's pictures have nowhere to go: {e}");
233    let make = |name: &str| gst::ElementFactory::make(name).build().map_err(|e| said(&e));
234    let (convert, scale) = (make("videoconvert")?, make("videoscale")?);
235    let bin = gst::Bin::new();
236    let parts = [&convert, &scale, sink.upcast_ref()];
237    bin.add_many(parts).map_err(|e| said(&e))?;
238    gst::Element::link_many(parts).map_err(|e| said(&e))?;
239    let entry = convert.static_pad("sink").ok_or_else(|| said(&"no way in"))?;
240    let entry = gst::GhostPad::with_target(&entry).map_err(|e| said(&e))?;
241    bin.add_pad(&entry).map_err(|e| said(&e))?;
242    Ok(bin.upcast())
243}
244
245/// What a player has to say for itself, when it is asked.
246#[derive(Debug, Clone, PartialEq, Eq)]
247enum Happened {
248    /// It played to its end.
249    Ended,
250    /// It can't go on: why, as GStreamer says it.
251    Failed(String),
252}
253
254/// One video, being played by GStreamer. Dropping it stops it.
255struct Player {
256    playbin: gst::Element,
257    latest: Arc<Mutex<Option<Frame>>>,
258}
259
260impl Player {
261    /// Start playing the video at `url`, which has to be an `https`
262    /// address: nothing else is fetched, and no file of this machine is
263    /// played because a note names it.
264    fn open(url: &str) -> Result<Self, String> {
265        let https = reqwest::Url::parse(url).is_ok_and(|url| url.scheme() == "https");
266        if !https {
267            return Err("not an https address".to_string());
268        }
269        Self::start(url)
270    }
271
272    /// Start playing what is at `uri`, whatever it is.
273    fn start(uri: &str) -> Result<Self, String> {
274        ready()?;
275        let playbin = gst::ElementFactory::make("playbin3")
276            .build()
277            .or_else(|_| gst::ElementFactory::make("playbin").build())
278            .map_err(|e| e.to_string())?;
279        let latest: Arc<Mutex<Option<Frame>>> = Arc::default();
280        playbin.set_property("uri", uri);
281        playbin.set_property("video-sink", picture_sink(latest.clone())?);
282        // Played faster or slower, its sound keeps its pitch, if there is
283        // what does that; and changes it, as a record does, if not.
284        if let Ok(tempo) = gst::ElementFactory::make("scaletempo").build() {
285            playbin.set_property("audio-filter", &tempo);
286        }
287        // Its `flags` are left as they come. Asked for pictures and sound
288        // and nothing else, it never gets as far as having either.
289        // Whatever fetches it says who is asking as everything else
290        // fetched here does.
291        playbin.connect("source-setup", false, |values| {
292            if let Some(source) = values.get(1).and_then(|value| value.get::<gst::Element>().ok())
293                && source.has_property("user-agent")
294            {
295                source.set_property("user-agent", concat!("avestruz/", env!("CARGO_PKG_VERSION")));
296            }
297            None
298        });
299        // What comes in several sizes, as a live video does, is taken in
300        // one that a row can show: whatever chooses among them is told
301        // the most to choose.
302        playbin.connect("element-setup", false, |values| {
303            if let Some(element) = values.get(1).and_then(|value| value.get::<gst::Element>().ok())
304                && element.find_property("max-bitrate").is_some_and(|most| most.value_type() == u32::static_type())
305            {
306                element.set_property("max-bitrate", STREAM_BITRATE_MAX);
307            }
308            None
309        });
310        let player = Self { playbin, latest };
311        player.playbin.set_state(gst::State::Playing).map_err(|e| e.to_string())?;
312        Ok(player)
313    }
314
315    fn play(&self) {
316        let _ = self.playbin.set_state(gst::State::Playing);
317    }
318
319    fn pause(&self) {
320        let _ = self.playbin.set_state(gst::State::Paused);
321    }
322
323    fn set_muted(&self, muted: bool) {
324        self.playbin.set_property("mute", muted);
325    }
326
327    /// Whether its sound is off, as whatever plays the sound has it.
328    fn muted(&self) -> bool {
329        self.playbin.property("mute")
330    }
331
332    /// Make it as loud as `amplitude`, of `1.0` at the most.
333    fn set_volume(&self, amplitude: f64) {
334        self.playbin.set_property("volume", amplitude);
335    }
336
337    /// How loud it is, in amplitude, as whatever plays the sound has it.
338    fn volume(&self) -> f64 {
339        self.playbin.property("volume")
340    }
341
342    /// Go to `seconds` from the start, and there exactly, and play on from
343    /// there at `speed`. Going to the picture nearest before it that
344    /// stands on its own would be quicker, and in a short video that may
345    /// be the first one: wherever it was dragged, it would start over.
346    /// Returns whether it could.
347    fn seek(&self, seconds: f64, speed: Speed) -> bool {
348        let to = gst::ClockTime::from_mseconds((seconds.max(0.0) * 1000.0) as u64);
349        let flags = gst::SeekFlags::FLUSH | gst::SeekFlags::ACCURATE;
350        self.playbin.seek(speed.0, flags, gst::SeekType::Set, to, gst::SeekType::None, gst::ClockTime::NONE).is_ok()
351    }
352
353    /// How far in it is, in seconds, if it knows.
354    fn position(&self) -> Option<f64> {
355        self.playbin.query_position::<gst::ClockTime>().map(|at| at.mseconds() as f64 / 1000.0)
356    }
357
358    /// How long it is, in seconds, if it knows yet.
359    fn duration(&self) -> Option<f64> {
360        self.playbin.query_duration::<gst::ClockTime>().map(|all| all.mseconds() as f64 / 1000.0)
361    }
362
363    /// The newest picture, if there is one since the last was taken.
364    fn take_frame(&self) -> Option<Frame> {
365        self.latest.lock().unwrap_or_else(PoisonError::into_inner).take()
366    }
367
368    /// Hear what it has said since it was last asked: that it ended, or
369    /// that it failed. While it is short of what to play it is held, and
370    /// let go again, if it is `playing`, when it has enough.
371    fn poll(&self, playing: bool) -> Option<Happened> {
372        let bus = self.playbin.bus()?;
373        let mut happened = None;
374        while let Some(message) = bus.pop() {
375            match message.view() {
376                gst::MessageView::Eos(_) => happened = happened.or(Some(Happened::Ended)),
377                gst::MessageView::Error(error) => return Some(Happened::Failed(error.error().to_string())),
378                gst::MessageView::Buffering(buffering) if buffering.percent() < 100 => self.pause(),
379                gst::MessageView::Buffering(_) if playing => self.play(),
380                _ => {}
381            }
382        }
383        happened
384    }
385}
386
387impl Drop for Player {
388    fn drop(&mut self) {
389        // Stopping may wait on the network to let go: not on the thread
390        // the window is drawn on.
391        let playbin = self.playbin.clone();
392        std::thread::spawn(move || {
393            let _ = playbin.set_state(gst::State::Null);
394        });
395    }
396}
397
398/// The video that plays, or did last, as the model keeps it and its row
399/// shows it.
400pub struct Playback {
401    /// Which video it is: its address.
402    url: String,
403    /// What plays it. `None` once it failed, if it never started, or
404    /// while what there is to play of it is looked for.
405    player: Option<Player>,
406    /// What there is to play of it is being looked for: it is a page
407    /// that shows a video, not a file.
408    awaited: bool,
409    /// Its latest picture, if it has had one.
410    pub frame: Option<Handle>,
411    /// It is meant to be playing, whether or not it has anything to play
412    /// yet.
413    pub playing: bool,
414    /// It played to its end.
415    pub ended: bool,
416    /// Its sound is off, as it was when last asked (see [`SOUND_EVERY`]).
417    pub muted: bool,
418    /// How loud it is, as shown (see [`shown_volume`]), when last asked.
419    pub volume: f64,
420    /// The pointer is over its mute button, or over the slider beside
421    /// it that sets how loud it is.
422    sound_over: bool,
423    /// That slider is being dragged, wherever the pointer has got to.
424    sound_dragged: bool,
425    /// When that was.
426    sound_asked: Instant,
427    /// How fast it is to play, and how fast what plays it was last told
428    /// to: it can only be told once it has something to play.
429    speed: Speed,
430    speed_told: Speed,
431    /// How far in it is, in seconds.
432    pub position: f64,
433    /// How long it is, in seconds, once it is known.
434    pub duration: Option<f64>,
435    /// Where its reader is dragging it to, while they are.
436    pub seeking: Option<f64>,
437    /// Why it can't be played, as GStreamer says it.
438    pub error: Option<String>,
439    /// When a row last showed it, and which build of the popup that was.
440    seen: Cell<(Instant, u64)>,
441}
442
443impl Playback {
444    /// Start playing the video at `url`. One that can't be started says
445    /// why, where it would have played.
446    pub fn start(url: &str) -> Self {
447        match Player::open(url) {
448            Ok(player) => Self::new(url, Some(player), None),
449            Err(e) => {
450                tracing::warn!("a video could not be played: {e}");
451                Self::new(url, None, Some(e))
452            }
453        }
454    }
455
456    /// The video at `url`, to play once what there is to play of it has
457    /// been found (see [`Playback::found`]): on its way until then.
458    fn awaiting(url: &str) -> Self {
459        Self { awaited: true, playing: true, ..Self::new(url, None, None) }
460    }
461
462    /// The video at `url`, played by `player`, or not played for `error`.
463    fn new(url: &str, player: Option<Player>, error: Option<String>) -> Self {
464        Self {
465            url: url.to_string(),
466            playing: player.is_some(),
467            player,
468            awaited: false,
469            frame: None,
470            ended: false,
471            muted: false,
472            volume: 1.0,
473            sound_over: false,
474            sound_dragged: false,
475            sound_asked: Instant::now(),
476            speed: Speed::default(),
477            speed_told: Speed::default(),
478            position: 0.0,
479            duration: None,
480            seeking: None,
481            error,
482            seen: Cell::new((Instant::now(), 0)),
483        }
484    }
485
486    /// A playback of the video at `url` with nothing playing it: what the
487    /// model keeps and a row shows, without GStreamer.
488    #[cfg(test)]
489    pub(crate) fn held(url: &str) -> Self {
490        Self { url: url.to_string(), error: None, ..Self::start("not an address") }
491    }
492
493    /// A row shows it, in build `view` of the popup.
494    fn seen(&self, view: u64) {
495        self.seen.set((Instant::now(), view));
496    }
497
498    /// Whether no row has shown it for a while, the popup having been
499    /// built `views` times so far.
500    fn unseen(&self, views: u64) -> bool {
501        let (when, view) = self.seen.get();
502        when.elapsed() > UNSEEN && views.saturating_sub(view) >= UNSEEN_VIEWS
503    }
504
505    /// Whether it is waiting for its first picture.
506    pub fn loading(&self) -> bool {
507        self.playing && self.frame.is_none() && self.error.is_none()
508    }
509
510    /// How often it is to be looked at, while the popup is `open`: often
511    /// while it plays or is on its way to, now and then while it is on
512    /// show and doesn't, and not at all once it has failed or is paused
513    /// out of sight.
514    pub fn tick_every(&self, open: bool) -> Option<Duration> {
515        match (self.playing, open && self.player.is_some()) {
516            (true, _) => Some(TICK_PLAYING),
517            (false, true) => Some(TICK_PAUSED),
518            (false, false) => None,
519        }
520    }
521
522    /// Hold it where it is.
523    pub fn pause(&mut self) {
524        self.playing = false;
525        if let Some(player) = &self.player {
526            player.pause();
527        }
528    }
529
530    /// What there is to play of it was found, at the address `stream`, or
531    /// was not, and why: play it, unless it was held meanwhile, or say why
532    /// it can't be.
533    fn found(&mut self, stream: Result<String, String>) {
534        self.awaited = false;
535        match stream.and_then(|stream| Player::open(&stream)) {
536            Ok(player) => {
537                if !self.playing {
538                    player.pause();
539                }
540                self.player = Some(player);
541            }
542            Err(e) => {
543                tracing::warn!("a video could not be played: {e}");
544                self.playing = false;
545                self.error = Some(e);
546            }
547        }
548    }
549
550    /// Play it if it is held, from the start if it had ended; hold it if
551    /// it plays. `view` is the build of the popup it was pressed in.
552    fn toggle(&mut self, view: u64) {
553        // Still looked for: what is changed is what it does when found.
554        if self.awaited {
555            self.playing = !self.playing;
556            self.seen(view);
557            return;
558        }
559        let Some(player) = &self.player else {
560            return;
561        };
562        if self.playing {
563            self.pause();
564            return;
565        }
566        if std::mem::take(&mut self.ended) {
567            player.seek(0.0, self.speed);
568            self.position = 0.0;
569        }
570        self.playing = true;
571        self.seen(view);
572        player.play();
573    }
574
575    /// Turn its sound off if it is on, and on if it is off: as it is,
576    /// not as it was last seen to be.
577    pub fn toggle_mute(&mut self) {
578        match &self.player {
579            Some(player) => {
580                self.muted = !player.muted();
581                player.set_muted(self.muted);
582                self.sound_asked = Instant::now();
583            }
584            None => self.muted = !self.muted,
585        }
586    }
587
588    /// Make it as loud as `shown` (see [`shown_volume`]). Turned up from
589    /// silence it is no longer muted: whoever moves the slider means to
590    /// hear it.
591    pub fn set_volume(&mut self, shown: f64) {
592        self.volume = shown.clamp(0.0, 1.0);
593        let heard = self.volume > 0.0 && self.muted;
594        if heard {
595            self.muted = false;
596        }
597        if let Some(player) = &self.player {
598            player.set_volume(amplitude(self.volume));
599            if heard {
600                player.set_muted(false);
601            }
602            // Not asked again while it is being dragged: what was just
603            // set is what is so.
604            self.sound_asked = Instant::now();
605        }
606    }
607
608    /// Whether the slider that sets how loud it is shows: while the
609    /// pointer is over it or over the mute button, and until it is let go
610    /// of if it is being dragged, which seldom stays on so small a thing.
611    pub fn sound_shows(&self) -> bool {
612        self.sound_over || self.sound_dragged
613    }
614
615    /// How loud it is, at a glance: for the picture on its mute button.
616    pub fn loudness(&self) -> Loudness {
617        match self.volume {
618            _ if self.muted => Loudness::Off,
619            volume if volume <= 0.0 => Loudness::Off,
620            volume if volume < 0.34 => Loudness::Low,
621            volume if volume < 0.67 => Loudness::Medium,
622            _ => Loudness::High,
623        }
624    }
625
626    /// Its reader let go of it at `seconds`: go there.
627    pub fn seek(&mut self, seconds: f64) {
628        self.seeking = None;
629        self.ended = false;
630        self.position = seconds;
631        if let Some(player) = &self.player
632            && player.seek(seconds, self.speed)
633        {
634            self.speed_told = self.speed;
635        }
636    }
637
638    /// How fast it plays, or is to once it has something to play.
639    pub fn speed(&self) -> Speed {
640        self.speed
641    }
642
643    /// Look at it: take its newest picture, hear whether it ended or
644    /// failed, note how far in it is, and hold it if no row has shown it
645    /// for a while, the popup having been built `views` times so far.
646    fn tick(&mut self, views: u64) {
647        if self.playing && self.unseen(views) {
648            self.pause();
649        }
650        let Some(player) = &self.player else {
651            return;
652        };
653        if let Some(frame) = player.take_frame() {
654            self.frame = Some(Handle::from_rgba(frame.width, frame.height, frame.rgba));
655        }
656        if self.duration.is_none() {
657            self.duration = player.duration().filter(|all| *all > 0.0);
658        }
659        let at = player.position();
660        if let Some(at) = at {
661            self.position = at;
662        }
663        // Told how fast to play once it has a picture, which is when it
664        // can be told anything; and where it is, so that it plays on from
665        // there. One that can't change its speed stays at the one it has.
666        // One with no length is live, and is not told: played faster it
667        // would run out of what there is of it, and stall there.
668        if self.speed != self.speed_told
669            && self.frame.is_some()
670            && self.duration.is_some()
671            && let Some(at) = at
672        {
673            if player.seek(at, self.speed) {
674                self.speed_told = self.speed;
675            } else {
676                tracing::warn!("a video would not play at {}", self.speed.label());
677                self.speed = self.speed_told;
678            }
679        }
680        if self.sound_asked.elapsed() >= SOUND_EVERY {
681            self.muted = player.muted();
682            self.volume = shown_volume(player.volume());
683            self.sound_asked = Instant::now();
684        }
685        match player.poll(self.playing) {
686            Some(Happened::Ended) => {
687                self.playing = false;
688                self.ended = true;
689            }
690            Some(Happened::Failed(why)) => {
691                tracing::warn!("a video stopped playing ({}): {why}", self.url);
692                self.playing = false;
693                self.error = Some(why);
694                self.player = None;
695            }
696            None => {}
697        }
698    }
699}
700
701/// The videos of the notes on show, as the model keeps them.
702#[derive(Default)]
703pub struct Videos {
704    /// The one that plays, or did last.
705    pub playing: Option<Playback>,
706    /// The links that turned out to be videos when they were asked what
707    /// they are, and were then played: each has the room of a video from
708    /// then on, in place of the card it had.
709    pub opened: HashSet<String>,
710    /// How many times the popup was built to be drawn.
711    views: Cell<u64>,
712    /// How fast videos play: the one that plays, and those after it.
713    speed: Speed,
714    /// The menu of speeds is open, on the one that plays.
715    speed_menu: bool,
716}
717
718impl Videos {
719    /// The popup is being built, to be drawn.
720    pub fn viewing(&self) {
721        self.views.set(self.views.get() + 1);
722    }
723
724    /// The playback of the video at `url`, if that is the one that plays,
725    /// or did last, for a row that shows it: which keeps it playing.
726    pub fn shown(&self, url: &str) -> Option<&Playback> {
727        let playback = self.playing.as_ref().filter(|playback| playback.url == url)?;
728        playback.seen(self.views.get());
729        Some(playback)
730    }
731
732    /// The play button of the video at `url` was pressed: hold it or let
733    /// it go if it is the one that plays, and start it in place of that
734    /// one if not. One that failed is started again.
735    ///
736    /// A YouTube video can't be started from its link: it is returned,
737    /// for what there is to play of it to be found and told to
738    /// [`Videos::found`], and is on its way until then.
739    pub fn press(&mut self, url: &str) -> Option<youtube::Video> {
740        match &mut self.playing {
741            Some(playback) if playback.url == url && playback.error.is_none() => {
742                playback.toggle(self.views.get());
743                None
744            }
745            _ => {
746                self.opened.insert(url.to_string());
747                let page = youtube::video_at(url);
748                let mut playback = if page.is_some() { Playback::awaiting(url) } else { Playback::start(url) };
749                playback.speed = self.speed;
750                playback.seen(self.views.get());
751                self.playing = Some(playback);
752                page
753            }
754        }
755    }
756
757    /// What there is to play of the video at `url` was found, or was not,
758    /// and why. Nothing comes of it if that video is no longer the one to
759    /// play, or is played already.
760    pub fn found(&mut self, url: &str, stream: Result<String, String>) {
761        if let Some(playback) = self.playing.as_mut().filter(|playback| playback.url == url && playback.awaited) {
762            playback.found(stream);
763        }
764    }
765
766    /// How fast videos play.
767    pub fn speed(&self) -> Speed {
768        self.speed
769    }
770
771    /// Play at `speed` from now on: the one that plays, and those after
772    /// it. The menu it was chosen from is put away.
773    pub fn set_speed(&mut self, speed: Speed) {
774        self.speed = speed;
775        self.speed_menu = false;
776        if let Some(playback) = &mut self.playing {
777            playback.speed = speed;
778        }
779    }
780
781    /// Whether the menu of speeds is open.
782    pub fn speed_menu(&self) -> bool {
783        self.speed_menu
784    }
785
786    /// Open the menu of speeds if it is closed, and close it if it is
787    /// open.
788    pub fn toggle_speed_menu(&mut self) {
789        self.speed_menu = !self.speed_menu;
790    }
791
792    /// Put the menu of speeds away.
793    pub fn close_speed_menu(&mut self) {
794        self.speed_menu = false;
795    }
796
797    /// Hold the one that plays, if one does: the popup closed. The
798    /// pointer is over nothing of it any more, and no menu is open.
799    pub fn pause(&mut self) {
800        self.speed_menu = false;
801        if let Some(playback) = &mut self.playing {
802            (playback.sound_over, playback.sound_dragged) = (false, false);
803            if playback.playing {
804                playback.pause();
805            }
806        }
807    }
808
809    /// Stop the one that plays and forget it: whoever was watching left.
810    pub fn stop(&mut self) {
811        self.speed_menu = false;
812        self.playing = None;
813    }
814
815    /// How often the one that plays is to be looked at, while the popup is
816    /// `open`, if at all.
817    pub fn tick_every(&self, open: bool) -> Option<Duration> {
818        self.playing.as_ref()?.tick_every(open)
819    }
820
821    /// Look at the one that plays: for its newest picture, how far in it
822    /// is, whether it ended or failed, and whether it is still on screen.
823    pub fn tick(&mut self) {
824        if let Some(playback) = &mut self.playing {
825            playback.tick(self.views.get());
826        }
827    }
828
829    /// Turn the sound of the one that plays off, or back on.
830    pub fn toggle_mute(&mut self) {
831        if let Some(playback) = &mut self.playing {
832            playback.toggle_mute();
833        }
834    }
835
836    /// The slider of the one that plays is being dragged to `shown`,
837    /// from `0.0` to `1.0`: make it that loud.
838    pub fn set_volume(&mut self, shown: f64) {
839        if let Some(playback) = &mut self.playing {
840            playback.sound_dragged = true;
841            playback.set_volume(shown);
842        }
843    }
844
845    /// That slider was let go.
846    pub fn volume_set(&mut self) {
847        if let Some(playback) = &mut self.playing {
848            playback.sound_dragged = false;
849        }
850    }
851
852    /// The pointer came over the sound controls of the one that plays, or
853    /// left them (see [`Playback::sound_shows`]).
854    pub fn sound_over(&mut self, over: bool) {
855        if let Some(playback) = &mut self.playing {
856            playback.sound_over = over;
857        }
858    }
859
860    /// The one that plays is being dragged to `seconds` in: show that,
861    /// and go nowhere until it is let go.
862    pub fn seeking(&mut self, seconds: f64) {
863        if let Some(playback) = &mut self.playing {
864            playback.seeking = Some(seconds);
865        }
866    }
867
868    /// It was let go: go where it was dragged to.
869    pub fn seek(&mut self) {
870        if let Some(playback) = &mut self.playing
871            && let Some(seconds) = playback.seeking
872        {
873            playback.seek(seconds);
874        }
875    }
876}
877
878#[cfg(test)]
879mod tests {
880    use super::{
881        FRAME_MAX_SIDE, Frame, Loudness, Playback, Player, Speed, UNSEEN, UNSEEN_VIEWS, Videos, amplitude, box_size, clock,
882        picture_sink, ready, shown_volume,
883    };
884    use cosmic::iced::Size;
885    use gstreamer as gst;
886    use gstreamer::prelude::*;
887    use std::sync::{Arc, Mutex};
888    use std::time::{Duration, Instant};
889
890    #[test]
891    fn a_video_has_the_whole_width_and_is_never_taller_than_wide() {
892        assert_eq!(box_size(Some((1920, 1080)), 480.0), Size::new(480.0, 270.0));
893        assert_eq!(box_size(None, 480.0), Size::new(480.0, 270.0), "what most videos are, when the note doesn't say");
894        assert_eq!(box_size(Some((0, 1080)), 480.0), Size::new(480.0, 270.0));
895        // A small one is given the same room: it is scaled up to play.
896        assert_eq!(box_size(Some((320, 240)), 480.0), Size::new(480.0, 360.0));
897        // One held upright plays between bars.
898        assert_eq!(box_size(Some((1080, 1920)), 480.0), Size::new(480.0, 480.0));
899    }
900
901    #[test]
902    fn time_reads_as_a_player_says_it() {
903        assert_eq!(clock(0.0), "0:00");
904        assert_eq!(clock(7.9), "0:07");
905        assert_eq!(clock(754.0), "12:34");
906        assert_eq!(clock(3723.0), "1:02:03");
907        assert_eq!(clock(-3.0), "0:00");
908        assert_eq!(clock(f64::NAN), "0:00");
909    }
910
911    #[test]
912    fn how_loud_is_shown_as_a_mixer_shows_it() {
913        // Half way on the slider is an eighth in amplitude, and back.
914        assert!((amplitude(0.5) - 0.125).abs() < 1e-9);
915        assert!((shown_volume(0.125) - 0.5).abs() < 1e-9);
916        for shown in [0.0, 0.01, 0.33, 0.5, 0.8, 1.0] {
917            assert!((shown_volume(amplitude(shown)) - shown).abs() < 1e-9, "{shown}");
918        }
919        // Louder than whole, as a mixer can make it, shows as whole; and
920        // nothing is asked for that is not between nothing and whole.
921        assert_eq!(shown_volume(1.7), 1.0);
922        assert_eq!((amplitude(-1.0), amplitude(3.0)), (0.0, 1.0));
923    }
924
925    #[test]
926    fn the_mute_button_says_how_loud_and_the_slider_unmutes() {
927        let mut playback = Playback::held("https://example.com/a.mp4");
928        assert_eq!((playback.volume, playback.loudness()), (1.0, Loudness::High));
929        for (shown, loudness) in [(0.0, Loudness::Off), (0.2, Loudness::Low), (0.5, Loudness::Medium), (0.67, Loudness::High)] {
930            playback.set_volume(shown);
931            assert_eq!((playback.volume, playback.loudness()), (shown, loudness));
932        }
933        playback.set_volume(7.0);
934        assert_eq!(playback.volume, 1.0);
935
936        // Muted, it is off however loud it would be.
937        playback.toggle_mute();
938        assert!(playback.muted && playback.loudness() == Loudness::Off && playback.volume == 1.0);
939        // Turned all the way down it stays muted; turned up, it is heard.
940        playback.set_volume(0.0);
941        assert!(playback.muted);
942        playback.set_volume(0.4);
943        assert!(!playback.muted && playback.loudness() == Loudness::Medium);
944    }
945
946    #[test]
947    fn the_slider_of_the_sound_shows_under_the_pointer_and_while_it_is_dragged() {
948        let mut videos = Videos::default();
949        // With no video played there is nothing to show it for.
950        videos.sound_over(true);
951        videos.set_volume(0.5);
952        assert!(videos.playing.is_none());
953
954        videos.playing = Some(Playback::held("https://example.com/a.mp4"));
955        let shows = |videos: &Videos| videos.playing.as_ref().is_some_and(Playback::sound_shows);
956        assert!(!shows(&videos));
957        videos.sound_over(true);
958        assert!(shows(&videos));
959        videos.sound_over(false);
960        assert!(!shows(&videos));
961
962        // Dragged, it stays though the pointer wanders off it, until it
963        // is let go.
964        videos.sound_over(true);
965        videos.set_volume(0.5);
966        videos.sound_over(false);
967        assert!(shows(&videos));
968        videos.set_volume(0.3);
969        assert!(videos.playing.as_ref().is_some_and(|playback| playback.volume == 0.3));
970        videos.volume_set();
971        assert!(!shows(&videos));
972        // Let go with the pointer still on it, it stays.
973        videos.sound_over(true);
974        videos.set_volume(0.6);
975        videos.volume_set();
976        assert!(shows(&videos));
977
978        // The popup closing puts it away, whatever the pointer was doing.
979        videos.set_volume(0.7);
980        videos.pause();
981        assert!(!shows(&videos));
982    }
983
984    #[test]
985    fn a_youtube_video_is_on_its_way_until_what_there_is_to_play_of_it_is_found() {
986        let link = "https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt";
987        let awaited = |videos: &Videos| videos.playing.as_ref().is_some_and(|playback| playback.awaited);
988        let mut videos = Videos::default();
989
990        // Pressed, it is the one to play, and what to look for is said.
991        let asked = videos.press(link).unwrap();
992        assert_eq!(asked.page(), "https://www.youtube.com/watch?v=aqz-KE-bpKQ");
993        let playback = videos.shown(link).unwrap();
994        assert!(playback.loading() && playback.error.is_none() && awaited(&videos));
995        assert_eq!(videos.tick_every(true), Some(super::TICK_PLAYING), "looked at, for whether it is still on show");
996
997        // Pressed again meanwhile, it is not looked for twice: it is held,
998        // and let go again.
999        assert_eq!(videos.press(link), None);
1000        assert!(videos.shown(link).is_some_and(|playback| !playback.playing && !playback.loading()));
1001        assert_eq!(videos.press(link), None);
1002        assert!(videos.shown(link).is_some_and(Playback::loading));
1003
1004        // Not found: it says why, where it would have played.
1005        videos.found(link, Err("yt-dlp says no".to_string()));
1006        let failed = videos.shown(link).unwrap();
1007        assert!(!failed.playing && !awaited(&videos));
1008        assert_eq!(failed.error.as_deref(), Some("yt-dlp says no"));
1009        // Found late, after that, nothing comes of it.
1010        videos.found(link, Ok("https://example.com/stream".to_string()));
1011        assert_eq!(videos.shown(link).unwrap().error.as_deref(), Some("yt-dlp says no"));
1012
1013        // Pressed again, it is looked for again. What is found that is not
1014        // an https address is not played.
1015        assert!(videos.press(link).is_some());
1016        videos.found(link, Ok("file:///etc/passwd".to_string()));
1017        assert_eq!(videos.shown(link).unwrap().error.as_deref(), Some("not an https address"));
1018
1019        // Another video pressed meanwhile is the one to play: the answer
1020        // for the first is nobody's.
1021        assert!(videos.press(link).is_some());
1022        assert_eq!(videos.press("http://example.com/b.mp4"), None);
1023        videos.found(link, Err("too late".to_string()));
1024        assert!(videos.shown(link).is_none());
1025        assert_eq!(videos.shown("http://example.com/b.mp4").unwrap().error.as_deref(), Some("not an https address"));
1026    }
1027
1028    #[test]
1029    fn a_speed_is_chosen_from_a_few_and_holds_for_the_next_video() {
1030        let labels: Vec<String> = Speed::ALL.iter().map(|speed| speed.label()).collect();
1031        assert_eq!(labels, ["0.5×", "0.75×", "1×", "1.25×", "1.5×", "2×"]);
1032        assert_eq!(Speed::ALL.iter().filter(|speed| speed.is_usual()).count(), 1);
1033        assert_eq!(Speed::default().label(), "1×");
1034        let [.., faster, _] = Speed::ALL;
1035
1036        let mut videos = Videos::default();
1037        assert!(videos.speed().is_usual() && !videos.speed_menu());
1038        videos.playing = Some(Playback::held("https://example.com/a.mp4"));
1039        videos.toggle_speed_menu();
1040        assert!(videos.speed_menu());
1041        // Chosen, it is the speed of the one that plays, and the menu is
1042        // put away.
1043        videos.set_speed(faster);
1044        assert!(!videos.speed_menu());
1045        assert_eq!((videos.speed(), videos.playing.as_ref().unwrap().speed()), (faster, faster));
1046
1047        // The next video plays at it too, a YouTube one included.
1048        assert_eq!(videos.press("http://example.com/b.mp4"), None);
1049        assert_eq!(videos.playing.as_ref().unwrap().speed(), faster);
1050        assert!(videos.press("https://youtu.be/aqz-KE-bpKQ").is_some());
1051        assert_eq!(videos.playing.as_ref().unwrap().speed(), faster);
1052
1053        // The menu is put away by itself as the popup closes, and when
1054        // whoever was watching leaves.
1055        videos.toggle_speed_menu();
1056        videos.pause();
1057        assert!(!videos.speed_menu());
1058        videos.toggle_speed_menu();
1059        videos.toggle_speed_menu();
1060        assert!(!videos.speed_menu());
1061        videos.toggle_speed_menu();
1062        videos.stop();
1063        assert!(!videos.speed_menu() && videos.speed() == faster);
1064    }
1065
1066    #[test]
1067    fn only_an_https_address_is_played() {
1068        for refused in ["http://example.com/a.mp4", "file:///etc/passwd", "rtsp://example.com/live", "a.mp4", ""] {
1069            assert_eq!(Player::open(refused).err().as_deref(), Some("not an https address"), "{refused}");
1070        }
1071        let refused = Playback::start("file:///etc/passwd");
1072        assert!(!refused.playing && refused.error.is_some() && refused.tick_every(true).is_none());
1073    }
1074
1075    /// `videos`, with the one that plays last shown `ago` ago.
1076    fn shown_ago(videos: &Videos, ago: Duration) {
1077        let playback = videos.playing.as_ref().unwrap();
1078        let (_, view) = playback.seen.get();
1079        playback.seen.set((Instant::now().checked_sub(ago).unwrap(), view));
1080    }
1081
1082    #[test]
1083    fn a_video_no_row_shows_is_held_and_one_that_is_shown_plays_on() {
1084        let url = "https://example.com/a.mp4";
1085        let long = UNSEEN + Duration::from_millis(50);
1086        let mut videos = Videos::default();
1087        videos.playing = Some(Playback::held(url));
1088        videos.playing.as_mut().unwrap().playing = true;
1089        let playing = |videos: &Videos| videos.playing.as_ref().unwrap().playing;
1090
1091        // Shown in each build of the popup: it plays on, however long each
1092        // took to draw.
1093        for _ in 0..10 {
1094            videos.viewing();
1095            assert!(videos.shown(url).is_some());
1096            shown_ago(&videos, long);
1097            videos.tick();
1098            assert!(playing(&videos));
1099        }
1100
1101        // The popup built again and again in no time, as it is when much
1102        // happens at once, and the row not yet: it plays on.
1103        assert!(videos.shown(url).is_some());
1104        for _ in 0..10 {
1105            videos.viewing();
1106        }
1107        videos.tick();
1108        assert!(playing(&videos), "not for long");
1109
1110        // Not shown for a while, through a few builds: it is held. Another
1111        // video's row is not its own.
1112        assert!(videos.shown(url).is_some());
1113        shown_ago(&videos, long);
1114        for _ in 1..UNSEEN_VIEWS {
1115            videos.viewing();
1116            assert!(videos.shown("https://example.com/b.mp4").is_none());
1117            videos.tick();
1118            assert!(playing(&videos), "one build is not a while");
1119        }
1120        videos.viewing();
1121        videos.tick();
1122        assert!(!playing(&videos), "out of sight");
1123
1124        // And stays so until its reader says otherwise.
1125        videos.viewing();
1126        assert!(videos.shown(url).is_some());
1127        videos.tick();
1128        assert!(!playing(&videos));
1129    }
1130
1131    #[test]
1132    fn pressing_play_holds_the_video_that_plays_and_starts_any_other() {
1133        let mut videos = Videos::default();
1134        videos.playing = Some(Playback::held("https://example.com/a.mp4"));
1135        assert!(videos.shown("https://example.com/a.mp4").is_some());
1136        assert!(videos.shown("https://example.com/b.mp4").is_none());
1137
1138        // Another one takes its place, and has the room of a video from
1139        // then on. (This one can't start: there is nothing at it.)
1140        videos.press("http://example.com/b.mp4");
1141        assert!(videos.shown("https://example.com/a.mp4").is_none());
1142        assert!(videos.shown("http://example.com/b.mp4").is_some_and(|playback| playback.error.is_some()));
1143        assert!(videos.opened.contains("http://example.com/b.mp4"));
1144
1145        // A file is started at once, and nothing more is asked for.
1146        assert_eq!(videos.press("https://example.com/a.mp4"), None);
1147
1148        // The popup closing holds the one that plays, and signing out
1149        // forgets it.
1150        videos.playing = Some(Playback::held("https://example.com/a.mp4"));
1151        videos.playing.as_mut().unwrap().playing = true;
1152        videos.pause();
1153        assert!(videos.playing.as_ref().is_some_and(|playback| !playback.playing));
1154        videos.stop();
1155        assert!(videos.playing.is_none());
1156    }
1157
1158    /// Whether GStreamer is there, with the elements `needed`: without
1159    /// them a test of it has nothing to stand on, and passes for nothing.
1160    fn gstreamer_has(needed: &[&str]) -> bool {
1161        let there = ready().is_ok() && needed.iter().all(|name| gst::ElementFactory::find(name).is_some());
1162        if !there {
1163            eprintln!("GStreamer, or one of {needed:?}, is not installed: nothing was tested");
1164        }
1165        there
1166    }
1167
1168    /// The first frame the picture sink hands over of a test picture
1169    /// `width` by `height`.
1170    fn first_frame_of(width: i32, height: i32) -> Frame {
1171        let latest: Arc<Mutex<Option<Frame>>> = Arc::default();
1172        let pipeline = gst::Pipeline::new();
1173        let source = gst::ElementFactory::make("videotestsrc").property("num-buffers", 3).build().unwrap();
1174        let caps = gst::Caps::builder("video/x-raw").field("width", width).field("height", height).build();
1175        let filter = gst::ElementFactory::make("capsfilter").property("caps", &caps).build().unwrap();
1176        let sink = picture_sink(latest.clone()).unwrap();
1177        pipeline.add_many([&source, &filter, &sink]).unwrap();
1178        gst::Element::link_many([&source, &filter, &sink]).unwrap();
1179        pipeline.set_state(gst::State::Playing).unwrap();
1180        let bus = pipeline.bus().unwrap();
1181        let ended = bus.timed_pop_filtered(gst::ClockTime::from_seconds(10), &[gst::MessageType::Eos, gst::MessageType::Error]);
1182        pipeline.set_state(gst::State::Null).unwrap();
1183        assert!(matches!(ended.unwrap().view(), gst::MessageView::Eos(_)));
1184        latest.lock().unwrap().take().unwrap()
1185    }
1186
1187    #[test]
1188    fn frames_come_as_rgba_scaled_down_to_fit_and_in_their_own_proportions() {
1189        if !gstreamer_has(&["videotestsrc", "videoconvert", "videoscale", "capsfilter"]) {
1190            return;
1191        }
1192        let side = FRAME_MAX_SIDE as u32;
1193        for ((width, height), expected) in [
1194            ((320, 240), (320, 240)),
1195            ((1920, 1080), (side, side * 9 / 16)),
1196            ((1080, 1920), (side * 9 / 16, side)),
1197            ((1001, 333), (side, 319)),
1198        ] {
1199            let frame = first_frame_of(width, height);
1200            assert_eq!((frame.width, frame.height), expected, "{width}x{height}");
1201            assert_eq!(frame.rgba.len(), (frame.width * frame.height * 4) as usize);
1202            // The test picture is opaque, and not all one colour.
1203            assert!(frame.rgba.chunks(4).all(|pixel| pixel[3] == 255));
1204            assert!(frame.rgba.chunks(4).any(|pixel| pixel[..3] != frame.rgba[..3]));
1205        }
1206    }
1207
1208    /// What it takes to make a test video and play it.
1209    const TO_PLAY: [&str; 7] = ["videotestsrc", "jpegenc", "avimux", "filesink", "playbin", "avidemux", "jpegdec"];
1210
1211    /// `seconds` of a test picture, as a file called after `name`.
1212    fn test_video(name: &str, seconds: u32) -> std::path::PathBuf {
1213        let path = std::env::temp_dir().join(format!("avestruz-test-{}-{name}.avi", std::process::id()));
1214        let making = format!(
1215            "videotestsrc num-buffers={} ! video/x-raw,width=320,height=240,framerate=30/1 ! jpegenc ! avimux ! filesink location={}",
1216            seconds * 30,
1217            path.display()
1218        );
1219        let made = gst::parse::launch(&making).unwrap();
1220        made.set_state(gst::State::Playing).unwrap();
1221        let bus = made.bus().unwrap();
1222        let done = bus.timed_pop_filtered(gst::ClockTime::from_seconds(20), &[gst::MessageType::Eos, gst::MessageType::Error]);
1223        made.set_state(gst::State::Null).unwrap();
1224        assert!(matches!(done.unwrap().view(), gst::MessageView::Eos(_)));
1225        path
1226    }
1227
1228    /// Look at `playback` as the app looks at it, shown each time, until
1229    /// `until` says so; for ten seconds at the most.
1230    fn watch(playback: &mut Playback, until: &dyn Fn(&Playback) -> bool) {
1231        let started = Instant::now();
1232        while !until(playback) && started.elapsed() < Duration::from_secs(10) {
1233            playback.seen(0);
1234            playback.tick(0);
1235            std::thread::sleep(Duration::from_millis(10));
1236        }
1237        assert!(until(playback), "within ten seconds");
1238    }
1239
1240    #[test]
1241    fn a_video_plays_faster_or_slower_as_it_is_told_and_seeks_at_that_speed() {
1242        if !gstreamer_has(&TO_PLAY) {
1243            return;
1244        }
1245        let path = test_video("speed", 8);
1246        let [slower, .., faster] = Speed::ALL;
1247        let mut playback = Playback::held(&format!("file://{}", path.display()));
1248        playback.player = Some(Player::start(&playback.url).unwrap());
1249        playback.playing = true;
1250        playback.toggle_mute();
1251
1252        // How far it gets in half a second of watching, for each second
1253        // that takes.
1254        let pace = |playback: &mut Playback| {
1255            let (started, from) = (Instant::now(), playback.position);
1256            watch(playback, &|_| started.elapsed() >= Duration::from_millis(500));
1257            (playback.position - from) / started.elapsed().as_secs_f64()
1258        };
1259
1260        // Told before it has anything to play, it is told again once it
1261        // has, and plays on from where it was.
1262        playback.speed = faster;
1263        watch(&mut playback, &|playback| playback.speed_told == faster);
1264        assert!(playback.frame.is_some() && playback.error.is_none());
1265        let fast = pace(&mut playback);
1266        assert!((1.6..=2.4).contains(&fast), "twice as fast: {fast}");
1267
1268        // Gone elsewhere in, it plays on as fast from there.
1269        playback.seek(1.0);
1270        watch(&mut playback, &|playback| playback.position >= 1.0 && playback.position < 3.0);
1271        let fast = pace(&mut playback);
1272        assert!((1.6..=2.4).contains(&fast), "still twice as fast: {fast}");
1273
1274        playback.speed = slower;
1275        let before = playback.position;
1276        watch(&mut playback, &|playback| playback.speed_told == slower);
1277        let slow = pace(&mut playback);
1278        assert!((0.3..=0.7).contains(&slow), "half as fast: {slow}");
1279        assert!(playback.position >= before && playback.position < before + 1.5, "from where it was");
1280        let _ = std::fs::remove_file(&path);
1281    }
1282
1283    #[test]
1284    fn a_video_plays_to_its_end_and_can_be_played_again() {
1285        if !gstreamer_has(&TO_PLAY) {
1286            return;
1287        }
1288        // A second of a test picture, as a file.
1289        let path = test_video("video", 1);
1290
1291        let mut playback = Playback::held(&format!("file://{}", path.display()));
1292        playback.player = Some(Player::start(&playback.url).unwrap());
1293        playback.playing = true;
1294        playback.toggle_mute();
1295        assert!(playback.loading() && playback.tick_every(false).is_some());
1296
1297        watch(&mut playback, &|playback| playback.ended);
1298        assert!(playback.frame.is_some() && !playback.playing && playback.error.is_none());
1299        // Its sound is as it was left: asked of what plays it since, more
1300        // than once, and not only remembered.
1301        assert!(playback.muted && playback.sound_asked.elapsed() < Duration::from_secs(1));
1302        playback.toggle_mute();
1303        assert!(!playback.muted);
1304        playback.toggle_mute();
1305        // How loud it is, likewise: set, and then heard back from what
1306        // plays it.
1307        playback.set_volume(0.5);
1308        watch(&mut playback, &|playback| playback.sound_asked.elapsed() < Duration::from_millis(50));
1309        assert!((playback.volume - 0.5).abs() < 0.01 && !playback.muted, "{}", playback.volume);
1310        playback.toggle_mute();
1311        assert!(playback.duration.is_some_and(|all| (0.9..=1.1).contains(&all)), "{:?}", playback.duration);
1312        assert_eq!(playback.tick_every(false), None, "nothing to look at while it is held out of sight");
1313
1314        // Played again, it starts over.
1315        playback.toggle(0);
1316        assert!(playback.playing && !playback.ended && playback.position == 0.0);
1317        watch(&mut playback, &|playback| playback.ended);
1318
1319        // What is not a video says so, where it would have played.
1320        std::fs::write(&path, "not a video").unwrap();
1321        let mut broken = Playback::held(&playback.url);
1322        broken.player = Some(Player::start(&broken.url).unwrap());
1323        broken.playing = true;
1324        watch(&mut broken, &|playback| playback.error.is_some());
1325        assert!(!broken.playing && broken.player.is_none());
1326        let _ = std::fs::remove_file(&path);
1327    }
1328}