Skip to main content

cosmic_applet_avestruz/
youtube.rs

1// SPDX-License-Identifier: MIT
2
3//! YouTube videos: telling a link to one from any other, and finding what
4//! there is to play of it.
5//!
6//! A link to YouTube is to a page, not to a file. In a browser the page
7//! plays the video with a player of YouTube's own, which is a program that
8//! runs in a web engine, and this client has none. What it has is
9//! GStreamer (see [`crate::video`]), which plays a stream given its
10//! address. That address is not on the page for the reading: it is worked
11//! out by running what YouTube sends, and YouTube changes how every few
12//! weeks. Keeping up with that is the whole of what
13//! [yt-dlp](https://github.com/yt-dlp/yt-dlp) does, so it is asked: run as
14//! a program of its own, if it is installed, when a video is played and
15//! not before.
16//!
17//! ```mermaid
18//! sequenceDiagram
19//!     participant row as The video's row
20//!     participant videos as Videos, in the model
21//!     participant ytdlp as yt-dlp, a program of its own
22//!     participant youtube as YouTube
23//!     participant gst as GStreamer: playbin
24//!     row->>videos: pressed: a YouTube link
25//!     videos-->>row: on its way (the row says so)
26//!     videos->>ytdlp: which stream of the video with this id?
27//!     ytdlp->>youtube: the page, and what it takes to read it
28//!     youtube-->>ytdlp: the streams there are
29//!     ytdlp-->>videos: the address of one with pictures and sound
30//!     videos->>gst: play this address
31//!     gst->>youtube: the stream
32//! ```
33//!
34//! yt-dlp is run as its user has set it up: its own configuration file
35//! holds here as at a terminal, which is where whatever it needs to get
36//! past YouTube on this machine is said (a JavaScript runtime, cookies, a
37//! proxy). If `yt-dlp --get-url` finds a video at a terminal, it is found
38//! here; and if not, what yt-dlp says is shown where the video would have
39//! played.
40//!
41//! Nothing a note says reaches yt-dlp's command line but the eleven
42//! characters of a video's id, and those only once they are known to be
43//! letters, figures, `-` and `_` (see [`VideoId`]).
44//!
45//! A stream's address is not good the moment it is given: YouTube turns
46//! away whoever asks for it before a time it names, a few seconds on,
47//! with a 403. yt-dlp is told that time and waits it out before it
48//! downloads anything; so it is asked for it here, along with the
49//! address, and waited for before the stream is handed to be played.
50//!
51//! One address is asked for, since that is what a `playbin` plays: one
52//! file with both the pictures and the sound in it. YouTube keeps such a
53//! file only in a small size (360 lines), and its larger sizes as
54//! pictures and sound apart; for a row of a popup that is enough, and the
55//! link opens the video in the browser for more.
56//!
57//! Of a video that is live there is no such file. It comes as HLS: its
58//! pictures in one run of short files and its sound in another, in
59//! several sizes, all listed in one playlist. That playlist is one
60//! address too, and GStreamer plays what it lists, pictures with sound;
61//! so where there is no file, it is the playlist that is asked for (see
62//! [`FORMAT`] and [`found`]).
63//!
64//! ```mermaid
65//! flowchart TD
66//!     asked["yt-dlp is asked for a stream"] --> file{"Is there one file of pictures and sound?"}
67//!     file -->|"yes: a video that was put up"| address["Its address is played"]
68//!     file -->|"no: a video that is live"| hls{"Are there pictures that come as HLS?"}
69//!     hls -->|"yes"| playlist["The playlist that lists them, and their sound, is played"]
70//!     hls -->|"no"| said["What yt-dlp says is shown where the video would have played"]
71//! ```
72
73use std::process::Stdio;
74use std::time::Duration;
75
76use reqwest::Url;
77
78use crate::helpers::unix_now;
79
80/// How long yt-dlp gets to find a stream. It answers in a few seconds when
81/// it answers.
82const FIND_TIMEOUT: Duration = Duration::from_secs(40);
83
84/// How long a stream is waited for to be good to fetch, at the most. It
85/// is a few seconds; a clock that is wrong must not make it an hour.
86const AVAILABLE_WAIT_MAX: Duration = Duration::from_secs(15);
87
88/// What yt-dlp is asked to write before the stream's address: when the
89/// stream is good to fetch from, in seconds since the Unix epoch, or `NA`
90/// if YouTube named no time.
91const AVAILABLE_AT: &str = "available_at=%(available_at)s";
92
93/// What yt-dlp is asked to write of the stream it chose: what its sound
94/// is in, which is `none` if it has none.
95const SOUND: &str = "sound=%(acodec)s";
96
97/// And the playlist the stream is listed in, with the others there are of
98/// the video, if it is listed in one; `NA` if not.
99const LISTED_IN: &str = "listed_in=%(manifest_url)s";
100
101/// The stream asked for: the best that is one file of pictures and sound,
102/// no taller than a popup has any use for. Failing any such file, as of a
103/// video that is live, pictures that come as HLS: not to be played
104/// themselves, having no sound, but for the playlist they are listed in.
105const FORMAT: &str = "b[height<=720]/b/bv[protocol^=m3u8]";
106
107/// How many characters a video's id has.
108const ID_CHARS: usize = 11;
109
110/// The proportions of a YouTube short, which is held upright, in pixels as
111/// they come.
112const SHORT_SIZE: (u32, u32) = (1080, 1920);
113
114/// What YouTube knows a video by: eleven letters, figures, `-` or `_`.
115/// There is no making one of anything else, so one can be handed to a
116/// command line, or written into an address, as it is.
117#[derive(Debug, Clone, PartialEq, Eq, Hash)]
118pub struct VideoId(String);
119
120impl VideoId {
121    /// `id` as a video's id, if it is shaped like one.
122    fn parse(id: &str) -> Option<Self> {
123        let shaped = id.len() == ID_CHARS && id.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
124        // The one word of eleven letters that stands where an id does, in
125        // the address of an embedded playlist.
126        (shaped && id != "videoseries").then(|| Self(id.to_string()))
127    }
128}
129
130/// A YouTube video, as a link names it.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct Video {
133    pub id: VideoId,
134    /// Its size in pixels, as far as the link gives it away: a short is
135    /// upright, and anything else is left to be what most videos are.
136    pub size: Option<(u32, u32)>,
137}
138
139impl Video {
140    /// The address of its page, with nothing in it but which video it is:
141    /// not what a link carried besides, which says who shared it.
142    pub fn page(&self) -> String {
143        format!("https://www.youtube.com/watch?v={}", self.id.0)
144    }
145
146    /// The pictures YouTube keeps to stand for it, the better first: one
147    /// as large as a popup can show, which only videos of some size have,
148    /// and a small one, which every video has. Both in the proportions
149    /// videos are.
150    pub fn posters(&self) -> Vec<String> {
151        ["maxresdefault", "mqdefault"].map(|picture| format!("https://i.ytimg.com/vi/{}/{picture}.jpg", self.id.0)).into()
152    }
153
154    /// Where YouTube says what it is called, in a few hundred bytes of
155    /// JSON (oEmbed): its page takes most of a megabyte to get to that.
156    pub fn about(&self) -> String {
157        // The address of its page, as one address says another: an id
158        // has nothing in it that needs saying differently.
159        format!("https://www.youtube.com/oembed?format=json&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D{}", self.id.0)
160    }
161}
162
163/// The YouTube video `url` links to, if it links to one: its page, a short,
164/// a live one, an embedded one, or the short address of any of them. Only
165/// an `https` link is one, as with everything fetched. A channel, a
166/// playlist or a search is not a video.
167pub fn video(url: &Url) -> Option<Video> {
168    if url.scheme() != "https" {
169        return None;
170    }
171    let host = url.host_str()?;
172    let host = ["www.", "m.", "music."].iter().find_map(|prefix| host.strip_prefix(prefix)).unwrap_or(host);
173    let mut path = url.path_segments()?;
174    let (first, second) = (path.next().unwrap_or_default(), path.next());
175    let (id, short) = match (host, first, second) {
176        ("youtu.be", id, None) => (id.to_string(), false),
177        ("youtube.com", "watch", None) => (url.query_pairs().find(|(name, _)| name == "v")?.1.into_owned(), false),
178        ("youtube.com", "shorts", Some(id)) => (id.to_string(), true),
179        ("youtube.com", "live" | "embed" | "v", Some(id)) | ("youtube-nocookie.com", "embed", Some(id)) => {
180            (id.to_string(), false)
181        }
182        _ => return None,
183    };
184    Some(Video { id: VideoId::parse(&id)?, size: short.then_some(SHORT_SIZE) })
185}
186
187/// The YouTube video the address `url` links to, if it is an address and
188/// links to one (see [`video`]).
189pub fn video_at(url: &str) -> Option<Video> {
190    video(&Url::parse(url).ok()?)
191}
192
193/// What a video is called, in what YouTube answers when asked
194/// [about](Video::about) it.
195pub fn title(answer: &[u8]) -> Option<String> {
196    let answer: serde_json::Value = serde_json::from_slice(answer).ok()?;
197    answer.get("title")?.as_str().map(str::to_string)
198}
199
200/// Why no stream of a video was found.
201#[derive(Debug, Clone, PartialEq, Eq)]
202pub enum FindError {
203    /// yt-dlp is not installed, or not where programs are looked for.
204    NotInstalled,
205    /// yt-dlp did not answer in [`FIND_TIMEOUT`].
206    TimedOut,
207    /// yt-dlp has no JavaScript runtime it may use, and YouTube gives up
208    /// its streams to nothing that can't run what it sends. What yt-dlp
209    /// says of that is a warning; the error after it is about something
210    /// else, and no help.
211    NoRuntime,
212    /// yt-dlp could not: what it said, or what kept it from being run.
213    Failed(String),
214}
215
216/// What went wrong, in what yt-dlp wrote to its error output. That it
217/// has no JavaScript runtime, or may not use the one it has to solve what
218/// YouTube sets it, if it warned of either: whatever error follows comes
219/// of that. Otherwise the last of the lines it marks as errors, without
220/// the mark, or else the last line it wrote at all.
221fn said_wrong(errors: &str) -> FindError {
222    let lines = || errors.lines().map(str::trim).filter(|line| !line.is_empty());
223    let unprepared = |line: &str| line.starts_with("WARNING:") && (line.contains("JavaScript runtime") || line.contains("[jsc]"));
224    if lines().any(unprepared) {
225        return FindError::NoRuntime;
226    }
227    let marked = lines().rev().find_map(|line| line.strip_prefix("ERROR:"));
228    FindError::Failed(marked.or_else(|| lines().next_back()).unwrap_or("it said nothing").trim().to_string())
229}
230
231/// What to play of what yt-dlp found, in what it wrote: the first line
232/// that is an `https` address, which is the stream's. Its configuration
233/// may have it write more. If the stream has no sound (see [`SOUND`]),
234/// the playlist it is listed in instead (see [`LISTED_IN`]), which lists
235/// the sound as well; and nothing if it is listed in none, rather than
236/// pictures in silence.
237fn found(output: &str) -> Option<String> {
238    let lines = || output.lines().map(str::trim);
239    let https = |line: &&str| Url::parse(line).is_ok_and(|url| url.scheme() == "https");
240    if lines().any(|line| line == "sound=none") {
241        return lines().find_map(|line| line.strip_prefix("listed_in=")).filter(https).map(str::to_string);
242    }
243    lines().find(https).map(str::to_string)
244}
245
246/// How long to wait before the stream yt-dlp found is asked for, in what
247/// it wrote (see [`AVAILABLE_AT`]), it being `now` seconds since the Unix
248/// epoch: until the time YouTube named, if it named one that is still to
249/// come, and no longer than [`AVAILABLE_WAIT_MAX`].
250fn wait_until_available(output: &str, now: u64) -> Duration {
251    let named = output.lines().find_map(|line| line.trim().strip_prefix("available_at=")?.parse::<u64>().ok());
252    Duration::from_secs(named.map_or(0, |at| at.saturating_sub(now))).min(AVAILABLE_WAIT_MAX)
253}
254
255/// Ask yt-dlp for an address at which `video` is to be had with both its
256/// pictures and its sound, and answer with it once it is good to fetch
257/// from. See the [module docs](self).
258pub async fn find_stream(video: Video) -> Result<String, FindError> {
259    let mut ytdlp = tokio::process::Command::new("yt-dlp");
260    ytdlp
261        .args(["--no-playlist", "--format", FORMAT])
262        .args(["--print", AVAILABLE_AT, "--print", SOUND, "--print", LISTED_IN, "--print", "urls", "--"])
263        .arg(video.page())
264        .stdin(Stdio::null())
265        .stdout(Stdio::piped())
266        .stderr(Stdio::piped())
267        // Not left running if it is given up on.
268        .kill_on_drop(true);
269    let answer = match tokio::time::timeout(FIND_TIMEOUT, ytdlp.output()).await {
270        Err(_) => return Err(FindError::TimedOut),
271        Ok(Err(e)) if e.kind() == std::io::ErrorKind::NotFound => return Err(FindError::NotInstalled),
272        Ok(Err(e)) => return Err(FindError::Failed(e.to_string())),
273        Ok(Ok(answer)) => answer,
274    };
275    if !answer.status.success() {
276        let errors = String::from_utf8_lossy(&answer.stderr);
277        tracing::debug!("yt-dlp failed, saying: {errors}");
278        return Err(said_wrong(&errors));
279    }
280    let output = String::from_utf8_lossy(&answer.stdout);
281    let stream = found(&output).ok_or_else(|| FindError::Failed("it named no stream".to_string()))?;
282    tokio::time::sleep(wait_until_available(&output, unix_now())).await;
283    Ok(stream)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::{AVAILABLE_WAIT_MAX, FindError, Video, VideoId, found, said_wrong, title, video_at, wait_until_available};
289    use std::time::Duration;
290
291    fn id_at(url: &str) -> Option<String> {
292        video_at(url).map(|video| video.id.0)
293    }
294
295    #[test]
296    fn a_youtube_video_is_known_by_its_id_however_its_link_is_written() {
297        for link in [
298            "https://www.youtube.com/watch?v=aqz-KE-bpKQ",
299            "https://youtube.com/watch?v=aqz-KE-bpKQ&t=42s",
300            "https://m.youtube.com/watch?feature=share&v=aqz-KE-bpKQ",
301            "https://music.youtube.com/watch?v=aqz-KE-bpKQ&list=PL123",
302            "https://youtu.be/aqz-KE-bpKQ",
303            "https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt",
304            "https://www.youtube.com/shorts/aqz-KE-bpKQ",
305            "https://www.youtube.com/live/aqz-KE-bpKQ?feature=shared",
306            "https://www.youtube.com/embed/aqz-KE-bpKQ",
307            "https://www.youtube-nocookie.com/embed/aqz-KE-bpKQ",
308            "https://www.youtube.com/v/aqz-KE-bpKQ",
309        ] {
310            assert_eq!(id_at(link).as_deref(), Some("aqz-KE-bpKQ"), "{link}");
311        }
312
313        // A short is upright; nothing else gives its shape away.
314        assert_eq!(video_at("https://www.youtube.com/shorts/aqz-KE-bpKQ").unwrap().size, Some((1080, 1920)));
315        assert_eq!(video_at("https://youtu.be/aqz-KE-bpKQ").unwrap().size, None);
316    }
317
318    #[test]
319    fn what_is_not_a_video_is_not_one() {
320        for link in [
321            "https://www.youtube.com/",
322            "https://www.youtube.com/@BlenderOfficial",
323            "https://www.youtube.com/playlist?list=PL6B3937A5D230E335",
324            "https://www.youtube.com/results?search_query=bunny",
325            "https://www.youtube.com/watch",
326            "https://www.youtube.com/watch?list=PL6B3937A5D230E335",
327            "https://www.youtube.com/embed/videoseries?list=PL6B3937A5D230E335",
328            "https://www.youtube.com/channel/UCSMOQeBJ2RAnuFungnQOxLg",
329            "https://youtu.be/",
330            "https://youtu.be/aqz-KE-bpKQ/more",
331            // Not YouTube, whatever it looks like.
332            "https://example.com/watch?v=aqz-KE-bpKQ",
333            "https://youtube.com.example.com/watch?v=aqz-KE-bpKQ",
334            "https://notyoutu.be/aqz-KE-bpKQ",
335            // Not fetched, so not played.
336            "http://www.youtube.com/watch?v=aqz-KE-bpKQ",
337            "not an address",
338        ] {
339            assert_eq!(id_at(link), None, "{link}");
340        }
341    }
342
343    #[test]
344    fn only_what_is_shaped_like_an_id_is_one() {
345        assert!(VideoId::parse("aqz-KE-bpKQ").is_some());
346        assert!(VideoId::parse("_-_-_-_-_-_").is_some());
347        for not in [
348            "",
349            "short",
350            "twelve-chars",
351            "aqz-KE-bpK",
352            "aqz KE bpKQ",
353            "aqz-KE-bpK;",
354            "--exec=boom",
355            "aqz-KE-bpK\n",
356            "ééééééééééé",
357        ] {
358            assert!(VideoId::parse(not).is_none(), "{not:?}");
359        }
360        // What a link says beside the id reaches nothing that is asked.
361        let shared = video_at("https://youtu.be/aqz-KE-bpKQ?si=Wh0Sh4redIt&t=1%20--exec%20boom").unwrap();
362        assert_eq!(shared.page(), "https://www.youtube.com/watch?v=aqz-KE-bpKQ");
363        assert_eq!(
364            shared.about(),
365            "https://www.youtube.com/oembed?format=json&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Daqz-KE-bpKQ"
366        );
367    }
368
369    #[test]
370    fn a_video_has_two_pictures_to_stand_for_it_the_better_first() {
371        let video = Video { id: VideoId::parse("aqz-KE-bpKQ").unwrap(), size: None };
372        assert_eq!(
373            video.posters(),
374            ["https://i.ytimg.com/vi/aqz-KE-bpKQ/maxresdefault.jpg", "https://i.ytimg.com/vi/aqz-KE-bpKQ/mqdefault.jpg"]
375        );
376    }
377
378    #[test]
379    fn youtube_says_what_a_video_is_called() {
380        let answer = br#"{"title":"Big Buck Bunny 60fps 4K","author_name":"Blender","type":"video","thumbnail_url":"https://i.ytimg.com/vi/aqz-KE-bpKQ/hqdefault.jpg"}"#;
381        assert_eq!(title(answer).as_deref(), Some("Big Buck Bunny 60fps 4K"));
382        assert_eq!(title(b"Bad Request"), None);
383        assert_eq!(title(br#"{"title":7}"#), None);
384        assert_eq!(title(b"{}"), None);
385    }
386
387    #[test]
388    fn a_stream_is_waited_for_until_youtube_says_it_is_good() {
389        let wrote = |available: &str| format!("available_at={available}\nhttps://rr2.googlevideo.com/videoplayback?expire=1\n");
390        let now = 1_795_041_533;
391        assert_eq!(wait_until_available(&wrote("1795041538"), now), Duration::from_secs(5));
392        // Good already, or no time named: not waited for.
393        assert_eq!(wait_until_available(&wrote("1795041533"), now), Duration::ZERO);
394        assert_eq!(wait_until_available(&wrote("1795041000"), now), Duration::ZERO);
395        assert_eq!(wait_until_available(&wrote("NA"), now), Duration::ZERO);
396        assert_eq!(wait_until_available("https://rr2.googlevideo.com/videoplayback\n", now), Duration::ZERO);
397        // A clock that is wrong, here or there, costs a moment at most.
398        assert_eq!(wait_until_available(&wrote("1795045133"), now), AVAILABLE_WAIT_MAX);
399        // The address is found beside it as it was alone.
400        assert_eq!(found(&wrote("1795041538")).as_deref(), Some("https://rr2.googlevideo.com/videoplayback?expire=1"));
401    }
402
403    #[test]
404    fn what_yt_dlp_writes_is_read_for_a_stream_or_for_what_went_wrong() {
405        let stream = "https://rr2---sn-nx57ynsk.googlevideo.com/videoplayback?expire=1795058366&id=o-ACD";
406        assert_eq!(found(&format!("{stream}\n")).as_deref(), Some(stream));
407        // Its configuration may have it write more than was asked.
408        assert_eq!(found(&format!("Big Buck Bunny\n  {stream}  \nhttps://second.example.com/\n")).as_deref(), Some(stream));
409        assert_eq!(found(""), None);
410        assert_eq!(found("NA\nhttp://plain.example.com/video\n"), None, "only https is played");
411
412        // A video that is live: its pictures have no sound, and the
413        // playlist they are listed in is what is played.
414        let pictures = "https://manifest.googlevideo.com/api/manifest/hls_playlist/itag/311/playlist/index.m3u8";
415        let playlist = "https://manifest.googlevideo.com/api/manifest/hls_variant/id/TNHAtXvAbEo.1/file/index.m3u8";
416        let live = |sound: &str, listed_in: &str| format!("available_at=NA\nsound={sound}\nlisted_in={listed_in}\n{pictures}\n");
417        assert_eq!(found(&live("none", playlist)).as_deref(), Some(playlist));
418        // With sound, it is played itself, whatever it is listed in.
419        assert_eq!(found(&live("mp4a.40.2", playlist)).as_deref(), Some(pictures));
420        assert_eq!(found(&live("NA", "NA")).as_deref(), Some(pictures));
421        // Pictures in silence are not played.
422        assert_eq!(found(&live("none", "NA")), None);
423        assert_eq!(found(&live("none", "http://plain.example.com/index.m3u8")), None);
424
425        let failed = |why: &str| FindError::Failed(why.to_string());
426        let errors = "WARNING: Unknown codec iamf.001.001.Opus\n\
427                      ERROR: [youtube] aqz-KE-bpKQ: Sign in to confirm you're not a bot.\n";
428        assert_eq!(said_wrong(errors), failed("[youtube] aqz-KE-bpKQ: Sign in to confirm you're not a bot."));
429        assert_eq!(said_wrong("Traceback (most recent call last):\n  somewhere\nKeyError: 'n'\n"), failed("KeyError: 'n'"));
430        assert_eq!(said_wrong("\n"), failed("it said nothing"));
431
432        // With nothing to run what YouTube sends, the error it ends on is
433        // about what came of that: the warning is what went wrong. As it
434        // says it with no runtime, and with one it may not use.
435        let none = "WARNING: [youtube] No supported JavaScript runtime could be found. Only deno is enabled by default\n\
436                    ERROR: [youtube] aqz-KE-bpKQ: Requested format is not available. Use --list-formats\n";
437        assert_eq!(said_wrong(none), FindError::NoRuntime);
438        let unused = "WARNING: [youtube] [jsc] Remote component challenge solver script (node) was skipped.\n\
439                      WARNING: [youtube] aqz-KE-bpKQ: n challenge solving failed: Some formats may be missing.\n\
440                      ERROR: [youtube] aqz-KE-bpKQ: Requested format is not available.\n";
441        assert_eq!(said_wrong(unused), FindError::NoRuntime);
442    }
443}