misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Video downloads: no error while yt-dlp finishes; a quality the reachable servers lack falls back (#79, #94) (#98)
Ahmed Nefzaoui8ed2613cef10
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb687565..13c41b83 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -161,6 +161,19 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Fixed+- **A video download could fail in MDM while yt-dlp went on and finished it**+ ([#79](https://github.com/anefzaoui/misterdownloadmanager/issues/79)). A line yt-dlp printed in+ the system's code page rather than UTF-8 (a title in Turkish or Russian on some Windows) ended+ MDM's reading there, and the finished file was then "not said". yt-dlp now always writes+ UTF-8, every line is read to the end, and the saved file is also found by its name. Whenever+ MDM gives a video download up, it ends yt-dlp and everything yt-dlp started, so nothing goes+ on downloading unseen.+- **YouTube: "Requested format is not available" after MDM moved a video to another server**+ ([#94](https://github.com/anefzaoui/misterdownloadmanager/issues/94)). When the servers this+ computer can reach don't serve the chosen quality, MDM downloads the nearest quality below it+ (always a video, never the sound alone) and says so in the download's log. With no video left+ at all, it tries the page's own servers. A server yt-dlp couldn't resolve or reach is avoided on+ the next look-up. The log also names the qualities a move left out.- **Lists read as blank items to screen readers** ([#95](https://github.com/anefzaoui/misterdownloadmanager/issues/95)):the rows of Download video's qualities, Add torrent's files, the language picker, Options(browsers, sounds, the file-type and site lists), the Scheduler and Import now have their namesdiff --git a/ROADMAP.md b/ROADMAP.mdindex 88cce085..36d8be74 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -23,7 +23,10 @@ Everything below ships together, in one release.- ✅ Google Drive: public files download by their share links([#34](https://github.com/anefzaoui/misterdownloadmanager/issues/34)); folders come later- ✅ Video downloads: Stop ends yt-dlp and everything it started- ([#61](https://github.com/anefzaoui/misterdownloadmanager/issues/61))+ ([#61](https://github.com/anefzaoui/misterdownloadmanager/issues/61)); no error while yt-dlp+ goes on and finishes ([#79](https://github.com/anefzaoui/misterdownloadmanager/issues/79)); a+ quality the reachable YouTube servers don't serve falls back to the nearest one+ ([#94](https://github.com/anefzaoui/misterdownloadmanager/issues/94))- ✅ A video's sound as MP3, at the quality you pick([#32](https://github.com/anefzaoui/misterdownloadmanager/issues/32))- ✅ More than 32 connections per download, if you want themdiff --git a/crates/tools/src/proc.rs b/crates/tools/src/proc.rsindex 0133e8b0..2023f2c5 100644--- a/crates/tools/src/proc.rs+++ b/crates/tools/src/proc.rs@@ -124,6 +124,18 @@ fn cookie_file(host: &str, cookies: &str) -> std::io::Result<CookieFile> {Ok(file)}+/// What yt-dlp prints is read as UTF-8 (#79): on a Windows with a legacy code page (Turkish,+/// Russian…) Python writes to a pipe in that code page, and a title's letters made the+/// final-path line unreadable. `--encoding` sets yt-dlp's own output, `PYTHONIOENCODING`+/// Python's.+const UTF8: [&str; 2] = ["--encoding", "utf-8"];++fn ytdlp_command(exe: &Path) -> Command {+ let mut cmd = Command::new(exe);+ cmd.env("PYTHONIOENCODING", "utf-8");+ cmd+}+/// `yt-dlp` with arguments in layers: `user` extras, then `ours`, then the fixed ones last/// (so nothing can switch them off), then `--` and the URL (so a URL starting with `-` is never/// read as an option).@@ -133,11 +145,13 @@ pub fn ytdlp(ours: &[String],url: &str,) -> Result<Command, ProcError> {- let mut cmd = Command::new(exe);+ let mut cmd = ytdlp_command(exe);for a in user.iter().chain(ours) {cmd.arg(safe(a)?);}- cmd.args(["--ignore-config", "--no-exec", "--no-update", "--"]);+ cmd.args(["--ignore-config", "--no-exec", "--no-update"]);+ cmd.args(UTF8);+ cmd.arg("--");cmd.arg(safe(url)?);Ok(cmd)}@@ -150,16 +164,13 @@ pub fn ytdlp_info(ours: &[String],info: &Path,) -> Result<Command, ProcError> {- let mut cmd = Command::new(exe);+ let mut cmd = ytdlp_command(exe);for a in user.iter().chain(ours) {cmd.arg(safe(a)?);}- cmd.args([- "--ignore-config",- "--no-exec",- "--no-update",- "--load-info-json",- ]);+ cmd.args(["--ignore-config", "--no-exec", "--no-update"]);+ cmd.args(UTF8);+ cmd.arg("--load-info-json");cmd.arg(info);Ok(cmd)}@@ -377,6 +388,8 @@ mod tests {"--ignore-config","--no-exec","--no-update",+ "--encoding",+ "utf-8","--","-https://x/"]diff --git a/crates/tools/src/servers.rs b/crates/tools/src/servers.rsindex a1c21a95..98aa7327 100644--- a/crates/tools/src/servers.rs+++ b/crates/tools/src/servers.rs@@ -125,16 +125,73 @@ fn headers_of(format: &Value) -> BTreeMap<String, String> {.unwrap_or_default()}+/// What [`reroute`] changed.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Rerouted {+ /// (dead host, replacement), each pair once.+ pub swaps: Vec<(String, String)>,+ /// The streams left out because no reachable alternative serves them, as "137 (1080p)" (for+ /// the download's log: a quality chosen from the window may be among them, #94).+ pub left_out: Vec<String>,+}++impl Rerouted {+ pub fn is_empty(&self) -> bool {+ self.swaps.is_empty() && self.left_out.is_empty()+ }+}++/// A format as the log names it: its id and its height (or "audio").+fn describe(f: &Value) -> String {+ let id = f.get("format_id").and_then(Value::as_str).unwrap_or("?");+ match f.get("height").and_then(Value::as_u64) {+ Some(h) => format!("{id} ({h}p)"),+ None if f.get("vcodec").and_then(Value::as_str) == Some("none") => format!("{id} (audio)"),+ None => id.to_owned(),+ }+}++/// The media servers yt-dlp's failure names as unreachable (#94): it couldn't resolve one, or+/// connect to it, or it timed out (`HTTPSConnection(host='rr1---sn-x.googlevideo.com',+/// port=443): Failed to resolve 'rr1---sn-x.googlevideo.com'`). A server answered at look-up+/// time may be gone by download time (a flaky resolver): the next look-up treats these as dead.+pub fn unreachable_in(message: &str) -> BTreeSet<String> {+ let network = [+ "Failed to resolve",+ "getaddrinfo",+ "Unable to connect",+ "timed out",+ "Connection refused",+ "Max retries",+ ]+ .iter()+ .any(|w| message.contains(w));+ if !network {+ return BTreeSet::new();+ }+ message+ .split(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '.'))+ .filter(|w| w.ends_with(".googlevideo.com") && w.contains("---"))+ .map(str::to_owned)+ .collect()+}++/// yt-dlp couldn't find the chosen format among the ones the page (or our edit of it) offers.+pub fn format_unavailable(message: &str) -> bool {+ message.contains("Requested format is not available")+}+/// Move the streams of unreachable media servers to an alternative that serves them; returns-/// what changed (dead host, replacement), each pair once. `alive` decides whether a server can be-/// reached ([`reachable`], all at once), `serves` whether it really serves one stream-/// ([`Prober::serves`], one after another). A stream no reachable alternative serves is left out, so yt-dlp chooses an-/// equivalent one (another codec of the same quality, the other audio).+/// what changed. `alive` decides whether a server can be reached ([`reachable`], all at once),+/// `serves` whether it really serves one stream ([`Prober::serves`], one after another). A stream+/// no reachable alternative serves is left out, so yt-dlp chooses an equivalent one (another+/// codec of the same quality, the other audio); the video job falls back to the nearest quality+/// when the chosen one is among them (video.rs).pub fn reroute(info: &mut Value,alive: impl Fn(&str) -> bool + Sync,serves: impl Fn(&str, &BTreeMap<String, String>) -> bool,-) -> Vec<(String, String)> {+) -> Rerouted {// Media hosts with an `mn` list, and one link of each (for its alternatives).let mut links: BTreeMap<String, Url> = BTreeMap::new();strings_mut(info, &mut |s| {@@ -166,10 +223,10 @@ pub fn reroute(.map(|(h, _)| h.clone()).collect();if dead.is_empty() {- return Vec::new();+ return Rerouted::default();}let Some(Value::Array(formats)) = info.get_mut("formats") else {- return Vec::new();+ return Rerouted::default();};// HLS formats list their pieces in a manifest fetched later, on the same servers, which// can't be edited here: leave them out so the choice falls on direct links (live@@ -203,6 +260,7 @@ pub fn reroute(.collect();let mut swaps: Vec<(String, String)> = Vec::new();let mut drop = BTreeSet::new();+ let mut left_out = Vec::new();for (i, host, to) in moves {match to {Some(alt) => {@@ -214,6 +272,7 @@ pub fn reroute(}}None => {+ left_out.push(describe(&formats[i]));drop.insert(i);}}@@ -227,7 +286,7 @@ pub fn reroute(if let Some(o) = info.as_object_mut() {o.remove("requested_formats");}- swaps+ Rerouted { swaps, left_out }}#[cfg(test)]@@ -256,8 +315,9 @@ mod tests {#[test]fn an_unreachable_server_is_swapped_for_its_alternative() {let mut v = info();- let swaps = reroute(&mut v, |h| h != DEAD, |_, _| true);- assert_eq!(swaps, vec![(DEAD.to_owned(), ALT.to_owned())]);+ let r = reroute(&mut v, |h| h != DEAD, |_, _| true);+ assert_eq!(r.swaps, vec![(DEAD.to_owned(), ALT.to_owned())]);+ assert!(r.left_out.is_empty());let text = v.to_string();assert!(!text.contains(DEAD), "every link moved: {text}");assert_eq!(@@ -287,8 +347,10 @@ mod tests {fn a_stream_the_alternative_refuses_is_left_out() {// 249 is refused by the alternative (403), 139 is served: only 139 stays.let mut v = info();- let swaps = reroute(&mut v, |h| h != DEAD, |link, _| !link.contains("itag=249"));- assert_eq!(swaps, vec![(DEAD.to_owned(), ALT.to_owned())]);+ let r = reroute(&mut v, |h| h != DEAD, |link, _| !link.contains("itag=249"));+ assert_eq!(r.swaps, vec![(DEAD.to_owned(), ALT.to_owned())]);+ // Said, for the log: what the choice may have lost (#94).+ assert_eq!(r.left_out, ["249"]);let ids: Vec<&str> = v["formats"].as_array().unwrap()@@ -298,10 +360,41 @@ mod tests {assert_eq!(ids, ["139"]);// Nothing served anywhere: every stream on the dead server is out, nothing swapped.let mut v = info();- assert!(reroute(&mut v, |h| h != DEAD, |_, _| false).is_empty());+ let r = reroute(&mut v, |h| h != DEAD, |_, _| false);+ assert!(r.swaps.is_empty());+ assert_eq!(r.left_out, ["139", "249"]);assert!(v["formats"].as_array().unwrap().is_empty());}+ #[test]+ fn a_left_out_stream_is_named_by_its_height() {+ let f = serde_json::json!({"format_id": "137", "height": 1080});+ assert_eq!(describe(&f), "137 (1080p)");+ let a = serde_json::json!({"format_id": "251", "vcodec": "none"});+ assert_eq!(describe(&a), "251 (audio)");+ }++ /// #94: yt-dlp's words for a server it couldn't reach name the server; other failures don't.+ #[test]+ fn unreachable_servers_from_ytdlps_failure() {+ let dns = "[download] Got error: HTTPSConnection(host='rr1---sn-u0opnpxuxa-u0oz.googlevideo.com', port=443): Failed to resolve 'rr1---sn-u0opnpxuxa-u0oz.googlevideo.com' ([Errno 11004] getaddrinfo failed). Giving up after 10 retries";+ assert_eq!(+ unreachable_in(dns).into_iter().collect::<Vec<_>>(),+ ["rr1---sn-u0opnpxuxa-u0oz.googlevideo.com"]+ );+ let refused = "Unable to connect to rr3---sn-abc.googlevideo.com: timed out";+ assert_eq!(unreachable_in(refused).len(), 1);+ // A googlevideo host in another kind of failure (403) isn't "unreachable".+ assert!(+ unreachable_in("HTTP Error 403: Forbidden (rr1---sn-x.googlevideo.com)").is_empty()+ );+ assert!(unreachable_in("Failed to resolve 'example.com'").is_empty());+ assert!(format_unavailable(+ "[youtube] jvfC98jCBuk: Requested format is not available. Use --list-formats for a list of available formats"+ ));+ assert!(!format_unavailable("HTTP Error 403"));+ }+#[test]fn a_blackholed_name_is_unreachable() {// A hosts-file block answers 0.0.0.0; "localhost" style real names would connect.diff --git a/crates/tools/src/video.rs b/crates/tools/src/video.rsindex 8c69675e..f73dbf6d 100644--- a/crates/tools/src/video.rs+++ b/crates/tools/src/video.rs@@ -248,8 +248,9 @@ type Child = Arc<Mutex<Option<proc::Spawned>>>;/// How one run of yt-dlp ended.enum Attempt {- /// The video saved, and the subtitles that didn't come with it.- Done(PathBuf, Vec<SubProblem>),+ /// The video saved, the subtitles that didn't come with it, and the quality yt-dlp chose+ /// (`137+251 1920x1080`).+ Done(PathBuf, Vec<SubProblem>, Option<String>),Stopped,/// `rerouted`: links were moved to other servers for this run.Failed {@@ -258,9 +259,55 @@ enum Attempt {},}-/// Runs the download; once more with a fresh look-up when a run whose links had to be moved to-/// other servers fails (new links, often other servers: YouTube's alternatives refuse some-/// streams some of the time).+/// End yt-dlp and everything it started (#79): whenever the download is given up, nothing may+/// go on downloading unseen (Windows: its job, the launcher's child and ffmpeg with it).+fn end(child: &Child) {+ let mut slot = child.lock().unwrap_or_else(|e| e.into_inner());+ if let Some(mut s) = slot.take() {+ s.kill();+ }+}++/// The format selector in yt-dlp's arguments (`-f <selector>`).+fn selector_of(ours: &[String]) -> Option<&str> {+ ours.iter()+ .position(|a| a == "-f")+ .and_then(|i| ours.get(i + 1))+ .map(String::as_str)+}++/// `ours` with another format selector.+fn with_selector(ours: &[String], selector: &str) -> Vec<String> {+ let mut out = ours.to_vec();+ if let Some(i) = out.iter().position(|a| a == "-f")+ && let Some(s) = out.get_mut(i + 1)+ {+ *s = selector.to_owned();+ }+ out+}++/// The nearest quality to a choice from the window (`bv*[height=1080]+ba/b[height=1080]`) when+/// that one isn't offered (#94: the servers this PC reaches don't serve it): the best at or below+/// that height, else the best video there is, always a video (`b` alone would take a sound-only+/// format when no video is left; live 2026-11-05). None when the choice names no height.+fn relaxed(selector: &str) -> Option<String> {+ selector+ .contains("[height=")+ .then(|| format!("{}/bv*+ba/bv*", selector.replace("[height=", "[height<=")))+}++/// Runs the download, and again when a run fails in a way a new look-up can mend:+/// - a media server yt-dlp couldn't reach (it resolved when looked up, then didn't: #94) is+/// treated as dead, so its streams move to an alternative;+/// - a run whose links had to be moved to other servers gets one fresh look-up (new links, often+/// other servers: YouTube's alternatives refuse some streams some of the time);+/// - the chosen quality not offered at all (left out by the move, #94) falls back to the nearest+/// one below it, said in the log; never the whole download's failure while another quality+/// is there;+/// - no video left at all after the move: once more on the page's own servers, unmoved.+///+/// Whenever it is given up, yt-dlp's whole job is ended (#79).fn supervise(exe: &Path,url: &str,@@ -270,10 +317,24 @@ fn supervise(expected: Option<u64>,retry: Option<&SubsRetry>,) {- for n in 0..2 {- match attempt(exe, url, ours, progress, child, expected, retry) {+ let mut ours = ours.to_vec();+ let mut dead: std::collections::BTreeSet<String> = Default::default();+ let mut looked_again = false;+ let mut relaxed_to: Option<String> = None;+ let mut reroute = true;+ let mut last = String::from("yt-dlp stopped");+ for _ in 0..5 {+ match attempt(+ exe, url, &ours, progress, child, expected, retry, &dead, reroute,+ ) {Attempt::Stopped => return,- Attempt::Done(f, problems) => {+ Attempt::Done(f, problems, quality) => {+ end(child);+ if relaxed_to.is_some()+ && let Some(q) = quality+ {+ note(progress, format!("Downloaded {q} instead"));+ }// The saved file's own size: a merged video or a converted MP3 isn't the size// of what came down.let saved = std::fs::metadata(&f).ok().map(|m| m.len());@@ -291,22 +352,60 @@ fn supervise(}return;}- Attempt::Failed { error, rerouted } if rerouted && n == 0 => {- progress.lock().unwrap().events.push((- std::time::SystemTime::now(),- format!("{error}; looking the page up again"),- ));- }- Attempt::Failed { error, .. } => {- let mut p = progress.lock().unwrap();- if p.state != State::Stopped {- p.speed = 0.0;- p.state = State::Failed(error);+ Attempt::Failed { error, rerouted } => {+ end(child);+ let gone: Vec<String> = servers::unreachable_in(&error)+ .into_iter()+ .filter(|h| !dead.contains(h))+ .collect();+ // On the page's own servers (no moving any more), an unreachable one is the end:+ // another look-up would go to it again (live 2026-11-05).+ if !gone.is_empty() && reroute {+ for h in &gone {+ note(+ progress,+ format!(+ "The server {h} couldn't be reached; looking the page up again without it"+ ),+ );+ }+ dead.extend(gone);+ } else if servers::format_unavailable(&error) && rerouted && !looked_again {+ looked_again = true;+ note(progress, format!("{error}; looking the page up again"));+ } else if servers::format_unavailable(&error)+ && relaxed_to.is_none()+ && let Some(sel) = selector_of(&ours).and_then(relaxed)+ {+ note(+ progress,+ "The chosen quality isn't offered by the servers this computer can reach; downloading the nearest quality below it".into(),+ );+ ours = with_selector(&ours, &sel);+ relaxed_to = Some(sel);+ } else if servers::format_unavailable(&error) && rerouted && reroute {+ note(+ progress,+ "No video the servers this computer can reach serve is left; trying the page's own servers".into(),+ );+ reroute = false;+ } else if rerouted && !looked_again {+ looked_again = true;+ note(progress, format!("{error}; looking the page up again"));+ } else {+ last = error;+ break;}- return;+ last = error;}}}+ end(child);+ let mut p = progress.lock().unwrap();+ if p.state != State::Stopped {+ p.speed = 0.0;+ p.state = State::Failed(last);+ }}/// yt-dlp's progress lines (`MDMP <downloaded> <total> <estimate> <speed>`) made into one@@ -384,6 +483,8 @@ struct Ran {status: std::io::Result<std::process::ExitStatus>,/// Where it said it saved the file (`MDMF`).saved: Option<PathBuf>,+ /// The quality it chose (`MDMQ`).+ quality: Option<String>,warnings: Vec<String>,/// What it said when it failed.failure: String,@@ -418,9 +519,24 @@ fn run(}};let mut saved = None;- for line in BufReader::new(stdout).lines().map_while(Result::ok) {+ let mut quality = None;+ // Every line to the end, read as bytes (#79): a line that isn't UTF-8 (a title in a legacy+ // code page) used to end the reading there, while yt-dlp went on; it is read leniently now,+ // and the saved file is also found by its name (`attempt`).+ let mut reader = BufReader::new(stdout);+ let mut buf = Vec::new();+ loop {+ buf.clear();+ match reader.read_until(b'\n', &mut buf) {+ Ok(0) | Err(_) => break,+ Ok(_) => {}+ }+ let text = String::from_utf8_lossy(&buf);+ let line = text.trim_end_matches(['\r', '\n']);if let Some(rest) = line.strip_prefix("MDMF ") {saved = Some(PathBuf::from(rest.trim()));+ } else if let Some(rest) = line.strip_prefix("MDMQ ") {+ quality = Some(rest.trim().to_owned());} else if let Some(rest) = line.strip_prefix("MDMP ")&& let Some(m) = meter.as_deref_mut(){@@ -453,11 +569,38 @@ fn run(Ok(Some(Ran {status,saved,+ quality,warnings,failure,}))}+/// The media file yt-dlp saved under our output name (`<dir>/<stem>.%(ext)s`), when it didn't say+/// where, or said it in a form that names no file (#79). Its subtitles (`<stem>.<lang>.srt`) and+/// unfinished parts don't count; the newest one wins.+fn saved_by_name(ours: &[String]) -> Option<PathBuf> {+ const MEDIA: [&str; 15] = [+ "mp4", "mkv", "webm", "mov", "m4v", "m4a", "mp3", "opus", "ogg", "oga", "flac", "wav",+ "aac", "flv", "3gp",+ ];+ let template = ours+ .iter()+ .position(|a| a == "-o")+ .and_then(|i| ours.get(i + 1))?;+ let t = Path::new(template);+ let dir = t.parent()?;+ let stem = t+ .file_name()?+ .to_string_lossy()+ .strip_suffix(".%(ext)s")?+ .replace("%%", "%");+ MEDIA+ .iter()+ .map(|ext| dir.join(format!("{stem}.{ext}")))+ .filter(|p| p.is_file())+ .max_by_key(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())+}+/// Wait `d`, or less if the download is stopped meanwhile (false then).fn pause(d: std::time::Duration, progress: &Mutex<Progress>) -> bool {let end = std::time::Instant::now() + d;@@ -470,9 +613,11 @@ fn pause(d: std::time::Duration, progress: &Mutex<Progress>) -> bool {progress.lock().unwrap().state != State::Stopped}-/// One run: look the page up, move links off unreachable servers, download from that list.-/// Subtitles the site refused are asked for once more after a pause (`retry`), beside the video;-/// the ones still refused are reported with it, never failing it.+/// One run: look the page up, move links off unreachable servers (and off `dead`, the ones an+/// earlier run couldn't reach), download from that list. Subtitles the site refused are asked+/// for once more after a pause (`retry`), beside the video; the ones still refused are reported+/// with it, never failing it.+#[allow(clippy::too_many_arguments)]fn attempt(exe: &Path,url: &str,@@ -481,21 +626,40 @@ fn attempt(child: &Child,expected: Option<u64>,retry: Option<&SubsRetry>,+ dead: &std::collections::BTreeSet<String>,+ reroute: bool,) -> Attempt {let failed = |error: String, rerouted: bool| Attempt::Failed { error, rerouted };let mut info = match look_up(exe, url) {Ok(v) => v,Err(e) => return failed(e, false),};- let prober = servers::Prober::new();- let swaps = servers::reroute(&mut info, servers::reachable, |l, h| prober.serves(l, h));- for (dead, alt) in &swaps {+ let changed = if reroute {+ let prober = servers::Prober::new();+ servers::reroute(+ &mut info,+ |h| !dead.contains(h) && servers::reachable(h),+ |l, h| prober.serves(l, h),+ )+ } else {+ servers::Rerouted::default()+ };+ for (gone, alt) in &changed.swaps {+ note(+ progress,+ format!("The server {gone} can't be reached; downloading from {alt}"),+ );+ }+ if !changed.left_out.is_empty() {note(progress,- format!("The server {dead} can't be reached; downloading from {alt}"),+ format!(+ "Not served by the servers this computer can reach, so left out: {}",+ changed.left_out.join(", ")+ ),);}- let rerouted = !swaps.is_empty();+ let rerouted = !changed.is_empty();let file = info_file();if let Err(e) = std::fs::write(&file, info.to_string()) {return failed(format!("Cannot write the video information: {e}"), rerouted);@@ -507,10 +671,15 @@ fn attempt(Ok(None) => return Attempt::Stopped,Err(e) => return failed(e, rerouted),};+ let quality = ran.quality.clone();let video = match (&ran.status, ran.saved) {// `--ignore-errors` (subtitles asked) lets yt-dlp end well with no file: the file// itself is the proof.(Ok(s), Some(f)) if s.success() && f.is_file() => f,+ // It said where, in a form that names no file (#79), or didn't say: our own name for it.+ (Ok(s), _) if s.success() && saved_by_name(ours).is_some() => {+ saved_by_name(ours).expect("just found")+ }(Ok(s), Some(_)) if s.success() => {return failed("yt-dlp said it saved the file, but it isn't there".into(),@@ -524,7 +693,7 @@ fn attempt(};let refused = subtitle_failures(&ran.warnings);if refused.is_empty() {- return Attempt::Done(video, Vec::new());+ return Attempt::Done(video, Vec::new(), quality);}for (code, why) in &refused {note(@@ -545,14 +714,14 @@ fn attempt(format!("Asking for the subtitles again in {} s", delay.as_secs()),);if !pause(delay, progress) {- return Attempt::Done(video, Vec::new());+ return Attempt::Done(video, Vec::new(), quality);}let codes: Vec<String> = refused.iter().map(|(c, _)| c.clone()).collect();match run(exe, &r.args(&codes), &file, progress, child, None) {Ok(Some(again)) if again.status.as_ref().is_ok_and(|s| s.success()) => {still = subtitle_failures(&again.warnings);}- Ok(None) => return Attempt::Done(video, Vec::new()),+ Ok(None) => return Attempt::Done(video, Vec::new(), quality.clone()),_ => {}}}@@ -583,7 +752,7 @@ fn attempt(}}}- Attempt::Done(video, problems)+ Attempt::Done(video, problems, quality)}/// A line for the download's log (English, as yt-dlp's own).@@ -621,6 +790,9 @@ fn template_text(s: &str) -> String {const PROGRESS: &str = "download:MDMP %(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s %(progress.speed)s";/// The final file: `MDMF <path>`.const FINAL: &str = "after_move:MDMF %(filepath)s";+/// The quality yt-dlp chose, before it downloads: `MDMQ <format id> <resolution>` (the log names+/// it when it isn't the one asked for, #94).+const QUALITY: &str = "video:MDMQ %(format_id)s %(resolution)s";impl VideoJob {/// Download `url` in format `selector` to `dir/<stem>.<ext>`, at most `rate` bytes/s;@@ -666,6 +838,8 @@ impl VideoJob {PROGRESS.into(),"--print".into(),FINAL.into(),+ "--print".into(),+ QUALITY.into(),];if let Some(r) = rate {ours.extend(["--limit-rate".into(), r.to_string()]);@@ -742,6 +916,8 @@ impl VideoJob {)});if std::panic::catch_unwind(run).is_err() {+ // Given up: nothing may go on downloading unseen (#79).+ end(&child);let mut p = progress.lock().unwrap_or_else(|e| e.into_inner());if p.state == State::Running {p.speed = 0.0;@@ -1036,6 +1212,61 @@ mod tests {assert_eq!(names, ["Talk.en-orig.vtt", "Talk.fr.srt"]);}+ /// #94: a window's choice falls back to the nearest quality below it, then to the best;+ /// choices without a height (audio, "b") have no fallback; the selector is swapped in place.+ #[test]+ fn a_missing_quality_falls_back_to_the_nearest_below() {+ assert_eq!(+ relaxed("bv*[height=1080]+ba/b[height=1080]").as_deref(),+ Some("bv*[height<=1080]+ba/b[height<=1080]/bv*+ba/bv*")+ );+ assert_eq!(relaxed("ba/b"), None);+ assert_eq!(relaxed("b"), None);+ let ours: Vec<String> = ["-f", "bv*[height=720]+ba/b[height=720]", "-o", "x"]+ .map(String::from)+ .to_vec();+ assert_eq!(selector_of(&ours), Some("bv*[height=720]+ba/b[height=720]"));+ assert_eq!(+ with_selector(&ours, "b"),+ ["-f", "b", "-o", "x"].map(String::from)+ );+ }++ /// #79: the saved file found by our own output name: the media file, not its subtitles,+ /// its unfinished part or another video's file; `%` in a title as it was written.+ #[test]+ fn the_saved_file_is_found_by_its_name() {+ let dir = tempfile::tempdir().unwrap();+ for f in [+ "Şirin 100% ğüş.mp4",+ "Şirin 100% ğüş.ru.srt",+ "Şirin 100% ğüş.f137.mp4.part",+ "Other.mp4",+ ] {+ std::fs::write(dir.path().join(f), b"x").unwrap();+ }+ let template = dir+ .path()+ .join(format!("{}.%(ext)s", template_text("Şirin 100% ğüş")));+ let ours: Vec<String> = vec!["-o".into(), template.to_string_lossy().into_owned()];+ assert_eq!(+ saved_by_name(&ours)+ .unwrap()+ .file_name()+ .unwrap()+ .to_string_lossy(),+ "Şirin 100% ğüş.mp4"+ );+ let none: Vec<String> = vec![+ "-o".into(),+ dir.path()+ .join("Missing.%(ext)s")+ .to_string_lossy()+ .into_owned(),+ ];+ assert_eq!(saved_by_name(&none), None);+ }+#[test]fn percent_signs_in_titles_stay_text() {assert_eq!(template_text("100% fun"), "100%% fun");diff --git a/crates/tools/tests/fake_ytdlp.rs b/crates/tools/tests/fake_ytdlp.rsindex 7c5e7ece..89ab3cec 100644--- a/crates/tools/tests/fake_ytdlp.rs+++ b/crates/tools/tests/fake_ytdlp.rs@@ -23,6 +23,7 @@ fn main() -> ExitCode {}if std::env::var_os("MDM_SUBS_RETRY_SECS").is_some() {checks(&me);+ job_checks(&me);println!("fake_ytdlp: ok");return ExitCode::SUCCESS;}@@ -43,8 +44,37 @@ fn mode(dir: &Path) -> String {std::fs::read_to_string(dir.join("mode.txt")).unwrap_or_default()}+/// A process the fake leaves behind (as yt-dlp's launcher leaves its child, and ffmpeg): it+/// writes to `file` every 100 ms for 30 s, unless ended.+fn linger(file: &Path) -> ExitCode {+ use std::io::Write;+ let end = Instant::now() + Duration::from_secs(30);+ while Instant::now() < end {+ if let Ok(mut f) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(file)+ {+ let _ = f.write_all(b"x");+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ ExitCode::SUCCESS+}++/// Raw bytes on stdout (a line in another code page than UTF-8, #79).+fn out_bytes(b: &[u8]) {+ use std::io::Write;+ let mut o = std::io::stdout().lock();+ let _ = o.write_all(b);+ let _ = o.flush();+}+fn fake_ytdlp() -> ExitCode {let args: Vec<String> = std::env::args().skip(1).collect();+ if args.first().map(String::as_str) == Some("--linger") {+ return linger(Path::new(&args[1]));+ }let after = |flag: &str| {args.iter().position(|a| a == flag)@@ -68,6 +98,46 @@ fn fake_ytdlp() -> ExitCode {.and_then(|t| t.trim().parse::<u32>().ok()).unwrap_or(0);std::fs::write(&tries, (tried + 1).to_string()).unwrap();+ let format = after("-f").unwrap_or_default();+ // #94: the chosen height isn't offered (the reroute left it out); a fallback is.+ if mode == "unavailable" && format.contains("[height=") {+ eprintln!(+ "ERROR: [youtube] abc: Requested format is not available. Use --list-formats for a list of available formats"+ );+ return ExitCode::FAILURE;+ }+ // #94: a media server that resolved when looked up doesn't when downloading, once.+ if mode == "dns-once" && tried == 0 {+ eprintln!(+ "ERROR: [download] Got error: HTTPSConnection(host='rr1---sn-dead.googlevideo.com', port=443): Failed to resolve 'rr1---sn-dead.googlevideo.com' ([Errno 11004] getaddrinfo failed). Giving up after 10 retries"+ );+ return ExitCode::FAILURE;+ }+ println!("MDMP 1024 4096 NA 1000");+ println!("MDMQ 18 640x360");+ // #79: it falls over mid-way, leaving a helper running (Windows: the launcher's child).+ if mode == "crash" {+ let me = std::env::current_exe().unwrap();+ let _ = Command::new(me)+ .args(["--linger", &dir.join("linger.log").to_string_lossy()])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn();+ std::thread::sleep(Duration::from_millis(500));+ eprintln!("ERROR: unable to download video data: HTTP Error 500");+ return ExitCode::FAILURE;+ }+ // #79: lines that aren't UTF-8, before and as the final path (a legacy code page).+ if mode == "odd-lines" {+ out_bytes(b"\xff\xfe [download] Destination: \xde\xfd.mp4\n");+ println!("not one of our lines");+ println!("MDMP NA NA NA NA");+ }+ // #79: silent for a while, as when ffmpeg merges a long video.+ if let Some(secs) = mode.strip_prefix("quiet:") {+ std::thread::sleep(Duration::from_secs(secs.trim().parse().unwrap_or(1)));+ }let langs = after("--sub-langs").unwrap_or_default();for lang in langs.split(',').filter(|l| !l.is_empty()) {let refused = lang == "en" && (mode == "refuse-always" || tried == 0);@@ -85,9 +155,21 @@ fn fake_ytdlp() -> ExitCode {std::fs::write(file, "1\n00:00:00,000 --> 00:00:01,000\nHello\n").unwrap();}if !has("--skip-download") {- let video = template.replace("%(ext)s", "mp4");+ let video = template.replace("%(ext)s", "mp4").replace("%%", "%");std::fs::write(&video, vec![0u8; 4096]).unwrap();- println!("MDMF {video}");+ if mode == "odd-lines" {+ // The path in a one-byte code page: every letter beyond ASCII one byte, not UTF-8.+ let mut line = b"MDMF ".to_vec();+ line.extend(+ video+ .chars()+ .map(|c| if c.is_ascii() { c as u8 } else { 0xde }),+ );+ line.push(b'\n');+ out_bytes(&line);+ } else {+ println!("MDMF {video}");+ }}ExitCode::SUCCESS}@@ -101,6 +183,18 @@ fn fake_in(me: &Path, dir: &Path) -> PathBuf {/// Download with `subs` while the fake behaves as `mode`; the end state, its log and folder.fn download(me: &Path, mode: &str, subs: &Subs) -> (mdm_tools::video::Progress, Vec<String>) {+ let (p, files, _out) = download_as(me, mode, subs, "b", "Talk");+ (p, files)+}++/// The same with a format `selector` and a file `stem`; also hands back the output folder.+fn download_as(+ me: &Path,+ mode: &str,+ subs: &Subs,+ selector: &str,+ stem: &str,+) -> (mdm_tools::video::Progress, Vec<String>, tempfile::TempDir) {let tools = tempfile::tempdir().unwrap();let out = tempfile::tempdir().unwrap();std::fs::write(out.path().join("mode.txt"), mode).unwrap();@@ -108,9 +202,9 @@ fn download(me: &Path, mode: &str, subs: &Subs) -> (mdm_tools::video::Progress,let job = VideoJob::start(&exe,"https://video.example/talk",- "b",+ selector,out.path(),- "Talk",+ stem,None,None,None,@@ -118,7 +212,7 @@ fn download(me: &Path, mode: &str, subs: &Subs) -> (mdm_tools::video::Progress,subs,).expect("started");- let end = Instant::now() + Duration::from_secs(60);+ let end = Instant::now() + Duration::from_secs(120);let p = loop {let p = job.progress();if p.state != State::Running {@@ -131,10 +225,91 @@ fn download(me: &Path, mode: &str, subs: &Subs) -> (mdm_tools::video::Progress,.unwrap().filter_map(Result::ok).map(|e| e.file_name().to_string_lossy().into_owned())- .filter(|n| !n.ends_with(".txt"))+ .filter(|n| !n.ends_with(".txt") && !n.ends_with(".log")).collect();files.sort();- (p, files)+ (p, files, out)+}++fn log_of(p: &mdm_tools::video::Progress) -> Vec<String> {+ p.events.iter().map(|(_, t)| t.clone()).collect()+}++/// #79 and #94: the job never gives up while yt-dlp works, never leaves it running when it does+/// give up, and mends what a new look-up or a nearby quality can mend.+fn job_checks(me: &Path) {+ let none = Subs::default();++ // Silent for 30 s (ffmpeg merging a long video): no timeout of MDM's own ends it.+ let (p, files, _o) = download_as(me, "quiet:30", &none, "b", "Talk");+ assert!(matches!(p.state, State::Done(_)), "quiet: {:?}", p.state);+ assert_eq!(files, ["Talk.mp4"]);++ // Lines that aren't UTF-8, the final path among them: read through, the file found by name.+ let (p, files, _o) = download_as(me, "odd-lines", &none, "b", "Şirin ğüş");+ match &p.state {+ State::Done(f) => assert_eq!(f.file_name().unwrap().to_string_lossy(), "Şirin ğüş.mp4"),+ other => panic!("odd lines: {other:?}"),+ }+ assert_eq!(files, ["Şirin ğüş.mp4"]);++ // It falls over mid-way: the failure is told, and what it left running is ended with it+ // (Windows: the job; elsewhere yt-dlp is one process, so there's no child to leave).+ let (p, _files, out) = download_as(me, "crash", &none, "b", "Talk");+ match &p.state {+ State::Failed(e) => assert!(e.contains("HTTP Error 500"), "{e}"),+ other => panic!("crash: {other:?}"),+ }+ #[cfg(windows)]+ {+ let size = || std::fs::metadata(out.path().join("linger.log")).map_or(0, |m| m.len());+ std::thread::sleep(Duration::from_millis(800));+ let after = size();+ std::thread::sleep(Duration::from_millis(1500));+ assert_eq!(+ size(),+ after,+ "the helper it left was ended with the download"+ );+ }+ #[cfg(not(windows))]+ let _ = out;++ // The chosen height isn't offered (a reroute left it out): the nearest below, said so.+ let (p, files, _o) = download_as(+ me,+ "unavailable",+ &none,+ "bv*[height=1080]+ba/b[height=1080]",+ "Talk",+ );+ assert!(+ matches!(p.state, State::Done(_)),+ "unavailable: {:?}",+ p.state+ );+ assert_eq!(files, ["Talk.mp4"]);+ let log = log_of(&p);+ assert!(+ log.iter()+ .any(|t| t.starts_with("The chosen quality isn't offered")),+ "{log:?}"+ );+ assert!(+ log.iter().any(|t| t == "Downloaded 18 640x360 instead"),+ "{log:?}"+ );++ // A media server that stopped resolving: looked up again without it, then saved.+ let (p, files, _o) = download_as(me, "dns-once", &none, "b", "Talk");+ assert!(matches!(p.state, State::Done(_)), "dns: {:?}", p.state);+ assert_eq!(files, ["Talk.mp4"]);+ let log = log_of(&p);+ assert!(+ log.iter().any(|t| t+ == "The server rr1---sn-dead.googlevideo.com couldn't be reached; looking the page up again without it"),+ "{log:?}"+ );}fn checks(me: &Path) {