Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Video downloads: Stop ends yt-dlp and everything it started (#61) (#64)

Ahmed Nefzaoui6595690931f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1319d3bd..72757c79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -131,6 +131,11 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **Stopping a video download left yt-dlp downloading in the background** on Windows
+ ([#61](https://github.com/anefzaoui/misterdownloadmanager/issues/61)): `yt-dlp.exe` starts a
+ second process that does the work, and only the first was ended. Resuming then failed ("yt-dlp
+ did not provide information") and a new try crawled, sharing the line with the old one. Each
+ helper now runs in a job of its own that Stop ends whole.
- **Linux: menus opened in the middle of the screen** in a Wayland session
([#50](https://github.com/anefzaoui/misterdownloadmanager/issues/50)): Wayland lets no program
place its windows, and MDM's menus and drop-down lists are windows it places. MDM now runs
diff --git a/crates/tools/src/proc.rs b/crates/tools/src/proc.rs
index 3cdd1550..ba269555 100644
--- a/crates/tools/src/proc.rs
+++ b/crates/tools/src/proc.rs
@@ -162,17 +162,15 @@ pub fn ytdlp_info(
Ok(cmd)
}
-/// The one job every child joins; it lives as long as the process (dropping it would kill
-/// them).
+/// A job of its own for one helper and every process it starts (#61): on Windows `yt-dlp.exe`
+/// is a launcher whose child does the work, and ffmpeg runs under that child. Closing the job
+/// (`Spawned::kill`, or MDM ending in any way) ends them all; ending the launcher alone left the
+/// download running, holding its file and the bandwidth.
#[cfg(windows)]
-fn job() -> Option<&'static win32job::Job> {
- static JOB: std::sync::OnceLock<Option<win32job::Job>> = std::sync::OnceLock::new();
- JOB.get_or_init(|| {
- let mut info = win32job::ExtendedLimitInfo::new();
- info.limit_kill_on_job_close();
- win32job::Job::create_with_limit_info(&info).ok()
- })
- .as_ref()
+fn new_job() -> Option<win32job::Job> {
+ let mut info = win32job::ExtendedLimitInfo::new();
+ info.limit_kill_on_job_close();
+ win32job::Job::create_with_limit_info(&info).ok()
}
/// A running helper with its stderr tail.
@@ -180,9 +178,19 @@ pub struct Spawned {
pub child: Child,
tail: Arc<Mutex<VecDeque<String>>>,
name: String,
+ #[cfg(windows)]
+ job: Option<win32job::Job>,
}
impl Spawned {
+ /// End the helper and everything it started (Windows: its job; elsewhere yt-dlp runs as one
+ /// process, its ffmpeg ending with it).
+ pub fn kill(&mut self) {
+ let _ = self.child.kill();
+ #[cfg(windows)]
+ drop(self.job.take());
+ }
+
/// The last stderr lines, for an error message.
pub fn tail(&self) -> String {
self.tail
@@ -227,10 +235,10 @@ pub fn spawn(mut cmd: Command, name: &str) -> Result<Spawned, ProcError> {
.spawn()
.map_err(|e| ProcError::Start(name.to_owned(), e))?;
#[cfg(windows)]
- if let Some(job) = job() {
+ let job = new_job().filter(|job| {
use std::os::windows::io::AsRawHandle;
- let _ = job.assign_process(child.as_raw_handle() as isize);
- }
+ job.assign_process(child.as_raw_handle() as isize).is_ok()
+ });
let tail = Arc::new(Mutex::new(VecDeque::new()));
if let Some(err) = child.stderr.take() {
let tail = tail.clone();
@@ -248,6 +256,8 @@ pub fn spawn(mut cmd: Command, name: &str) -> Result<Spawned, ProcError> {
child,
tail,
name: name.to_owned(),
+ #[cfg(windows)]
+ job,
})
}
@@ -274,7 +284,7 @@ pub fn output(cmd: Command, name: &str, timeout: Duration) -> Result<Vec<u8>, Pr
};
}
Ok(None) if Instant::now() >= deadline => {
- let _ = s.child.kill();
+ s.kill();
let _ = s.child.wait();
return Err(ProcError::Timeout(name.to_owned()));
}
@@ -371,4 +381,43 @@ mod tests {
let err = output(slow, "cmd", Duration::from_millis(500)).unwrap_err();
assert!(matches!(err, ProcError::Timeout(_)), "{err}");
}
+
+ /// #61: killing a helper ends what it started too (yt-dlp.exe is a launcher whose child
+ /// downloads). Here a script starts a child that writes a line every second: once killed,
+ /// the file stops growing.
+ #[cfg(windows)]
+ #[test]
+ fn killing_a_helper_ends_its_children() {
+ let dir = tempfile::tempdir().unwrap();
+ let marker = dir.path().join("marker.txt");
+ let child = dir.path().join("child.cmd");
+ let parent = dir.path().join("parent.cmd");
+ std::fs::write(
+ &child,
+ format!(
+ "@for /l %%i in (1,1,60) do @(echo x>>\"{}\" & ping -n 2 127.0.0.1 >nul)\r\n",
+ marker.display()
+ ),
+ )
+ .unwrap();
+ std::fs::write(
+ &parent,
+ format!(
+ "@start \"\" /b cmd /c \"{}\"\r\n@ping -n 60 127.0.0.1 >nul\r\n",
+ child.display()
+ ),
+ )
+ .unwrap();
+ let mut cmd = Command::new("cmd");
+ cmd.arg("/C").arg(&parent);
+ let mut s = spawn(cmd, "cmd").unwrap();
+ let size = || std::fs::metadata(&marker).map_or(0, |m| m.len());
+ std::thread::sleep(Duration::from_secs(3));
+ assert!(size() > 0, "the child runs");
+ s.kill();
+ std::thread::sleep(Duration::from_millis(1500));
+ let after_kill = size();
+ std::thread::sleep(Duration::from_secs(3));
+ assert_eq!(size(), after_kill, "the child ended with the helper");
+ }
}
diff --git a/crates/tools/src/video.rs b/crates/tools/src/video.rs
index 73a7edea..78715b3c 100644
--- a/crates/tools/src/video.rs
+++ b/crates/tools/src/video.rs
@@ -401,7 +401,7 @@ impl VideoJob {
pub fn stop(&self) {
self.progress.lock().unwrap().state = State::Stopped;
if let Some(s) = self.child.lock().unwrap().as_mut() {
- let _ = s.child.kill();
+ s.kill();
}
}
}
@@ -452,6 +452,69 @@ mod tests {
);
}
+ /// Live (#61): `MDM_LIVE_YTDLP=<yt-dlp.exe> MDM_LIVE_SLOW=<a slow file's address>
+ /// cargo test -p mdm-tools live_stop -- --ignored --nocapture` (the lab server:
+ /// `/gen/20M/clip.mp4?rate=50K`). Stopping a video download ends every yt-dlp process it
+ /// started (Windows: the launcher and its child), and the part file stops growing.
+ #[test]
+ #[ignore]
+ fn live_stop_ends_every_process() {
+ let exe = PathBuf::from(std::env::var("MDM_LIVE_YTDLP").expect("MDM_LIVE_YTDLP"));
+ let url = std::env::var("MDM_LIVE_SLOW").expect("MDM_LIVE_SLOW");
+ let dir = tempfile::tempdir().unwrap();
+ let job = VideoJob::start(
+ &exe,
+ &url,
+ "b",
+ dir.path(),
+ "clip",
+ None,
+ None,
+ None,
+ &Default::default(),
+ )
+ .unwrap();
+ let size = || {
+ std::fs::read_dir(dir.path())
+ .unwrap()
+ .filter_map(Result::ok)
+ .map(|e| e.metadata().map_or(0, |m| m.len()))
+ .sum::<u64>()
+ };
+ std::thread::sleep(std::time::Duration::from_secs(8));
+ println!("before stop: {} bytes, {:?}", size(), job.progress().state);
+ job.stop();
+ std::thread::sleep(std::time::Duration::from_secs(3));
+ let stopped = size();
+ std::thread::sleep(std::time::Duration::from_secs(4));
+ println!("after stop: {stopped} then {} bytes", size());
+ assert_eq!(size(), stopped, "nothing downloads after Stop");
+ // Started again: it continues the same part file (nothing else holds it now).
+ let again = VideoJob::start(
+ &exe,
+ &url,
+ "b",
+ dir.path(),
+ "clip",
+ None,
+ None,
+ None,
+ &Default::default(),
+ )
+ .unwrap();
+ std::thread::sleep(std::time::Duration::from_secs(8));
+ // yt-dlp's own count (a file open in another process shows a stale size on Windows).
+ let p = again.progress();
+ println!("resumed: yt-dlp at {} bytes, {:?}", p.downloaded, p.state);
+ assert!(p.downloaded > stopped, "it went on from where it stopped");
+ assert!(
+ !matches!(p.state, State::Failed(_)),
+ "resumed without an error: {:?}",
+ p.state
+ );
+ again.stop();
+ }
+
fn run(expected: Option<u64>, lines: &[&str]) -> Vec<(u64, Option<u64>)> {
let mut m = Meter::new(expected);
let mut p = Progress {