tuitube 0.5.0

YouTube in your terminal: a vim-style client with local subscriptions, built on yt-dlp and mpv
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! Playing a video: mpv, run as a separate program, given the stream URLs
//! tuitube resolved. Video opens in mpv's own window; sound only plays with
//! no window, controlled from tuitube's player bar.
//!
//! mpv starts with `--no-config` (none of the user's mpv.conf, input.conf
//! or scripts), `--terminal=no` (it never touches tuitube's terminal, and
//! never prints the signed stream URLs), `--ytdl=no` (it doesn't run a
//! second yt-dlp of its own) and `--tls-verify=yes` (mpv's own default
//! accepts any certificate). On Unix it's controlled over one end of a
//! socket pair handed to it as file descriptor 3
//! (`--input-ipc-client=fd://3`): there's no socket file another program
//! could connect to, and mpv quits when tuitube's end closes. mpv's control
//! protocol can run programs, so it must never be reachable by anyone else.
//!
//! On Unix, mpv starts idle with nothing about the video on its command
//! line, which every user of the computer can read (`ps`): the title, the
//! user agent and the URLs go over the socket. Windows has no socket yet,
//! so they're arguments there, after `--`; other users can't read another
//! user's command line on Windows.

use std::path::Path;
use std::process::Stdio;
use std::time::Duration;

use anyhow::{Context, Result};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::oneshot;

use crate::chapters::Chapter;
use crate::tools::{self, Tools};
use crate::ytdlp::Streams;

/// How long mpv has to quit when asked, before it's killed.
const QUIT_GRACE: Duration = Duration::from_secs(3);

/// Something mpv said, for the playback numbered `play`.
#[derive(Debug)]
pub struct PlayerEvent {
    pub play: u64,
    pub kind: PlayerEventKind,
}

#[derive(Debug, PartialEq)]
#[cfg_attr(not(unix), allow(dead_code))]
pub enum PlayerEventKind {
    Position(f64),
    Duration(f64),
    Paused(bool),
    /// The video played to its end: mpv's `end-file` with reason `eof`, not
    /// `quit` (its window closed, or tuitube stopped it) or `error`.
    Ended,
    /// mpv exited, after the video ended or its window was closed.
    Exited,
}

pub struct Player {
    pub play: u64,
    /// tuitube can pause, seek and follow the playback: over mpv's socket,
    /// which Windows doesn't have yet. A field, not `cfg!(unix)` where it's
    /// asked, so tests check both ways on any system
    /// ([`Player::set_controllable`]).
    controllable: bool,
    #[cfg(unix)]
    control: Option<tokio::sync::mpsc::UnboundedSender<String>>,
    /// Tells the task that owns mpv's process to end it.
    stop: Option<oneshot::Sender<()>>,
}

pub struct Start<'a> {
    pub mpv: &'a Path,
    pub tools: &'a Tools,
    pub streams: &'a Streams,
    pub title: &'a str,
    pub start_at: Option<f64>,
    pub audio_only: bool,
    /// The subtitles' URL (WebVTT on YouTube's server), if any, and
    /// whether they show at first.
    pub subtitles: Option<&'a str>,
    pub subtitles_shown: bool,
}

impl Player {
    pub fn start(
        play: u64,
        start: Start,
        tx: UnboundedSender<crate::app::AppEvent>,
    ) -> Result<Self> {
        let mut command = tokio::process::Command::new(start.mpv);
        command
            .args(args(&start))
            .env_clear()
            .envs(tools::child_env(start.tools))
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            // If tuitube ends without stopping it, mpv goes too.
            .kill_on_drop(true);
        if let Some(home) = dirs::home_dir() {
            command.current_dir(home);
        }

        #[cfg(unix)]
        let (child, control) = {
            use std::os::fd::AsRawFd;
            let (ours, theirs) = std::os::unix::net::UnixStream::pair()?;
            let fd = theirs.as_raw_fd();
            // SAFETY: only dup2 or fcntl runs between fork and exec, both
            // async-signal-safe. dup2 also clears close-on-exec on fd 3.
            unsafe {
                command.pre_exec(move || {
                    let ok = if fd == 3 {
                        libc::fcntl(3, libc::F_SETFD, 0) != -1
                    } else {
                        libc::dup2(fd, 3) != -1
                    };
                    if !ok {
                        return Err(std::io::Error::last_os_error());
                    }
                    Ok(())
                });
            }
            let child = command.spawn().context("cannot start mpv")?;
            drop(theirs);
            ours.set_nonblocking(true)?;
            let stream = tokio::net::UnixStream::from_std(ours)?;
            let (control_tx, control_rx) = tokio::sync::mpsc::unbounded_channel();
            spawn_ipc(play, stream, control_rx, tx.clone());
            for line in commands(&start) {
                let _ = control_tx.send(line);
            }
            (child, control_tx)
        };
        #[cfg(not(unix))]
        let child = command.spawn().context("cannot start mpv")?;

        let (stop_tx, stop_rx) = oneshot::channel();
        tokio::spawn(own(play, child, stop_rx, tx));
        Ok(Self {
            play,
            controllable: cfg!(unix),
            #[cfg(unix)]
            control: Some(control),
            stop: Some(stop_tx),
        })
    }

    /// A player with no mpv behind it, for the demo's player bar.
    pub fn detached(play: u64) -> Self {
        Self {
            play,
            // In tests, as on Unix on every system: a test of Windows'
            // playback says so (`set_controllable`), so no test passes on
            // one system and fails on another.
            controllable: cfg!(unix) || cfg!(test),
            #[cfg(unix)]
            control: None,
            stop: None,
        }
    }

    /// Whether an mpv plays it: not the demo's.
    pub fn has_mpv(&self) -> bool {
        self.stop.is_some()
    }

    /// Whether tuitube can pause, seek and follow the playback (not on
    /// Windows yet).
    pub fn controllable(&self) -> bool {
        self.controllable
    }

    /// Plays as on Unix (`true`) or as on Windows (`false`), whichever
    /// system runs the test.
    #[cfg(test)]
    pub fn set_controllable(&mut self, controllable: bool) {
        self.controllable = controllable;
    }

    fn send(&self, command: serde_json::Value) {
        #[cfg(unix)]
        if let Some(control) = &self.control {
            let _ = control.send(line(command));
        }
        #[cfg(not(unix))]
        let _ = command;
    }

    pub fn toggle_pause(&self) {
        self.send(serde_json::json!(["cycle", "pause"]));
    }

    pub fn seek(&self, seconds: i32) {
        self.send(serde_json::json!(["seek", seconds, "relative"]));
    }

    /// Goes to `seconds` from the start, to the frame (a SponsorBlock skip
    /// lands where the segment ends, not at the keyframe before).
    pub fn seek_to(&self, seconds: f64) {
        if seconds.is_finite() && seconds >= 0.0 {
            self.send(serde_json::json!(["seek", seconds, "absolute+exact"]));
        }
    }

    /// Shows or hides the subtitles.
    pub fn show_subtitles(&self, shown: bool) {
        self.send(serde_json::json!(["set_property", "sub-visibility", shown]));
    }

    /// Gives mpv the video's chapters, for the marks on its window's seek
    /// bar and its own chapter keys. mpv keeps only the ones before the
    /// length it knows, so this waits for mpv to say the length. Titles go
    /// as JSON strings, as the video's does.
    pub fn set_chapters(&self, chapters: &[Chapter]) {
        self.send(chapters_command(chapters));
    }

    /// Stops playback: mpv is asked to quit, and killed if it hasn't
    /// within `QUIT_GRACE`.
    pub fn stop(&mut self) {
        self.send(serde_json::json!(["quit"]));
        #[cfg(unix)]
        {
            // Closing our end makes mpv quit even if it missed the command.
            self.control = None;
        }
        if let Some(stop) = self.stop.take() {
            let _ = stop.send(());
        }
    }
}

impl Drop for Player {
    fn drop(&mut self) {
        self.stop();
    }
}

/// Owns mpv's process: waits for it to end, or for `stop`, then gives it
/// `QUIT_GRACE` before killing it through its handle (never by process id,
/// which another program may have by then). Says when it's gone.
async fn own(
    play: u64,
    mut child: tokio::process::Child,
    stop: oneshot::Receiver<()>,
    tx: UnboundedSender<crate::app::AppEvent>,
) {
    tokio::select! {
        _ = child.wait() => {}
        // Asked to stop, or the Player is gone.
        _ = stop => {
            // Windows has no way to ask mpv to quit yet.
            let grace = if cfg!(unix) { QUIT_GRACE } else { Duration::ZERO };
            if tokio::time::timeout(grace, child.wait()).await.is_err() {
                let _ = child.start_kill();
                let _ = child.wait().await;
            }
        }
    }
    let _ = tx.send(crate::app::AppEvent::Player(PlayerEvent {
        play,
        kind: PlayerEventKind::Exited,
    }));
}

/// mpv's arguments. Nothing about the video is in them on Unix; on Windows
/// the title, user agent and start go in options, the sound's URL in
/// `--audio-file=` and the picture's after `--`.
fn args(start: &Start) -> Vec<String> {
    let mut args: Vec<String> = [
        "--no-config",
        "--load-scripts=no",
        "--terminal=no",
        "--ytdl=no",
        "--tls-verify=yes",
        "--keep-open=no",
        "--save-position-on-quit=no",
        "--resume-playback=no",
        "--hwdec=auto-safe",
    ]
    .map(String::from)
    .into();
    if start.audio_only {
        args.push("--no-video".into());
        args.push("--force-window=no".into());
    } else {
        args.push("--force-window=immediate".into());
    }
    if cfg!(unix) {
        // Idle until the file comes over the socket, then quit after it.
        args.push("--idle=once".into());
        args.push("--input-ipc-client=fd://3".into());
        return args;
    }
    args.push("--idle=no".into());
    for (name, value) in settings(start) {
        args.push(format!("--{name}={value}"));
    }
    if let Some(audio) = &start.streams.audio {
        args.push(format!("--audio-file={audio}"));
    }
    if let Some(subtitles) = start.subtitles {
        args.push(format!("--sub-file={subtitles}"));
    }
    args.push("--".into());
    args.push(start.streams.video.clone());
    args
}

/// The options that describe this playback: its title (in mpv's window and
/// media controls), the user agent the streams expect, where to start.
fn settings(start: &Start) -> Vec<(&'static str, String)> {
    let title = crate::video::one_line(start.title, 150);
    let mut settings = vec![
        ("force-media-title", title.clone()),
        // The window title expands `${…}` properties; `$$` is a plain `$`.
        ("title", format!("{} — tuitube", title.replace('$', "$$"))),
    ];
    if let Some(ua) = &start.streams.user_agent {
        settings.push(("user-agent", crate::video::one_line(ua, 300)));
    }
    if let Some(at) = start.start_at.filter(|s| s.is_finite() && *s > 0.0) {
        settings.push(("start", format!("{at:.0}")));
    }
    if start.subtitles.is_some() {
        let shown = if start.subtitles_shown { "yes" } else { "no" };
        settings.push(("sub-visibility", shown.into()));
    }
    settings
}

/// mpv's command setting its list of chapters to `chapters`.
fn chapters_command(chapters: &[Chapter]) -> serde_json::Value {
    let list: Vec<serde_json::Value> = chapters
        .iter()
        .map(|c| serde_json::json!({ "title": c.title, "time": c.start }))
        .collect();
    serde_json::json!(["set_property", "chapter-list", list])
}

/// One command for mpv's control socket, as a line of JSON: strings are
/// JSON strings, so a title can't break out of its place.
#[cfg_attr(not(unix), allow(dead_code))]
fn line(command: serde_json::Value) -> String {
    format!("{}\n", serde_json::json!({ "command": command }))
}

/// What's sent over the socket to play the video: the properties tuitube
/// follows, the settings (with `set`, which takes the value as is), the
/// sound's URL added to the list of audio files as one item (and the
/// subtitles' to the subtitle files), then the picture's URL.
#[cfg_attr(not(unix), allow(dead_code))]
fn commands(start: &Start) -> Vec<String> {
    let mut commands: Vec<String> = [(1, "time-pos"), (2, "duration"), (3, "pause")]
        .into_iter()
        .map(|(id, property)| line(serde_json::json!(["observe_property", id, property])))
        .collect();
    for (name, value) in settings(start) {
        commands.push(line(serde_json::json!(["set", name, value])));
    }
    if let Some(audio) = &start.streams.audio {
        commands.push(line(serde_json::json!([
            "change-list",
            "audio-files",
            "append",
            audio
        ])));
    }
    // Loaded with the video, as one item of the list: mpv selects it.
    if let Some(subtitles) = start.subtitles {
        commands.push(line(serde_json::json!([
            "change-list",
            "sub-files",
            "append",
            subtitles
        ])));
    }
    commands.push(line(serde_json::json!([
        "loadfile",
        start.streams.video,
        "replace"
    ])));
    commands
}

#[cfg(unix)]
fn spawn_ipc(
    play: u64,
    stream: tokio::net::UnixStream,
    mut control: tokio::sync::mpsc::UnboundedReceiver<String>,
    tx: UnboundedSender<crate::app::AppEvent>,
) {
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
    let (read, mut write) = stream.into_split();
    tokio::spawn(async move {
        while let Some(line) = control.recv().await {
            if write.write_all(line.as_bytes()).await.is_err() {
                break;
            }
        }
        // Dropping the writer closes our end: mpv quits.
    });
    tokio::spawn(async move {
        let mut lines = BufReader::new(read).lines();
        while let Ok(Some(line)) = lines.next_line().await {
            if line.len() > 64 * 1024 {
                continue;
            }
            if let Some(kind) = parse_event(&line) {
                let _ = tx.send(crate::app::AppEvent::Player(PlayerEvent { play, kind }));
            }
        }
    });
}

#[derive(serde::Deserialize)]
#[cfg(any(unix, test))]
struct IpcMessage {
    event: Option<String>,
    name: Option<String>,
    data: Option<serde_json::Value>,
    reason: Option<String>,
}

/// One of mpv's messages, if it's one tuitube follows.
#[cfg(any(unix, test))]
fn parse_event(line: &str) -> Option<PlayerEventKind> {
    let message: IpcMessage = serde_json::from_str(line).ok()?;
    if message.event.as_deref() == Some("end-file") {
        return (message.reason.as_deref() == Some("eof")).then_some(PlayerEventKind::Ended);
    }
    if message.event.as_deref() != Some("property-change") {
        return None;
    }
    let data = message.data?;
    match message.name.as_deref()? {
        "time-pos" => data.as_f64().map(PlayerEventKind::Position),
        "duration" => data.as_f64().map(PlayerEventKind::Duration),
        "pause" => data.as_bool().map(PlayerEventKind::Paused),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn streams() -> Streams {
        Streams {
            video: "https://rr1.googlevideo.com/videoplayback?v=1".into(),
            audio: Some("https://rr1.googlevideo.com/videoplayback?a=1,b=2".into()),
            user_agent: Some("Mozilla/5.0\nX-Injected: yes".into()),
            duration: Some(10.0),
            chapters: Vec::new(),
            quality: None,
            info: None,
            captions: Vec::new(),
        }
    }

    fn start<'a>(tools: &'a Tools, streams: &'a Streams, title: &'a str) -> Start<'a> {
        Start {
            mpv: Path::new("/usr/bin/mpv"),
            tools,
            streams,
            title,
            start_at: Some(42.4),
            audio_only: false,
            subtitles: None,
            subtitles_shown: false,
        }
    }

    #[cfg(unix)]
    #[test]
    fn nothing_about_the_video_is_on_mpvs_command_line() {
        let (tools, streams) = (Tools::default(), streams());
        let args = args(&start(&tools, &streams, "My secret video"));
        assert_eq!(args[0], "--no-config");
        for flag in [
            "--terminal=no",
            "--ytdl=no",
            "--tls-verify=yes",
            "--idle=once",
        ] {
            assert!(args.contains(&flag.to_string()), "{flag}");
        }
        let all = args.join(" ");
        assert!(!all.contains("secret"), "{all}");
        assert!(!all.contains("googlevideo"), "{all}");
        assert!(!all.contains("Mozilla"), "{all}");
    }

    #[test]
    fn the_socket_gets_the_video_as_json_strings() {
        let (tools, streams) = (Tools::default(), streams());
        let title = "\"]}{\"command\":[\"run\",\"sh\"]} ${path} --script=x";
        let lines = commands(&start(&tools, &streams, title));
        for line in &lines {
            let parsed: serde_json::Value = serde_json::from_str(line.trim_end()).unwrap();
            assert!(parsed["command"].is_array(), "{line}");
            assert!(!line.trim_end().contains('\n'));
        }
        let set = |name: &str| {
            lines
                .iter()
                .map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap())
                .find(|v| v["command"][0] == "set" && v["command"][1] == name)
                .map(|v| v["command"][2].as_str().unwrap().to_string())
        };
        assert_eq!(
            set("force-media-title").unwrap(),
            title,
            "kept whole, as one string"
        );
        assert!(
            set("title").unwrap().contains("$${path}"),
            "no property expansion"
        );
        assert_eq!(
            set("user-agent").unwrap(),
            "Mozilla/5.0 X-Injected: yes",
            "one line"
        );
        assert_eq!(set("start").unwrap(), "42");
        let last: serde_json::Value = serde_json::from_str(lines.last().unwrap()).unwrap();
        assert_eq!(last["command"][0], "loadfile");
        assert_eq!(last["command"][1], streams.video.as_str());
        let audio: serde_json::Value = serde_json::from_str(&lines[lines.len() - 2]).unwrap();
        assert_eq!(
            audio["command"][2], "append",
            "one item: commas don't split it"
        );
    }

    #[test]
    fn subtitles_go_in_with_the_video_shown_or_not() {
        let (tools, streams) = (Tools::default(), streams());
        let mut start = start(&tools, &streams, "A video");
        let vtt = "https://www.youtube.com/api/timedtext?v=x&lang=en,fr&fmt=vtt";
        start.subtitles = Some(vtt);
        let lines: Vec<serde_json::Value> = commands(&start)
            .iter()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        let sub = lines
            .iter()
            .find(|v| v["command"][1] == "sub-files")
            .expect("the subtitles");
        assert_eq!(
            sub["command"],
            serde_json::json!(["change-list", "sub-files", "append", vtt]),
            "one item: the comma doesn't split it"
        );
        let shown = lines
            .iter()
            .find(|v| v["command"][0] == "set" && v["command"][1] == "sub-visibility")
            .unwrap();
        assert_eq!(shown["command"][2], "no");
        assert_eq!(lines.last().unwrap()["command"][0], "loadfile");
        start.subtitles = None;
        let none = commands(&start).join("");
        assert!(!none.contains("sub-"), "{none}");
    }

    #[test]
    fn chapters_go_to_mpv_as_one_command_of_json_strings() {
        let chapters = [
            Chapter {
                start: 0.0,
                title: "Intro".into(),
            },
            Chapter {
                start: 83.5,
                title: "\"]}\n{\"command\":[\"run\",\"sh\"]} ${path}".into(),
            },
        ];
        let sent = line(chapters_command(&chapters));
        assert_eq!(sent.matches('\n').count(), 1, "one line: {sent}");
        let parsed: serde_json::Value = serde_json::from_str(sent.trim_end()).unwrap();
        let command = &parsed["command"];
        assert_eq!(command[0], "set_property");
        assert_eq!(command[1], "chapter-list");
        assert_eq!(command[2][1]["time"], 83.5);
        assert_eq!(
            command[2][1]["title"],
            chapters[1].title.as_str(),
            "kept whole"
        );
        assert_eq!(command.as_array().unwrap().len(), 3);
    }

    #[test]
    fn only_followed_properties_become_events() {
        let pos = r#"{"event":"property-change","id":1,"name":"time-pos","data":12.5}"#;
        assert_eq!(parse_event(pos), Some(PlayerEventKind::Position(12.5)));
        let pause = r#"{"event":"property-change","id":3,"name":"pause","data":true}"#;
        assert_eq!(parse_event(pause), Some(PlayerEventKind::Paused(true)));
        assert_eq!(
            parse_event(r#"{"event":"property-change","name":"time-pos","data":null}"#),
            None
        );
        assert_eq!(parse_event(r#"{"request_id":0,"error":"success"}"#), None);
        assert_eq!(parse_event("not json"), None);
    }

    #[test]
    fn only_playing_to_the_end_counts_as_ended() {
        let end = |reason: &str| {
            parse_event(&format!(
                r#"{{"event":"end-file","reason":"{reason}","playlist_entry_id":1}}"#
            ))
        };
        assert_eq!(end("eof"), Some(PlayerEventKind::Ended));
        for reason in ["quit", "stop", "error", "redirect", "unknown"] {
            assert_eq!(end(reason), None, "{reason}");
        }
        assert_eq!(parse_event(r#"{"event":"end-file"}"#), None);
    }
}

/// With the real mpv: `cargo test -- --ignored live`.
#[cfg(all(test, unix))]
mod live {
    use super::*;
    use crate::app::AppEvent;

    #[tokio::test]
    #[ignore = "runs mpv"]
    async fn live_mpv_plays_what_the_socket_sends_and_stops() {
        let tools = Tools::find(None, None, None);
        let mpv = tools.mpv.clone().expect("mpv is installed");
        // Silence made by mpv itself, with a second silent sound added the
        // way a stream's separate sound is: no network, no sound.
        let streams = Streams {
            video: "av://lavfi:anullsrc=d=5".into(),
            audio: Some("av://lavfi:anullsrc=d=5".into()),
            user_agent: Some("tuitube-test".into()),
            duration: None,
            chapters: Vec::new(),
            quality: None,
            info: None,
            captions: Vec::new(),
        };
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let start = Start {
            mpv: &mpv,
            tools: &tools,
            streams: &streams,
            title: "silence, with \"quotes\" and ${path}",
            start_at: Some(1.0),
            audio_only: true,
            subtitles: None,
            subtitles_shown: false,
        };
        let mut player = Player::start(7, start, tx).unwrap();
        let mut positions = Vec::new();
        let mut exited = false;
        let mut ended = false;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
        while let Ok(Some(event)) = tokio::time::timeout_at(deadline, rx.recv()).await {
            let AppEvent::Player(event) = event else {
                continue;
            };
            assert_eq!(event.play, 7);
            match event.kind {
                PlayerEventKind::Position(at) => {
                    positions.push(at);
                    if positions.len() == 3 {
                        player.stop();
                    }
                }
                PlayerEventKind::Ended => ended = true,
                PlayerEventKind::Exited => {
                    exited = true;
                    break;
                }
                _ => {}
            }
        }
        assert!(
            !positions.is_empty(),
            "nothing played: the socket's file didn't load"
        );
        assert!(positions[0] >= 0.9, "started at --start: {positions:?}");
        assert!(exited, "mpv didn't quit");
        assert!(!ended, "stopped isn't played to the end");
    }

    #[tokio::test]
    #[ignore = "runs mpv"]
    async fn live_mpv_seeks_to_where_a_skipped_segment_ends() {
        let tools = Tools::find(None, None, None);
        let mpv = tools.mpv.clone().expect("mpv is installed");
        let streams = Streams {
            video: "av://lavfi:anullsrc=d=10".into(),
            audio: None,
            user_agent: None,
            duration: None,
            chapters: Vec::new(),
            quality: None,
            info: None,
            captions: Vec::new(),
        };
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let start = Start {
            mpv: &mpv,
            tools: &tools,
            streams: &streams,
            title: "ten seconds of silence",
            start_at: None,
            audio_only: true,
            subtitles: None,
            subtitles_shown: false,
        };
        let mut player = Player::start(9, start, tx).unwrap();
        let mut sought = None;
        let mut landed = None;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
        while let Ok(Some(event)) = tokio::time::timeout_at(deadline, rx.recv()).await {
            let AppEvent::Player(event) = event else {
                continue;
            };
            match event.kind {
                PlayerEventKind::Position(at) if sought.is_none() && at < 1.0 => {
                    player.seek_to(6.5);
                    sought = Some(std::time::Instant::now());
                }
                PlayerEventKind::Position(at) if at >= 6.5 && landed.is_none() => {
                    landed = sought.map(|t| (at, t.elapsed()));
                    player.stop();
                }
                PlayerEventKind::Exited => break,
                _ => {}
            }
        }
        let (at, after) = landed.expect("the seek didn't happen");
        // Played there in real time, it would take 5.5 s or more.
        assert!(after < Duration::from_secs(3), "{after:?}");
        assert!(at < 8.0, "landed at {at}");
    }

    #[tokio::test]
    #[ignore = "runs mpv"]
    async fn live_mpv_says_when_a_video_plays_to_its_end() {
        let tools = Tools::find(None, None, None);
        let mpv = tools.mpv.clone().expect("mpv is installed");
        let streams = Streams {
            video: "av://lavfi:anullsrc=d=2".into(),
            audio: None,
            user_agent: None,
            duration: None,
            chapters: Vec::new(),
            quality: None,
            info: None,
            captions: Vec::new(),
        };
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let start = Start {
            mpv: &mpv,
            tools: &tools,
            streams: &streams,
            title: "two seconds of silence",
            start_at: None,
            audio_only: true,
            subtitles: None,
            subtitles_shown: false,
        };
        let _player = Player::start(8, start, tx).unwrap();
        let mut kinds = Vec::new();
        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
        while let Ok(Some(event)) = tokio::time::timeout_at(deadline, rx.recv()).await {
            if let AppEvent::Player(event) = event {
                match event.kind {
                    PlayerEventKind::Ended | PlayerEventKind::Exited => kinds.push(event.kind),
                    _ => {}
                }
                if kinds.last() == Some(&PlayerEventKind::Exited) {
                    break;
                }
            }
        }
        assert_eq!(
            kinds,
            [PlayerEventKind::Ended, PlayerEventKind::Exited],
            "ended, then quit by itself"
        );
    }
}