lurq 0.63.2

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! Playing a video or a sound: a [`Media`] opened from a [`Source`], its picture, its sound, and where it is.
//!
//! A media decodes on a thread of its own with the system's decoder (Media Foundation on Windows), keeps its own
//! clock, and puts each frame into an image a [`Video`](crate::components::Video) draws: the window is drawn
//! again for a new frame, and no component is rendered for it. On macOS and iOS the system's player (`AVPlayer`)
//! decodes and is heard, and the media's thread takes its frames and follows its clock; that player is the main
//! thread's, so a video opens there in a process whose main thread runs its loop, as an app's does. Its sound goes to
//! the system's default output, and the media's clock then follows what is heard. What holds a media tells it to play,
//! to pause, to go to a time, how fast to go and how loud to be, asks it where it is ([`Media::state`]), and is woken
//! when that changes in a way a clock does not tell: it opened, it ended, it failed.
//!
//! What happens to it is told to who listens, on the UI thread, once each time it happens: it opened
//! ([`Media::on_load`]), it failed ([`Media::on_error`]), it played to its end ([`Media::on_ended`]), it began or
//! stopped playing ([`Media::on_playing_change`]) and waiting for what it plays ([`Media::on_waiting_change`]).
//!
//! [`Media::open`] is what is seen, with its sound; [`Media::sound`] what is only heard: a song, a recording, a
//! message. A sound at an address is loaded whole through the app's loader and kept, so that it plays again at
//! once: in memory ([`sound_cache`]), or as a file in the folder of an app that turned the cache on the disk on
//! (`App::enable_media_disk_cache`), where it is there for the next run of the app too.
//!
//! `ui::VideoPlayer::source` and `ui::AudioPlayer::source` do all of this for a player. An app that draws its
//! own asks for a media itself.
//!
//! On Windows, where the `wgpu` renderer draws on Direct3D 12, a frame stays on the graphics card from the
//! decoder to the screen: decoded there, copied there once, drawn there. Elsewhere it is copied through memory
//! once.
//!
//! What is not here yet: a speed that keeps the pitch of the sound on Windows (faster is higher; Apple's players
//! keep it); a video at an address read through the app's loader (the system reads it itself where it can); on
//! macOS and iOS, a clip its track turns is drawn as it was filmed.

use std::{
  collections::VecDeque,
  sync::{Arc, Condvar, Mutex, MutexGuard},
};

pub use crate::core::{MediaError, MediaInfo};
use crate::{
  images::ImageData,
  resources::{Load, LoadError, LoadState, Loader, MediaDiskCache, Source, SourceKind},
  time::{Duration, Instant},
};

#[cfg(any(target_os = "macos", target_os = "ios"))]
mod apple;
mod cache;
mod driven;
mod events;
#[cfg(windows)]
mod mf;
mod session;

/// Has the next frame a media shows on a card find its device removed, as a card that is reset removes it.
#[cfg(all(test, windows))]
pub(crate) fn lose_card_for_test() {
  mf::LOSE_CARD.store(true, std::sync::atomic::Ordering::Release);
}
#[cfg(windows)]
mod output;
#[cfg(target_arch = "wasm32")]
mod web;

pub use cache::{DEFAULT_SOUND_CACHE_BYTES, SoundCache, sound_cache};
#[doc(hidden)]
pub use driven::{DrivenMedias, MediaDriver, drive_media};
pub(crate) use events::{LoopNoted, note_loop, tell_news};
pub use session::AudioCategory;
pub(crate) use session::set_category as set_audio_category;

/// What changed in a media is told to these, from its own thread.
type Waker = Arc<dyn Fn() + Send + Sync>;

/// Where a media is, and what it is: read with [`Media::state`].
#[derive(Clone, Debug, PartialEq)]
pub struct MediaState {
  /// How long it is, in seconds, once that is known. `None` for what has no end, and before it opened.
  pub duration: Option<f64>,
  /// Where it is, in seconds.
  pub position: f64,
  /// How large its picture is, once it opened. `None` for what has no picture, and for what is only heard.
  pub size: Option<(u32, u32)>,
  /// Whether it has sound, once it opened.
  pub sound: bool,
  /// How loud its sound is, from 0 to 1, and whether it is silenced.
  pub volume: f32,
  pub muted: bool,
  /// Whether it plays: it was told to, and has not ended or failed.
  pub playing: bool,
  /// Whether it waits for what it plays: opening, or reading what is not there yet.
  pub waiting: bool,
  /// Whether it played to its end.
  pub ended: bool,
  /// Why it cannot play, where it cannot: the kind of failure, which the app's
  /// [`Locale`](crate::core::Locale) puts into words ([`MediaWords::error`](crate::core::MediaWords::error)).
  pub error: Option<MediaError>,
  /// How fast it goes: 1 is as it was made.
  pub rate: f64,
}

/// What a load that failed is, as a media says it.
fn load_failed(error: LoadError) -> MediaError {
  match error {
    LoadError::NotFound => MediaError::NotFound,
    LoadError::Denied => MediaError::Denied,
    LoadError::Status(status) => MediaError::Server(status),
    LoadError::TooLarge { .. } => MediaError::TooLarge,
    LoadError::TimedOut => MediaError::TimedOut,
    LoadError::Unsupported(why) => MediaError::Unavailable(Arc::from(why)),
    LoadError::Io(said) => MediaError::Network(Arc::from(said)),
    LoadError::Cancelled => MediaError::Other(Arc::from("the load was stopped")),
  }
}

/// What the thread of a media is told.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Command {
  Play,
  Pause,
  Seek(f64),
  Rate(f64),
  Volume(f32),
  Muted(bool),
  Close,
}

/// What a media and its thread share.
pub(crate) struct Shared {
  inner: Mutex<Inner>,
  commands: Mutex<VecDeque<Command>>,
  /// Told when a command comes: the thread waits on it while it has nothing to decode.
  told: Condvar,
  wakers: Mutex<Vec<Waker>>,
  /// Its handlers of events and what it last told them, once something listens.
  listening: std::sync::OnceLock<Arc<events::Listening>>,
}

/// The state of a media, and the clock it is read from: where it was at `since`, going at `rate` while it plays.
pub(crate) struct Inner {
  pub duration: Option<f64>,
  pub size: Option<(u32, u32)>,
  pub sound: bool,
  /// How loud its sound is, from 0 to 1, and whether it is silenced: what its output starts with.
  pub volume: f32,
  pub muted: bool,
  /// Whether it opened and is ready to play: what it is told of is known.
  pub opened: bool,
  pub playing: bool,
  pub waiting: bool,
  pub ended: bool,
  pub error: Option<MediaError>,
  pub rate: f64,
  pub at: f64,
  pub since: Instant,
  /// How many times it was sent somewhere ([`Media::seek`]). The thread counts the ones it has done, and does
  /// not set the clock by what is heard while one is on its way: that would be where it was.
  pub sent: u64,
  pub frame: Option<ImageData>,
}

impl Inner {
  /// Where it is now, in seconds.
  pub fn position(&self) -> f64 {
    let moved = if self.playing && !self.waiting {
      self.since.elapsed().as_secs_f64() * self.rate
    } else {
      0.0
    };
    let position = (self.at + moved).max(0.0);
    match self.duration {
      Some(duration) => position.min(duration),
      None => position,
    }
  }

  /// Holds the clock at where it is, to start again from there: before what moves it changes.
  pub fn hold(&mut self) {
    self.at = self.position();
    self.since = Instant::now();
  }
}

impl Shared {
  /// What a media and its thread share, as a media starts: waiting to open, paused at its start.
  fn new() -> Arc<Self> {
    Arc::new(Self {
      inner: Mutex::new(Inner {
        duration: None,
        size: None,
        sound: false,
        volume: 1.0,
        muted: false,
        opened: false,
        playing: false,
        waiting: true,
        ended: false,
        error: None,
        rate: 1.0,
        at: 0.0,
        since: Instant::now(),
        sent: 0,
        frame: None,
      }),
      commands: Mutex::new(VecDeque::new()),
      told: Condvar::new(),
      wakers: Mutex::new(Vec::new()),
      listening: std::sync::OnceLock::new(),
    })
  }

  pub fn inner(&self) -> MutexGuard<'_, Inner> {
    self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
  }

  /// Tells who listens that the media changed.
  pub fn wake(&self) {
    let wakers = self
      .wakers
      .lock()
      .unwrap_or_else(|poisoned| poisoned.into_inner())
      .clone();
    for waker in wakers {
      waker();
    }
    self.noted();
  }

  /// Tells the thread that listens to the media's events that it changed, where something listens: its next turn
  /// looks at it.
  fn noted(&self) {
    if let Some(listening) = self.listening.get() {
      listening.note();
    }
  }

  /// The commands a driven media was told and has not done, taken where `take`.
  fn take_driven(&self, take: bool) -> Vec<Command> {
    let mut commands = self.commands.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    if take {
      commands.drain(..).collect()
    } else {
      commands.iter().copied().collect()
    }
  }

  /// It cannot play, and why.
  pub fn fail(&self, why: MediaError) {
    {
      let mut inner = self.inner();
      inner.hold();
      inner.error = Some(why);
      inner.playing = false;
      inner.waiting = false;
    }
    self.wake();
  }

  /// The commands that came, in order. With `wait`, it waits that long for one where there is none.
  pub fn take(&self, wait: Option<Duration>) -> Vec<Command> {
    let mut commands = self.commands.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    if commands.is_empty()
      && let Some(wait) = wait
    {
      commands = self
        .told
        .wait_timeout(commands, wait)
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .0;
    }
    commands.drain(..).collect()
  }

  fn tell(&self, command: Command) {
    self
      .commands
      .lock()
      .unwrap_or_else(|poisoned| poisoned.into_inner())
      .push_back(command);
    self.told.notify_all();
    // A page has no thread of the media's: what it is told is done now.
    #[cfg(target_arch = "wasm32")]
    web::told(self);
  }

  /// Whether nothing holds the media any more. It waits `wait` to be told so, and takes no command.
  fn closed(&self, wait: Duration) -> bool {
    let is = |commands: &VecDeque<Command>| commands.contains(&Command::Close);
    let commands = self.commands.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
    if is(&commands) {
      return true;
    }
    let commands = self
      .told
      .wait_timeout(commands, wait)
      .unwrap_or_else(|poisoned| poisoned.into_inner())
      .0;
    is(&commands)
  }
}

/// What tells the thread to end once nothing holds the media.
struct Handle {
  shared: Arc<Shared>,
}

impl Drop for Handle {
  fn drop(&mut self) {
    self.shared.tell(Command::Close);
  }
}

/// A video or a sound that plays. It is cheap to clone, and its thread ends when the last of it is dropped.
///
/// ```no_run
/// use lurq::{
///   components::Video,
///   media::Media,
///   resources::{Loader, Source},
/// };
///
/// # fn show(loader: &Loader) {
/// let media = Media::open(loader, &Source::file("clips/lake.mp4"));
/// media.play();
/// // Its picture, once it opened: drawn again by itself as frames come.
/// let picture = media.frame().map(Video::new);
/// let seconds = media.state().position;
///
/// // A song: only heard, and kept once it is loaded from its address.
/// let song = Media::sound(loader, &Source::url("https://example.com/song.mp3"));
/// song.set_volume(0.8);
/// song.play();
/// # }
/// ```
#[derive(Clone)]
pub struct Media(Arc<Handle>);

/// What a source is, for what opens it: the file it is read from, the bytes it is, or its address.
#[derive(Clone)]
pub(crate) enum Opened {
  File(std::path::PathBuf),
  /// The bytes, and the name they came by where they have one: its ending tells the decoder what they are.
  Bytes(Arc<[u8]>, Option<Arc<str>>),
  Url(Arc<str>),
}

/// What a media starts from: what is there to open, or a load of it that is on its way.
enum Asked {
  Opened(Opened),
  /// The file `disk` keeps under `key`: a sound that was loaded before, by this run of the app or an earlier.
  Kept {
    path: std::path::PathBuf,
    key: u64,
    disk: MediaDiskCache,
  },
  /// The bytes at `address`, loaded whole by the app's loader and kept under `key`: by `disk` where it is on,
  /// and in memory where it is not.
  Load {
    load: Load,
    key: u64,
    address: Arc<str>,
    disk: MediaDiskCache,
  },
}

/// Waits for `load` to end. `None` once nothing holds the media.
fn loaded(shared: &Arc<Shared>, load: &Load) -> Option<Result<Arc<[u8]>, LoadError>> {
  // The load wakes the thread when it ends, and the thread looks again a few times a second besides.
  load.wake_with({
    let shared = shared.clone();
    Arc::new(move || shared.told.notify_all())
  });
  loop {
    match load.state() {
      LoadState::Ready(bytes) => return Some(Ok(bytes)),
      LoadState::Failed(error) => return Some(Err(error)),
      LoadState::Loading { .. } => {}
    }
    if shared.closed(Duration::from_millis(50)) {
      return None;
    }
  }
}

/// What `asked` is once it is there to open: a load is waited for, and what it loaded is kept. With it, the
/// cache on the disk and the key of the file that is opened, where it is one that cache keeps. `None` where
/// there is nothing to open: the media was let go, or the load failed, which the media's state then says.
fn settle(shared: &Arc<Shared>, asked: Asked) -> Option<(Opened, Option<(MediaDiskCache, u64)>)> {
  match asked {
    Asked::Opened(opened) => Some((opened, None)),
    Asked::Kept { path, key, disk } => Some((Opened::File(path), Some((disk, key)))),
    Asked::Load {
      load,
      key,
      address,
      disk,
    } => match loaded(shared, &load)? {
      // The app's loader wrote the file as it loaded it; where it did not (the load was one that had ended
      // before the cache was told to forget), it is written now. The sound plays from the file, and its bytes
      // are let go.
      Ok(bytes) => Some(match disk.put(key, &address, &bytes) {
        Some(path) => (Opened::File(path), Some((disk, key))),
        // No cache on the disk, or one that cannot keep this: it is kept in memory.
        None => {
          sound_cache().put(key, bytes.clone());
          (Opened::Bytes(bytes, Some(address)), None)
        }
      }),
      // More than the loader reads whole, or a build that loads no address: the system reads it itself, and
      // nothing of it is kept.
      Err(LoadError::TooLarge { .. } | LoadError::Unsupported(_)) => Some((Opened::Url(address), None)),
      Err(error) => {
        shared.fail(load_failed(error));
        None
      }
    },
  }
}

/// The life of a media on its thread: `asked` is waited for, and `run` plays it until nothing holds the media.
#[cfg_attr(not(any(windows, target_os = "macos", target_os = "ios")), allow(dead_code))]
fn live(shared: &Arc<Shared>, asked: Asked, heard: bool, run: impl FnOnce(&Arc<Shared>, Opened, bool)) {
  let Some((opened, kept)) = settle(shared, asked) else {
    return;
  };
  run(shared, opened, heard);
  // A file of the cache on the disk that could not be played is let go: it has the length it was written
  // with, and is not what was written. The next try loads it anew.
  if let Some((disk, key)) = kept
    && shared.inner().error.is_some()
  {
    disk.forget_key(key);
  }
}

impl Media {
  /// Opens `source` with the app's `loader` and shows its first frame, paused at its start: what is seen, with
  /// its sound where it has some. It never fails here: what cannot be opened says why in its
  /// [`state`](Self::state).
  pub fn open(loader: &Loader, source: &Source) -> Self {
    Self::start_from(loader, source, false)
  }

  /// Opens `source` as what is only heard: a song, a recording, a message. Where it has a picture too, the
  /// picture is not decoded.
  ///
  /// At an address it is loaded whole through the app's `loader` (with its headers, its timeout and what the
  /// loader allows) and kept: played again, it starts at once and asks the network for nothing. It is kept in
  /// memory ([`sound_cache`]) for the run of the app; where the loader's cache on the disk is on
  /// ([`Loader::enable_media_disk_cache`]), it is kept there as a file, for the next run too, and plays from the
  /// file. What is larger than the loader reads whole is read by the system itself as it plays, and not kept.
  /// While it loads, its state says it waits.
  pub fn sound(loader: &Loader, source: &Source) -> Self {
    Self::start_from(loader, source, true)
  }

  fn of(shared: Arc<Shared>) -> Self {
    Self(Arc::new(Handle { shared }))
  }

  fn start_from(loader: &Loader, source: &Source, heard: bool) -> Self {
    let shared = Shared::new();
    // A test drives it: nothing is opened.
    if driven::take(&shared) {
      return Self::of(shared);
    }
    let asked = match &source.kind {
      SourceKind::File(path) => Ok(Asked::Opened(Opened::File(path.clone()))),
      SourceKind::Resource(resource) => Ok(Asked::Opened(Opened::File(loader.resource_path(resource)))),
      SourceKind::Bytes(bytes) => Ok(Asked::Opened(Opened::Bytes(bytes.clone(), None))),
      SourceKind::Url(address) if !loader.allows(address) => Err(MediaError::Denied),
      // A browser reads the address itself as it plays: nothing is loaded first, nor kept.
      #[cfg(target_arch = "wasm32")]
      SourceKind::Url(address) => Ok(Asked::Opened(Opened::Url(address.clone()))),
      // A sound is loaded whole and kept; kept already, it is there: as a file where the app's cache on the
      // disk is on, in memory where it is not.
      #[cfg(not(target_arch = "wasm32"))]
      SourceKind::Url(address) if heard => {
        let (key, disk) = (source.cache_key(), loader.media_disk_cache());
        sound_cache().follow(disk);
        Ok(if let Some(path) = disk.file(key) {
          Asked::Kept {
            path,
            key,
            disk: disk.clone(),
          }
        } else if let Some(bytes) = sound_cache().get(key) {
          Asked::Opened(Opened::Bytes(bytes, Some(address.clone())))
        } else {
          Asked::Load {
            load: loader.load(source),
            key,
            address: address.clone(),
            disk: disk.clone(),
          }
        })
      }
      #[cfg(not(target_arch = "wasm32"))]
      SourceKind::Url(address) => Ok(Asked::Opened(Opened::Url(address.clone()))),
    };
    match asked {
      Ok(asked) => Self::start(&shared, asked, heard),
      Err(why) => shared.fail(why),
    }
    Self::of(shared)
  }

  #[cfg(windows)]
  fn start(shared: &Arc<Shared>, asked: Asked, heard: bool) {
    let thread = shared.clone();
    let spawned = std::thread::Builder::new()
      .name("lurq-media".to_owned())
      .spawn(move || live(&thread, asked, heard, mf::run));
    if spawned.is_err() {
      shared.fail(MediaError::Other(Arc::from(
        "a thread to decode on could not be started",
      )));
    }
  }

  #[cfg(any(target_os = "macos", target_os = "ios"))]
  fn start(shared: &Arc<Shared>, asked: Asked, heard: bool) {
    let thread = shared.clone();
    let spawned = std::thread::Builder::new()
      .name("lurq-media".to_owned())
      .spawn(move || live(&thread, asked, heard, apple::run));
    if spawned.is_err() {
      shared.fail(MediaError::Other(Arc::from("a thread to play on could not be started")));
    }
  }

  /// The page's `<audio>`: see [`web`].
  #[cfg(target_arch = "wasm32")]
  fn start(shared: &Arc<Shared>, asked: Asked, heard: bool) {
    let opened = match asked {
      Asked::Opened(opened) => opened,
      Asked::Kept { path, .. } => Opened::File(path),
      Asked::Load { address, .. } => Opened::Url(address),
    };
    web::start(shared, opened, heard);
  }

  #[cfg(not(any(windows, target_os = "macos", target_os = "ios", target_arch = "wasm32")))]
  fn start(shared: &Arc<Shared>, _: Asked, _: bool) {
    shared.fail(MediaError::Unavailable(Arc::from(
      "this build has no decoder for this system yet",
    )));
  }

  fn shared(&self) -> &Shared {
    &self.0.shared
  }

  /// Where it is and what it is, now.
  pub fn state(&self) -> MediaState {
    let inner = self.shared().inner();
    MediaState {
      duration: inner.duration,
      position: inner.position(),
      size: inner.size,
      sound: inner.sound,
      volume: inner.volume,
      muted: inner.muted,
      playing: inner.playing,
      waiting: inner.waiting,
      ended: inner.ended,
      error: inner.error.clone(),
      rate: inner.rate,
    }
  }

  /// Its picture, once it opened: an image that holds the frame of the moment, which a
  /// [`Video`](crate::components::Video) draws. The same image for as long as the media lives.
  pub fn frame(&self) -> Option<ImageData> {
    self.shared().inner().frame.clone()
  }

  /// Plays from where it is; from its start where it had ended.
  pub fn play(&self) {
    self.shared().tell(Command::Play);
  }

  /// Stops where it is. Its state says so at once: the thread stops decoding when it hears.
  pub fn pause(&self) {
    {
      let mut inner = self.shared().inner();
      inner.hold();
      inner.playing = false;
    }
    self.shared().noted();
    self.shared().tell(Command::Pause);
  }

  /// Goes to `seconds` and shows the frame there, playing or not. Its state is at that time at once, so what
  /// draws where it is (a seek bar being dragged) does not see it go back: the frame comes when it is decoded.
  pub fn seek(&self, seconds: f64) {
    if !seconds.is_finite() {
      return;
    }
    let to = {
      let mut inner = self.shared().inner();
      let to = match inner.duration {
        Some(duration) => seconds.clamp(0.0, duration),
        None => seconds.max(0.0),
      };
      inner.at = to;
      inner.since = Instant::now();
      inner.ended = false;
      inner.sent += 1;
      to
    };
    self.shared().noted();
    self.shared().tell(Command::Seek(to));
  }

  /// How fast it goes: 1 is as it was made. Nothing that is not a speed is taken.
  pub fn set_rate(&self, rate: f64) {
    if rate.is_finite() && rate > 0.0 {
      self.shared().tell(Command::Rate(rate));
    }
  }

  /// How loud its sound is, from 0 (nothing) to 1 (as it was made): of this media alone, and at once. Nothing
  /// that is not a number is taken.
  pub fn set_volume(&self, volume: f32) {
    if volume.is_finite() {
      let volume = volume.clamp(0.0, 1.0);
      self.shared().inner().volume = volume;
      self.shared().tell(Command::Volume(volume));
    }
  }

  /// Silences its sound, or lets it be heard again as loud as it was.
  pub fn set_muted(&self, muted: bool) {
    self.shared().inner().muted = muted;
    self.shared().tell(Command::Muted(muted));
  }

  /// Calls `wake` when the media changes in a way its clock does not tell: it opened, it ended, it failed, it
  /// went to another time. From the media's own thread.
  pub fn on_change(&self, wake: impl Fn() + Send + Sync + 'static) {
    self
      .shared()
      .wakers
      .lock()
      .unwrap_or_else(|poisoned| poisoned.into_inner())
      .push(Arc::new(wake));
  }

  /// Calls `handler` once it opened and is ready to play, with its length, its picture's size and whether it has
  /// sound. On the UI thread, as the events below: see [`on_playing_change`](Self::on_playing_change).
  pub fn on_load(&self, handler: impl Fn(&MediaInfo) + Send + Sync + 'static) {
    self.listening().handlers().load.push(Arc::new(handler));
  }

  /// Calls `handler` once it cannot play, with why: a kind, which the app's
  /// [`Locale`](crate::core::Locale) puts into words ([`MediaWords::error`](crate::core::MediaWords::error)). A
  /// media that failed stays failed: one that tries again is opened anew.
  pub fn on_error(&self, handler: impl Fn(&MediaError) + Send + Sync + 'static) {
    self.listening().handlers().error.push(Arc::new(handler));
  }

  /// Calls `handler` each time it played to its end: again only after it played again.
  pub fn on_ended(&self, handler: impl Fn() + Send + Sync + 'static) {
    self.listening().handlers().ended.push(Arc::new(handler));
  }

  /// Calls `handler` with whether it plays, each time that changes once it opened: it was told to play or to
  /// pause, it ended, it failed.
  ///
  /// The events of a media are told on the thread that first listened to it, which is the UI thread: the media's
  /// own thread wakes the loops of that thread's windows, and the next turn of each tells what changed since it last
  /// told, in the order a media lives it (it opened, it waits or not, it plays or not, it ended, it failed), once
  /// each. A handler may play, pause and seek. What changed before it was listened to is told in the next turn. A
  /// second handler is called after the first.
  pub fn on_playing_change(&self, handler: impl Fn(bool) + Send + Sync + 'static) {
    self.listening().handlers().playing.push(Arc::new(handler));
  }

  /// Calls `handler` with whether it waits for what it plays (an address that is read slower than it plays), each
  /// time that changes once it opened: `true` when it began waiting, `false` when it goes on. Opening is not
  /// waiting: what opens is told by [`on_load`](Self::on_load).
  pub fn on_waiting_change(&self, handler: impl Fn(bool) + Send + Sync + 'static) {
    self.listening().handlers().waiting.push(Arc::new(handler));
  }

  fn listening(&self) -> &Arc<events::Listening> {
    events::Listening::of(&self.0.shared)
  }
}