medias 0.3.5

TV media player on bare DRM/KMS: Vulkan UI plane over libmpv video, for local files, UPnP/DLNA servers and YouTube, controlled by HDMI-CEC remote, evdev or terminal
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
//! YouTube provider. Listing uses the Data API (`api`) or InnerTube; playback
//! streams direct URLs from InnerTube `player` (`innertube::streams`), with
//! mpv's yt-dlp hook as the fallback.
//!
//! Anonymous sources come from ~/medias/youtube.txt ("Label | query" per line);
//! `query` is a yt-dlp target such as `ytsearch20:<terms>` or a channel URL.

pub mod api;
pub mod auth;
pub mod innertube;
pub mod model;

use std::io::{self, Read};
use std::os::fd::AsRawFd;

use auth::{Account, Credentials, Session, Tokens};

/// Ties credentials, the two persisted sessions (Data API and YouTube TV), and
/// the API client together, and keeps OAuth access tokens fresh. `main` owns
/// one instance.
pub struct Service {
    creds: Option<Credentials>,
    session: Option<Session>,    // Data API (user's own OAuth client)
    #[cfg(feature = "youtube-tv")]
    tv_session: Option<Session>, // YouTube TV client (InnerTube)
    account: Option<String>,     // cached channel name once fetched
}

impl Service {
    pub fn load() -> Service {
        Service {
            creds: Credentials::load(),
            session: auth::load_session(Account::DataApi),
            #[cfg(feature = "youtube-tv")]
            tv_session: auth::load_session(Account::Tv),
            account: None,
        }
    }

    /// Signed in to the Data API (subscriptions, playlists, liked, search).
    pub fn signed_in(&self) -> bool {
        self.session.is_some()
    }

    /// Signed in with the YouTube TV client (recommendations).
    #[cfg(feature = "youtube-tv")]
    pub fn tv_signed_in(&self) -> bool {
        self.tv_session.is_some()
    }

    /// Cached signed-in account name, if it has been fetched.
    pub fn account(&self) -> Option<&str> {
        self.account.as_deref()
    }

    /// Fetch and cache the signed-in channel name (one `channels.list` call).
    pub fn refresh_account(&mut self) {
        if let Ok(client) = self.client() {
            if let Ok(mine) = client.mine() {
                self.account = Some(mine.title);
            }
        }
    }

    /// True when the Data API can be reached (signed in, or an API key is set).
    /// Anonymous use without either falls back to yt-dlp search + sources.
    pub fn data_api_available(&self) -> bool {
        self.signed_in() || self.creds.as_ref().and_then(|c| c.api_key.as_ref()).is_some()
    }

    /// OAuth client for an account's device sign-in; None for the Data API
    /// when youtube_oauth.json (or the env equivalent) is missing.
    pub fn sign_in_credentials(&self, account: Account) -> Option<Credentials> {
        match account {
            Account::DataApi => self.creds.clone().filter(Credentials::can_sign_in),
            #[cfg(feature = "youtube-tv")]
            Account::Tv => Some(auth::tv_credentials()),
        }
    }

    /// A Data API client with a valid bearer token (refreshing and persisting if
    /// the access token expired) and/or an API key. Errs when neither is set.
    pub fn client(&mut self) -> Result<api::Client, String> {
        let key = self.creds.as_ref().and_then(|c| c.api_key.clone());
        let token = match (&self.creds, &mut self.session) {
            (Some(creds), Some(session)) => Some(fresh_token(Account::DataApi, creds, session)?),
            _ => None,
        };
        if token.is_none() && key.is_none() {
            return Err("not signed in and no API key configured".into());
        }
        Ok(api::Client::new(token, key))
    }

    /// A fresh YouTube TV access token for InnerTube, or None (not signed in
    /// or refresh failed).
    #[cfg(feature = "youtube-tv")]
    pub fn tv_access_token(&mut self) -> Option<String> {
        let session = self.tv_session.as_mut()?;
        match fresh_token(Account::Tv, &auth::tv_credentials(), session) {
            Ok(token) => Some(token),
            Err(error) => {
                eprintln!("youtube tv: {error}");
                None
            }
        }
    }

    /// Record freshly granted tokens for an account and persist them.
    pub fn complete_sign_in(&mut self, account: Account, tokens: Tokens) {
        let session = auth::session_from(tokens);
        if let Err(error) = auth::save_session(account, &session) {
            eprintln!("save youtube session: {error}");
        }
        match account {
            Account::DataApi => {
                self.session = Some(session);
                self.refresh_account();
            }
            #[cfg(feature = "youtube-tv")]
            Account::Tv => self.tv_session = Some(session),
        }
    }

    pub fn sign_out(&mut self, account: Account) {
        auth::clear_session(account);
        match account {
            Account::DataApi => {
                self.session = None;
                self.account = None;
            }
            #[cfg(feature = "youtube-tv")]
            Account::Tv => self.tv_session = None,
        }
    }
}

/// The session's access token, refreshed (and persisted) when expired.
fn fresh_token(account: Account, creds: &Credentials, session: &mut Session) -> Result<String, String> {
    if session.expired() {
        if session.refresh_token.is_empty() {
            return Err("session expired; sign in again".into());
        }
        let tokens = auth::refresh(creds, &session.refresh_token)?;
        *session = auth::session_from(tokens);
        let _ = auth::save_session(account, session);
    }
    Ok(session.access_token.clone())
}
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command, Output, Stdio};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
    pub label: String,
    pub query: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Video {
    pub title: String,
    pub url: String,
}

/// Parse a youtube.txt body. Lines are `Label | query`; blanks and `#` comments
/// are skipped.
pub fn parse_config(text: &str) -> Vec<Source> {
    text.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty() && !l.starts_with('#'))
        .filter_map(|l| {
            let (label, query) = l.split_once('|')?;
            let (label, query) = (label.trim(), query.trim());
            if label.is_empty() || query.is_empty() {
                return None;
            }
            Some(Source {
                label: label.into(),
                query: query.into(),
            })
        })
        .collect()
}

fn config_path() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home).join("medias").join("youtube.txt")
}

/// Configured sources, or a small default set if the config is absent.
pub fn sources() -> Vec<Source> {
    match std::fs::read_to_string(config_path()) {
        Ok(text) => {
            let s = parse_config(&text);
            if s.is_empty() { defaults() } else { s }
        }
        Err(_) => defaults(),
    }
}

fn defaults() -> Vec<Source> {
    vec![
        Source {
            label: "Popular music".into(),
            query: "ytsearch25:popular music".into(),
        },
        Source {
            label: "News".into(),
            query: "ytsearch25:news".into(),
        },
    ]
}

/// Parse `yt-dlp --print "%(title)s\t%(id)s"` output into videos.
pub fn parse_entries(stdout: &str) -> Vec<Video> {
    stdout
        .lines()
        .filter_map(|line| {
            let (title, id) = line.split_once('\t')?;
            let (title, id) = (title.trim(), id.trim());
            if id.is_empty() {
                return None;
            }
            let url = if id.starts_with("http") {
                id.to_string()
            } else {
                format!("https://www.youtube.com/watch?v={id}")
            };
            Some(Video {
                title: if title.is_empty() {
                    id.into()
                } else {
                    title.into()
                },
                url,
            })
        })
        .collect()
}

struct ChildGroup {
    child: Child,
    complete: bool,
}

impl Drop for ChildGroup {
    fn drop(&mut self) {
        if !self.complete {
            // The child leads a separate process group, including pipe-holding descendants.
            unsafe { libc::kill(-(self.child.id() as libc::pid_t), libc::SIGKILL) };
            let _ = self.child.kill();
            let _ = self.child.wait();
        }
    }
}

fn nonblocking(pipe: &impl AsRawFd) -> io::Result<()> {
    let fd = pipe.as_raw_fd();
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

fn drain(pipe: &mut impl Read, output: &mut Vec<u8>) -> io::Result<bool> {
    let mut bytes = [0; 8192];
    // Bound each drain so continuous output cannot delay cancellation indefinitely.
    for _ in 0..8 {
        match pipe.read(&mut bytes) {
            Ok(0) => return Ok(true),
            Ok(count) => output.extend_from_slice(&bytes[..count]),
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
            Err(error) => return Err(error),
        }
    }
    Ok(false)
}

fn cancellable_output(
    command: &mut Command,
    mut cancelled: impl FnMut() -> bool,
) -> io::Result<Output> {
    if cancelled() {
        return Err(io::Error::new(io::ErrorKind::Interrupted, "resolution cancelled"));
    }
    let child = command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    let mut group = ChildGroup {
        child,
        complete: false,
    };
    let mut stdout = group.child.stdout.take().unwrap();
    let mut stderr = group.child.stderr.take().unwrap();
    nonblocking(&stdout)?;
    nonblocking(&stderr)?;
    let (mut out, mut err) = (Vec::new(), Vec::new());
    let (mut out_done, mut err_done) = (false, false);
    loop {
        if cancelled() {
            return Err(io::Error::new(io::ErrorKind::Interrupted, "resolution cancelled"));
        }
        if !out_done {
            out_done = drain(&mut stdout, &mut out)?;
        }
        if !err_done {
            err_done = drain(&mut stderr, &mut err)?;
        }
        // Keep the PID reserved until pipes close; cancellation signals its process group.
        if out_done && err_done && let Some(status) = group.child.try_wait()? {
            group.complete = true;
            return Ok(Output {
                status,
                stdout: out,
                stderr: err,
            });
        }
        let mut polls = [
            libc::pollfd {
                fd: if out_done { -1 } else { stdout.as_raw_fd() },
                events: libc::POLLIN,
                revents: 0,
            },
            libc::pollfd {
                fd: if err_done { -1 } else { stderr.as_raw_fd() },
                events: libc::POLLIN,
                revents: 0,
            },
        ];
        let result = unsafe { libc::poll(polls.as_mut_ptr(), polls.len() as libc::nfds_t, 20) };
        if result < 0 {
            let error = io::Error::last_os_error();
            if error.kind() != io::ErrorKind::Interrupted {
                return Err(error);
            }
        }
    }
}

/// Merge video lists round-robin (one from each list per pass), dropping ids in
/// `skip` and repeats; mixes feeds so no single source dominates the top.
pub fn interleave(lists: Vec<Vec<model::Video>>, skip: &std::collections::HashSet<String>) -> Vec<model::Video> {
    let mut queues: Vec<std::collections::VecDeque<model::Video>> = lists.into_iter().map(Into::into).collect();
    let mut seen = skip.clone();
    let mut out = Vec::new();
    while queues.iter().any(|q| !q.is_empty()) {
        for queue in &mut queues {
            if let Some(video) = queue.pop_front()
                && seen.insert(video.id.clone())
            {
                out.push(video);
            }
        }
    }
    out
}

/// A video's 480x360 thumbnail (16:9 content letterboxed in 4:3; `thumbs::decode` crops it).
/// Present for every video; hq720.jpg (1280x720, ~12x the bytes) is not.
pub fn thumb_url(id: &str) -> String {
    format!("https://i.ytimg.com/vi/{id}/hqdefault.jpg")
}

/// The 11-character video id of a YouTube URL: youtube.com/watch?v=, youtu.be/,
/// and /shorts/, /live/, /embed/ paths (www., m., music. hosts).
pub fn video_id(url: &str) -> Option<String> {
    let rest = url.split_once("://").map_or(url, |(_, r)| r);
    let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
    let host = host.strip_prefix("www.").or_else(|| host.strip_prefix("m.")).unwrap_or(host);
    let id = if host == "youtu.be" {
        Some(path)
    } else if host == "youtube.com" || host == "music.youtube.com" {
        let (route, query) = path.split_once('?').unwrap_or((path, ""));
        query
            .split('&')
            .find_map(|kv| kv.strip_prefix("v="))
            .or_else(|| ["shorts/", "live/", "embed/"].iter().find_map(|p| route.strip_prefix(p)))
    } else {
        None
    }?;
    let id = id.split(['?', '&', '#', '/']).next()?;
    let valid = id.len() == 11 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
    valid.then(|| id.to_string())
}

/// Absolute path to the yt-dlp binary, independent of the launch PATH:
/// MEDIAS_YTDL_PATH, then common install locations, else the bare name.
pub fn ytdl_path() -> String {
    if let Ok(p) = std::env::var("MEDIAS_YTDL_PATH")
        && !p.is_empty()
    {
        return p;
    }
    for candidate in ["/usr/bin/yt-dlp", "/usr/local/bin/yt-dlp", "/usr/sbin/yt-dlp", "/opt/homebrew/bin/yt-dlp"] {
        if std::path::Path::new(candidate).exists() {
            return candidate.to_string();
        }
    }
    "yt-dlp".to_string()
}

/// Resolve a source via yt-dlp; console shutdown cancels the subprocess group.
pub fn resolve(query: &str) -> io::Result<Vec<Video>> {
    let mut command = Command::new(ytdl_path());
    command.args([
        "--flat-playlist",
        "--no-warnings",
        "--ignore-errors",
        "--print",
        "%(title)s\t%(id)s",
        query,
    ]);
    let out = cancellable_output(&mut command, crate::console::stopping)?;
    if !out.status.success() && out.stdout.is_empty() {
        let err = String::from_utf8_lossy(&out.stderr);
        return Err(io::Error::other(format!(
            "yt-dlp: {}",
            err.lines().next().unwrap_or("failed")
        )));
    }
    Ok(parse_entries(&String::from_utf8_lossy(&out.stdout)))
}

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

    #[test]
    fn subprocess_output_drains_both_pipes() {
        let mut command = Command::new("/bin/sh");
        command.args(["-c", "dd if=/dev/zero bs=65536 count=4 2>/dev/null; (dd if=/dev/zero bs=65536 count=4 2>/dev/null) >&2"]);
        let output = cancellable_output(&mut command, || false).unwrap();
        assert!(output.status.success());
        assert_eq!(output.stdout.len(), 262144);
        assert_eq!(output.stderr.len(), 262144);
        assert!(
            output
                .stdout
                .iter()
                .chain(&output.stderr)
                .all(|&byte| byte == 0)
        );
    }

    #[test]
    fn subprocess_cancellation_closes_descendant_pipes() {
        for script in ["sleep 30 &", "sleep 30 & wait"] {
            let mut command = Command::new("/bin/sh");
            command.args(["-c", script]);
            let start = std::time::Instant::now();
            let mut checks = 0;
            let error = cancellable_output(&mut command, || {
                checks += 1;
                checks >= 5
            })
            .unwrap_err();
            assert_eq!(error.kind(), io::ErrorKind::Interrupted);
            assert!(start.elapsed() < std::time::Duration::from_secs(2));
        }
    }

    #[test]
    fn config_parsing() {
        let text = "\
# saved searches
Lofi | ytsearch20:lofi hip hop
  My Playlist  |  https://youtube.com/playlist?list=ABC

bad line without pipe
empty |
| noquerylabel
";
        assert_eq!(
            parse_config(text),
            vec![
                Source {
                    label: "Lofi".into(),
                    query: "ytsearch20:lofi hip hop".into()
                },
                Source {
                    label: "My Playlist".into(),
                    query: "https://youtube.com/playlist?list=ABC".into()
                },
            ]
        );
    }

    #[test]
    fn entries_build_watch_urls() {
        let out =
            "Never Gonna Give You Up\tdQw4w9WgXcQ\nSome Title\tabc123\njunk no tab\n\tEMPTYTITLE\n";
        let v = parse_entries(out);
        assert_eq!(v.len(), 3);
        assert_eq!(v[0].title, "Never Gonna Give You Up");
        assert_eq!(v[0].url, "https://www.youtube.com/watch?v=dQw4w9WgXcQ");
        assert_eq!(v[2].title, "EMPTYTITLE"); // empty title falls back to id
    }

    #[test]
    fn interleave_round_robins_and_skips_seen_ids() {
        let video = |id: &str| model::Video { id: id.into(), title: String::new(), channel: String::new(), duration: 0, thumbs: Default::default() };
        let lists = vec![
            vec![video("a1"), video("a2"), video("a3")],
            vec![video("b1"), video("a2"), video("w")],
            vec![video("c1")],
        ];
        let skip = ["w".to_string()].into_iter().collect();
        let ids: Vec<String> = interleave(lists, &skip).into_iter().map(|v| v.id).collect();
        assert_eq!(ids, ["a1", "b1", "c1", "a2", "a3"]);
    }

    #[test]
    fn video_ids_from_url_forms() {
        for url in [
            "https://www.youtube.com/watch?v=WXELsIk4o0g&t=4246s",
            "https://m.youtube.com/watch?feature=share&v=WXELsIk4o0g",
            "https://music.youtube.com/watch?v=WXELsIk4o0g#x",
            "https://youtu.be/WXELsIk4o0g?t=10",
            "https://www.youtube.com/shorts/WXELsIk4o0g",
            "https://www.youtube.com/live/WXELsIk4o0g?si=abc",
        ] {
            assert_eq!(video_id(url).as_deref(), Some("WXELsIk4o0g"), "{url}");
        }
        assert_eq!(video_id("https://www.youtube.com/watch?v=short"), None);
        assert_eq!(video_id("https://vimeo.com/123456789"), None);
        assert_eq!(video_id("/media/movies/a.mkv"), None);
    }

    #[test]
    fn entries_passthrough_full_url() {
        let v = parse_entries("Clip\thttps://www.youtube.com/watch?v=xyz\n");
        assert_eq!(v[0].url, "https://www.youtube.com/watch?v=xyz");
    }
}